blob: 0c17c75fceb29d4417bd6630335602f301ed08a8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Chris Lattnere7a2e912008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattnere7a2e912008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattnere7a2e912008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattnere7a2e912008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattnere7a2e912008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner05faf172008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattnere7a2e912008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000102
Chris Lattnere7a2e912008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
120 if (!isCompAssign) {
121 ImpCastExprToType(lhsExpr, destType);
122 ImpCastExprToType(rhsExpr, destType);
123 }
124 return destType;
125}
126
127QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
128 // Perform the usual unary conversions. We do this early so that
129 // integral promotions to "int" can allow us to exit early, in the
130 // lhs == rhs check. Also, for conversion purposes, we ignore any
131 // qualifiers. For example, "const float" and "float" are
132 // equivalent.
Douglas Gregorbf3af052008-11-13 20:12:29 +0000133 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
134 else lhs = lhs.getUnqualifiedType();
135 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
136 else rhs = rhs.getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000137
Chris Lattnere7a2e912008-07-25 21:10:04 +0000138 // If both types are identical, no conversion is needed.
139 if (lhs == rhs)
140 return lhs;
141
142 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
143 // The caller can deal with this (e.g. pointer + int).
144 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
145 return lhs;
146
147 // At this point, we have two different arithmetic types.
148
149 // Handle complex types first (C99 6.3.1.8p1).
150 if (lhs->isComplexType() || rhs->isComplexType()) {
151 // if we have an integer operand, the result is the complex type.
152 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
153 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000154 return lhs;
155 }
156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
157 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000158 return rhs;
159 }
160 // This handles complex/complex, complex/float, or float/complex.
161 // When both operands are complex, the shorter operand is converted to the
162 // type of the longer, and that is the type of the result. This corresponds
163 // to what is done when combining two real floating-point operands.
164 // The fun begins when size promotion occur across type domains.
165 // From H&S 6.3.4: When one operand is complex and the other is a real
166 // floating-point type, the less precise type is converted, within it's
167 // real or complex domain, to the precision of the other type. For example,
168 // when combining a "long double" with a "double _Complex", the
169 // "double _Complex" is promoted to "long double _Complex".
170 int result = Context.getFloatingTypeOrder(lhs, rhs);
171
172 if (result > 0) { // The left side is bigger, convert rhs.
173 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000176 }
177 // At this point, lhs and rhs have the same rank/size. Now, make sure the
178 // domains match. This is a requirement for our implementation, C99
179 // does not require this promotion.
180 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
181 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000184 return lhs;
185 }
186 }
187 return lhs; // The domain/size match exactly.
188 }
189 // Now handle "real" floating types (i.e. float, double, long double).
190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
191 // if we have an integer operand, the result is the real floating type.
192 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
193 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000194 return lhs;
195 }
196 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
197 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000198 return rhs;
199 }
200 // We have two real floating types, float/complex combos were handled above.
201 // Convert the smaller operand to the bigger result.
202 int result = Context.getFloatingTypeOrder(lhs, rhs);
203
204 if (result > 0) { // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000205 return lhs;
206 }
207 if (result < 0) { // convert the lhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000208 return rhs;
209 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000210 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattnere7a2e912008-07-25 21:10:04 +0000211 }
212 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
213 // Handle GCC complex int extension.
214 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
215 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
216
217 if (lhsComplexInt && rhsComplexInt) {
218 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
219 rhsComplexInt->getElementType()) >= 0) {
220 // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000221 return lhs;
222 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000223 return rhs;
224 } else if (lhsComplexInt && rhs->isIntegerType()) {
225 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000226 return lhs;
227 } else if (rhsComplexInt && lhs->isIntegerType()) {
228 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000229 return rhs;
230 }
231 }
232 // Finally, we have two differing integer types.
233 // The rules for this case are in C99 6.3.1.8
234 int compare = Context.getIntegerTypeOrder(lhs, rhs);
235 bool lhsSigned = lhs->isSignedIntegerType(),
236 rhsSigned = rhs->isSignedIntegerType();
237 QualType destType;
238 if (lhsSigned == rhsSigned) {
239 // Same signedness; use the higher-ranked type
240 destType = compare >= 0 ? lhs : rhs;
241 } else if (compare != (lhsSigned ? 1 : -1)) {
242 // The unsigned type has greater than or equal rank to the
243 // signed type, so use the unsigned type
244 destType = lhsSigned ? rhs : lhs;
245 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
246 // The two types are different widths; if we are here, that
247 // means the signed type is larger than the unsigned type, so
248 // use the signed type.
249 destType = lhsSigned ? lhs : rhs;
250 } else {
251 // The signed type is higher-ranked than the unsigned type,
252 // but isn't actually any bigger (like unsigned int and long
253 // on most 32-bit systems). Use the unsigned type corresponding
254 // to the signed type.
255 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
256 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000257 return destType;
258}
259
260//===----------------------------------------------------------------------===//
261// Semantic Analysis for various Expression Types
262//===----------------------------------------------------------------------===//
263
264
Steve Narofff69936d2007-09-16 03:34:24 +0000265/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000266/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
267/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
268/// multiple tokens. However, the common case is that StringToks points to one
269/// string.
270///
271Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000272Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 assert(NumStringToks && "Must have at least one string!");
274
275 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
276 if (Literal.hadError)
277 return ExprResult(true);
278
279 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
280 for (unsigned i = 0; i != NumStringToks; ++i)
281 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000282
283 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000284 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000285 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
286 << SourceRange(StringToks[0].getLocation(),
287 StringToks[NumStringToks-1].getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000288
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000289 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000290 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000291 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000292
293 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
294 if (getLangOptions().CPlusPlus)
295 StrTy.addConst();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000296
297 // Get an array type for the string, according to C99 6.4.5. This includes
298 // the nul terminator character as well as the string length for pascal
299 // strings.
300 StrTy = Context.getConstantArrayType(StrTy,
301 llvm::APInt(32, Literal.GetStringLength()+1),
302 ArrayType::Normal, 0);
303
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
305 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000306 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000307 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 StringToks[NumStringToks-1].getLocation());
309}
310
Chris Lattner639e2d32008-10-20 05:16:36 +0000311/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
312/// CurBlock to VD should cause it to be snapshotted (as we do for auto
313/// variables defined outside the block) or false if this is not needed (e.g.
314/// for values inside the block or for globals).
315///
316/// FIXME: This will create BlockDeclRefExprs for global variables,
317/// function references, etc which is suboptimal :) and breaks
318/// things like "integer constant expression" tests.
319static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
320 ValueDecl *VD) {
321 // If the value is defined inside the block, we couldn't snapshot it even if
322 // we wanted to.
323 if (CurBlock->TheDecl == VD->getDeclContext())
324 return false;
325
326 // If this is an enum constant or function, it is constant, don't snapshot.
327 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
328 return false;
329
330 // If this is a reference to an extern, static, or global variable, no need to
331 // snapshot it.
332 // FIXME: What about 'const' variables in C++?
333 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
334 return Var->hasLocalStorage();
335
336 return true;
337}
338
339
340
Steve Naroff08d92e42007-09-15 18:49:24 +0000341/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000342/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000343/// identifier is used in a function call context.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000344/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
345/// class or namespace that the identifier must be a member of.
Steve Naroff08d92e42007-09-15 18:49:24 +0000346Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 IdentifierInfo &II,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000348 bool HasTrailingLParen,
349 const CXXScopeSpec *SS) {
Douglas Gregor10c42622008-11-18 15:03:34 +0000350 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
351}
352
353/// ActOnDeclarationNameExpr - The parser has read some kind of name
354/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
355/// performs lookup on that name and returns an expression that refers
356/// to that name. This routine isn't directly called from the parser,
357/// because the parser doesn't know about DeclarationName. Rather,
358/// this routine is called by ActOnIdentifierExpr,
359/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
360/// which form the DeclarationName from the corresponding syntactic
361/// forms.
362///
363/// HasTrailingLParen indicates whether this identifier is used in a
364/// function call context. LookupCtx is only used for a C++
365/// qualified-id (foo::bar) to indicate the class or namespace that
366/// the identifier must be a member of.
367Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
368 DeclarationName Name,
369 bool HasTrailingLParen,
370 const CXXScopeSpec *SS) {
Chris Lattner8a934232008-03-31 00:36:02 +0000371 // Could be enum-constant, value decl, instance variable, etc.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000372 Decl *D;
373 if (SS && !SS->isEmpty()) {
374 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
375 if (DC == 0)
376 return true;
Douglas Gregor10c42622008-11-18 15:03:34 +0000377 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000378 } else
Douglas Gregor10c42622008-11-18 15:03:34 +0000379 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Chris Lattner8a934232008-03-31 00:36:02 +0000380
381 // If this reference is in an Objective-C method, then ivar lookup happens as
382 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000383 IdentifierInfo *II = Name.getAsIdentifierInfo();
384 if (II && getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000385 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-03-31 00:36:02 +0000386 // There are two cases to handle here. 1) scoped lookup could have failed,
387 // in which case we should look for an ivar. 2) scoped lookup could have
388 // found a decl, but that decl is outside the current method (i.e. a global
389 // variable). In these two cases, we do a lookup for an ivar with this
390 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe8043c32008-04-01 23:04:06 +0000391 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000392 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregor10c42622008-11-18 15:03:34 +0000393 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000394 // FIXME: This should use a new expr for a direct reference, don't turn
395 // this into Self->ivar, just return a BareIVarExpr or something.
396 IdentifierInfo &II = Context.Idents.get("self");
397 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
398 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
399 static_cast<Expr*>(SelfExpr.Val), true, true);
400 }
401 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000402 // Needed to implement property "super.method" notation.
Chris Lattner84692652008-11-20 05:35:30 +0000403 if (SD == 0 && II->isStr("super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000404 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000405 getCurMethodDecl()->getClassInterface()));
Douglas Gregorcd9b46e2008-11-04 14:56:14 +0000406 return new ObjCSuperExpr(Loc, T);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000407 }
Chris Lattner8a934232008-03-31 00:36:02 +0000408 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 if (D == 0) {
410 // Otherwise, this could be an implicitly declared function reference (legal
411 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000412 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000413 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000414 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 else {
416 // If this name wasn't predeclared and if this is not a function call,
417 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000418 if (SS && !SS->isEmpty())
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000419 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattner08631c52008-11-23 21:45:46 +0000420 << Name << SS->getRange();
Douglas Gregor10c42622008-11-18 15:03:34 +0000421 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
422 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000423 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000424 else
Chris Lattner08631c52008-11-23 21:45:46 +0000425 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 }
427 }
Chris Lattner8a934232008-03-31 00:36:02 +0000428
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000429 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
430 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
431 if (MD->isStatic())
432 // "invalid use of member 'x' in static member function"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000433 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000434 << FD->getDeclName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000435 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
436 // "invalid use of nonstatic data member 'x'"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000437 return Diag(Loc, diag::err_invalid_non_static_member_use)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000438 << FD->getDeclName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000439
440 if (FD->isInvalidDecl())
441 return true;
442
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +0000443 // FIXME: Handle 'mutable'.
444 return new DeclRefExpr(FD,
445 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000446 }
447
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000448 return Diag(Loc, diag::err_invalid_non_static_member_use)
449 << FD->getDeclName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000450 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 if (isa<TypedefDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000452 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000453 if (isa<ObjCInterfaceDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000454 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000455 if (isa<NamespaceDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000456 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Reid Spencer5f016e22007-07-11 17:01:13 +0000457
Steve Naroffdd972f22008-09-05 22:11:13 +0000458 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000459 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
460 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
461
Steve Naroffdd972f22008-09-05 22:11:13 +0000462 ValueDecl *VD = cast<ValueDecl>(D);
463
464 // check if referencing an identifier with __attribute__((deprecated)).
465 if (VD->getAttr<DeprecatedAttr>())
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000466 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Steve Naroffdd972f22008-09-05 22:11:13 +0000467
468 // Only create DeclRefExpr's for valid Decl's.
469 if (VD->isInvalidDecl())
470 return true;
Chris Lattner639e2d32008-10-20 05:16:36 +0000471
472 // If the identifier reference is inside a block, and it refers to a value
473 // that is outside the block, create a BlockDeclRefExpr instead of a
474 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
475 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000476 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000477 // We do not do this for things like enum constants, global variables, etc,
478 // as they do not get snapshotted.
479 //
480 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000481 // The BlocksAttr indicates the variable is bound by-reference.
482 if (VD->getAttr<BlocksAttr>())
Douglas Gregor9d293df2008-10-28 00:22:11 +0000483 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
484 Loc, true);
Steve Naroff090276f2008-10-10 01:28:17 +0000485
486 // Variable will be bound by-copy, make it const within the closure.
487 VD->getType().addConst();
Douglas Gregor9d293df2008-10-28 00:22:11 +0000488 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
489 Loc, false);
Steve Naroff090276f2008-10-10 01:28:17 +0000490 }
491 // If this reference is not in a block or if the referenced variable is
492 // within the block, create a normal DeclRefExpr.
Douglas Gregore0a5d5f2008-10-22 04:14:44 +0000493 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000494}
495
Chris Lattnerd9f69102008-08-10 01:53:14 +0000496Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000497 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000498 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000499
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000501 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000502 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
503 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
504 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000506
507 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000508 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000509 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000510
Chris Lattnerfa28b302008-01-12 08:14:25 +0000511 // Pre-defined identifiers are of type char[x], where x is the length of the
512 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000513 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000514 if (getCurFunctionDecl())
515 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000516 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000517 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000518
Chris Lattner8f978d52008-01-12 19:32:28 +0000519 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000520 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000521 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000522 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000523}
524
Steve Narofff69936d2007-09-16 03:34:24 +0000525Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000526 llvm::SmallString<16> CharBuffer;
527 CharBuffer.resize(Tok.getLength());
528 const char *ThisTokBegin = &CharBuffer[0];
529 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
530
531 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
532 Tok.getLocation(), PP);
533 if (Literal.hadError())
534 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000535
536 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
537
Chris Lattnerc250aae2008-06-07 22:35:38 +0000538 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
539 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000540}
541
Steve Narofff69936d2007-09-16 03:34:24 +0000542Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 // fast path for a single digit (which is quite common). A single digit
544 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
545 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000546 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000547
Chris Lattner98be4942008-03-05 18:54:05 +0000548 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000549 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 Context.IntTy,
551 Tok.getLocation()));
552 }
553 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000554 // Add padding so that NumericLiteralParser can overread by one character.
555 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 const char *ThisTokBegin = &IntegerBuffer[0];
557
558 // Get the spelling of the token, which eliminates trigraphs, etc.
559 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner28997ec2008-09-30 20:51:14 +0000560
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
562 Tok.getLocation(), PP);
563 if (Literal.hadError)
564 return ExprResult(true);
565
Chris Lattner5d661452007-08-26 03:42:43 +0000566 Expr *Res;
567
568 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000569 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000570 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000571 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000572 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000573 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000574 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000575 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000576
577 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
578
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000579 // isExact will be set by GetFloatValue().
580 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000581 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000582 Ty, Tok.getLocation());
583
Chris Lattner5d661452007-08-26 03:42:43 +0000584 } else if (!Literal.isIntegerLiteral()) {
585 return ExprResult(true);
586 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000587 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000588
Neil Boothb9449512007-08-29 22:00:19 +0000589 // long long is a C99 feature.
590 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000591 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000592 Diag(Tok.getLocation(), diag::ext_longlong);
593
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000595 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000596
597 if (Literal.GetIntegerValue(ResultVal)) {
598 // If this value didn't fit into uintmax_t, warn and force to ull.
599 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000600 Ty = Context.UnsignedLongLongTy;
601 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000602 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000603 } else {
604 // If this value fits into a ULL, try to figure out what else it fits into
605 // according to the rules of C99 6.4.4.1p5.
606
607 // Octal, Hexadecimal, and integers with a U suffix are allowed to
608 // be an unsigned int.
609 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
610
611 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000612 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000613 if (!Literal.isLong && !Literal.isLongLong) {
614 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000615 unsigned IntSize = Context.Target.getIntWidth();
616
Reid Spencer5f016e22007-07-11 17:01:13 +0000617 // Does it fit in a unsigned int?
618 if (ResultVal.isIntN(IntSize)) {
619 // Does it fit in a signed int?
620 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000621 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000623 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000624 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000626 }
627
628 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000629 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000630 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000631
632 // Does it fit in a unsigned long?
633 if (ResultVal.isIntN(LongSize)) {
634 // Does it fit in a signed long?
635 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000636 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000637 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000638 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000639 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 }
642
643 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000644 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000645 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000646
647 // Does it fit in a unsigned long long?
648 if (ResultVal.isIntN(LongLongSize)) {
649 // Does it fit in a signed long long?
650 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000651 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000653 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000654 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000655 }
656 }
657
658 // If we still couldn't decide a type, we probably have something that
659 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000660 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000661 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000662 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000663 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000665
666 if (ResultVal.getBitWidth() != Width)
667 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 }
669
Chris Lattnerf0467b32008-04-02 04:24:33 +0000670 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 }
Chris Lattner5d661452007-08-26 03:42:43 +0000672
673 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
674 if (Literal.isImaginary)
675 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
676
677 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000678}
679
Steve Narofff69936d2007-09-16 03:34:24 +0000680Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000681 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000682 Expr *E = (Expr *)Val;
683 assert((E != 0) && "ActOnParenExpr() missing expr");
684 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000685}
686
687/// The UsualUnaryConversions() function is *not* called by this routine.
688/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +0000689bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
690 SourceLocation OpLoc,
691 const SourceRange &ExprRange,
692 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000693 // C99 6.5.3.4p1:
694 if (isa<FunctionType>(exprType) && isSizeof)
695 // alignof(function) is allowed.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000696 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 else if (exprType->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000698 Diag(OpLoc, diag::ext_sizeof_void_type)
699 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
700 else if (exprType->isIncompleteType())
701 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
702 diag::err_alignof_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000703 << exprType << ExprRange;
Sebastian Redl05189992008-11-11 17:56:53 +0000704
705 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000706}
707
Sebastian Redl05189992008-11-11 17:56:53 +0000708/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
709/// the same for @c alignof and @c __alignof
710/// Note that the ArgRange is invalid if isType is false.
711Action::ExprResult
712Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
713 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 // If error parsing type, ignore.
Sebastian Redl05189992008-11-11 17:56:53 +0000715 if (TyOrEx == 0) return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000716
Sebastian Redl05189992008-11-11 17:56:53 +0000717 QualType ArgTy;
718 SourceRange Range;
719 if (isType) {
720 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
721 Range = ArgRange;
722 } else {
723 // Get the end location.
724 Expr *ArgEx = (Expr *)TyOrEx;
725 Range = ArgEx->getSourceRange();
726 ArgTy = ArgEx->getType();
727 }
728
729 // Verify that the operand is valid.
730 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 return true;
Sebastian Redl05189992008-11-11 17:56:53 +0000732
733 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
734 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
735 OpLoc, Range.getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +0000736}
737
Chris Lattner5d794252007-08-24 21:41:10 +0000738QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000739 DefaultFunctionArrayConversion(V);
740
Chris Lattnercc26ed72007-08-26 05:39:26 +0000741 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000742 if (const ComplexType *CT = V->getType()->getAsComplexType())
743 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000744
745 // Otherwise they pass through real integer and floating point types here.
746 if (V->getType()->isArithmeticType())
747 return V->getType();
748
749 // Reject anything else.
Chris Lattnerd1625842008-11-24 06:25:27 +0000750 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000751 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000752}
753
754
Reid Spencer5f016e22007-07-11 17:01:13 +0000755
Douglas Gregor74253732008-11-19 15:42:04 +0000756Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 tok::TokenKind Kind,
758 ExprTy *Input) {
Douglas Gregor74253732008-11-19 15:42:04 +0000759 Expr *Arg = (Expr *)Input;
760
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 UnaryOperator::Opcode Opc;
762 switch (Kind) {
763 default: assert(0 && "Unknown unary op!");
764 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
765 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
766 }
Douglas Gregor74253732008-11-19 15:42:04 +0000767
768 if (getLangOptions().CPlusPlus &&
769 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
770 // Which overloaded operator?
771 OverloadedOperatorKind OverOp =
772 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
773
774 // C++ [over.inc]p1:
775 //
776 // [...] If the function is a member function with one
777 // parameter (which shall be of type int) or a non-member
778 // function with two parameters (the second of which shall be
779 // of type int), it defines the postfix increment operator ++
780 // for objects of that type. When the postfix increment is
781 // called as a result of using the ++ operator, the int
782 // argument will have value zero.
783 Expr *Args[2] = {
784 Arg,
785 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
786 /*isSigned=*/true),
787 Context.IntTy, SourceLocation())
788 };
789
790 // Build the candidate set for overloading
791 OverloadCandidateSet CandidateSet;
792 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
793
794 // Perform overload resolution.
795 OverloadCandidateSet::iterator Best;
796 switch (BestViableFunction(CandidateSet, Best)) {
797 case OR_Success: {
798 // We found a built-in operator or an overloaded operator.
799 FunctionDecl *FnDecl = Best->Function;
800
801 if (FnDecl) {
802 // We matched an overloaded operator. Build a call to that
803 // operator.
804
805 // Convert the arguments.
806 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
807 if (PerformObjectArgumentInitialization(Arg, Method))
808 return true;
809 } else {
810 // Convert the arguments.
811 if (PerformCopyInitialization(Arg,
812 FnDecl->getParamDecl(0)->getType(),
813 "passing"))
814 return true;
815 }
816
817 // Determine the result type
818 QualType ResultTy
819 = FnDecl->getType()->getAsFunctionType()->getResultType();
820 ResultTy = ResultTy.getNonReferenceType();
821
822 // Build the actual expression node.
823 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
824 SourceLocation());
825 UsualUnaryConversions(FnExpr);
826
827 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
828 } else {
829 // We matched a built-in operator. Convert the arguments, then
830 // break out so that we will build the appropriate built-in
831 // operator node.
832 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
833 "passing"))
834 return true;
835
836 break;
837 }
838 }
839
840 case OR_No_Viable_Function:
841 // No viable function; fall through to handling this as a
842 // built-in operator, which will produce an error message for us.
843 break;
844
845 case OR_Ambiguous:
846 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
847 << UnaryOperator::getOpcodeStr(Opc)
848 << Arg->getSourceRange();
849 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
850 return true;
851 }
852
853 // Either we found no viable overloaded operator or we matched a
854 // built-in operator. In either case, fall through to trying to
855 // build a built-in operation.
856 }
857
858 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000859 if (result.isNull())
860 return true;
Douglas Gregor74253732008-11-19 15:42:04 +0000861 return new UnaryOperator(Arg, Opc, result, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000862}
863
864Action::ExprResult Sema::
Douglas Gregor337c6b92008-11-19 17:17:41 +0000865ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000867 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000868
Douglas Gregor337c6b92008-11-19 17:17:41 +0000869 if (getLangOptions().CPlusPlus &&
870 LHSExp->getType()->isRecordType() ||
871 LHSExp->getType()->isEnumeralType() ||
872 RHSExp->getType()->isRecordType() ||
873 RHSExp->getType()->isRecordType()) {
874 // Add the appropriate overloaded operators (C++ [over.match.oper])
875 // to the candidate set.
876 OverloadCandidateSet CandidateSet;
877 Expr *Args[2] = { LHSExp, RHSExp };
878 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
879
880 // Perform overload resolution.
881 OverloadCandidateSet::iterator Best;
882 switch (BestViableFunction(CandidateSet, Best)) {
883 case OR_Success: {
884 // We found a built-in operator or an overloaded operator.
885 FunctionDecl *FnDecl = Best->Function;
886
887 if (FnDecl) {
888 // We matched an overloaded operator. Build a call to that
889 // operator.
890
891 // Convert the arguments.
892 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
893 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
894 PerformCopyInitialization(RHSExp,
895 FnDecl->getParamDecl(0)->getType(),
896 "passing"))
897 return true;
898 } else {
899 // Convert the arguments.
900 if (PerformCopyInitialization(LHSExp,
901 FnDecl->getParamDecl(0)->getType(),
902 "passing") ||
903 PerformCopyInitialization(RHSExp,
904 FnDecl->getParamDecl(1)->getType(),
905 "passing"))
906 return true;
907 }
908
909 // Determine the result type
910 QualType ResultTy
911 = FnDecl->getType()->getAsFunctionType()->getResultType();
912 ResultTy = ResultTy.getNonReferenceType();
913
914 // Build the actual expression node.
915 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
916 SourceLocation());
917 UsualUnaryConversions(FnExpr);
918
919 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
920 } else {
921 // We matched a built-in operator. Convert the arguments, then
922 // break out so that we will build the appropriate built-in
923 // operator node.
924 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
925 "passing") ||
926 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
927 "passing"))
928 return true;
929
930 break;
931 }
932 }
933
934 case OR_No_Viable_Function:
935 // No viable function; fall through to handling this as a
936 // built-in operator, which will produce an error message for us.
937 break;
938
939 case OR_Ambiguous:
940 Diag(LLoc, diag::err_ovl_ambiguous_oper)
941 << "[]"
942 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
943 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
944 return true;
945 }
946
947 // Either we found no viable overloaded operator or we matched a
948 // built-in operator. In either case, fall through to trying to
949 // build a built-in operation.
950 }
951
Chris Lattner12d9ff62007-07-16 00:14:47 +0000952 // Perform default conversions.
953 DefaultFunctionArrayConversion(LHSExp);
954 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000955
Chris Lattner12d9ff62007-07-16 00:14:47 +0000956 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000957
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000959 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000960 // in the subscript position. As a result, we need to derive the array base
961 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000962 Expr *BaseExpr, *IndexExpr;
963 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000964 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000965 BaseExpr = LHSExp;
966 IndexExpr = RHSExp;
967 // FIXME: need to deal with const...
968 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000969 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000970 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000971 BaseExpr = RHSExp;
972 IndexExpr = LHSExp;
973 // FIXME: need to deal with const...
974 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000975 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
976 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000977 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000978
979 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000980 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
981 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000982 return Diag(LLoc, diag::err_ext_vector_component_access)
983 << SourceRange(LLoc, RLoc);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000984 // FIXME: need to deal with const...
985 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000986 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000987 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
988 << RHSExp->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 }
990 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000991 if (!IndexExpr->getType()->isIntegerType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000992 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
993 << IndexExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +0000994
Chris Lattner12d9ff62007-07-16 00:14:47 +0000995 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
996 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000997 // void (*)(int)) and pointers to incomplete types. Functions are not
998 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000999 if (!ResultType->isObjectType())
1000 return Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001001 diag::err_typecheck_subscript_not_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00001002 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner12d9ff62007-07-16 00:14:47 +00001003
1004 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001005}
1006
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001007QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001008CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001009 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001010 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001011
1012 // This flag determines whether or not the component is to be treated as a
1013 // special name, or a regular GLSL-style component access.
1014 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001015
1016 // The vector accessor can't exceed the number of elements.
1017 const char *compStr = CompName.getName();
1018 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001019 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattnerd1625842008-11-24 06:25:27 +00001020 << baseType << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001021 return QualType();
1022 }
Nate Begeman8a997642008-05-09 06:41:27 +00001023
1024 // Check that we've found one of the special components, or that the component
1025 // names must come from the same set.
1026 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1027 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1028 SpecialComponent = true;
1029 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001030 do
1031 compStr++;
1032 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1033 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1034 do
1035 compStr++;
1036 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1037 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1038 do
1039 compStr++;
1040 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1041 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001042
Nate Begeman8a997642008-05-09 06:41:27 +00001043 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001044 // We didn't get to the end of the string. This means the component names
1045 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001046 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1047 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001048 return QualType();
1049 }
1050 // Each component accessor can't exceed the vector type.
1051 compStr = CompName.getName();
1052 while (*compStr) {
1053 if (vecType->isAccessorWithinNumElements(*compStr))
1054 compStr++;
1055 else
1056 break;
1057 }
Nate Begeman8a997642008-05-09 06:41:27 +00001058 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001059 // We didn't get to the end of the string. This means a component accessor
1060 // exceeds the number of elements in the vector.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001061 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattnerd1625842008-11-24 06:25:27 +00001062 << baseType << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001063 return QualType();
1064 }
Nate Begeman8a997642008-05-09 06:41:27 +00001065
1066 // If we have a special component name, verify that the current vector length
1067 // is an even number, since all special component names return exactly half
1068 // the elements.
1069 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001070 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001071 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001072 return QualType();
1073 }
1074
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001075 // The component accessor looks fine - now we need to compute the actual type.
1076 // The vector type is implied by the component accessor. For example,
1077 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001078 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1079 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner3c73c412008-11-19 08:23:25 +00001080 : CompName.getLength();
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001081 if (CompSize == 1)
1082 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001083
Nate Begeman213541a2008-04-18 23:10:10 +00001084 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001085 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001086 // diagostics look bad. We want extended vector types to appear built-in.
1087 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1088 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1089 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001090 }
1091 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001092}
1093
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001094/// constructSetterName - Return the setter name for the given
1095/// identifier, i.e. "set" + Name where the initial character of Name
1096/// has been capitalized.
1097// FIXME: Merge with same routine in Parser. But where should this
1098// live?
1099static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1100 const IdentifierInfo *Name) {
1101 llvm::SmallString<100> SelectorName;
1102 SelectorName = "set";
1103 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1104 SelectorName[3] = toupper(SelectorName[3]);
1105 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1106}
1107
Reid Spencer5f016e22007-07-11 17:01:13 +00001108Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001109ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001110 tok::TokenKind OpKind, SourceLocation MemberLoc,
1111 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001112 Expr *BaseExpr = static_cast<Expr *>(Base);
1113 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001114
1115 // Perform default conversions.
1116 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001117
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001118 QualType BaseType = BaseExpr->getType();
1119 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001120
Chris Lattner68a057b2008-07-21 04:36:39 +00001121 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1122 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001124 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001125 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001126 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1127 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001128 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001129 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00001130 << BaseType << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001132
Chris Lattner68a057b2008-07-21 04:36:39 +00001133 // Handle field access to simple records. This also handles access to fields
1134 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001135 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001136 RecordDecl *RDecl = RTy->getDecl();
1137 if (RTy->isIncompleteType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001138 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001139 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001140 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001141 FieldDecl *MemberDecl = RDecl->getMember(&Member);
1142 if (!MemberDecl)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001143 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner3c73c412008-11-19 08:23:25 +00001144 << &Member << BaseExpr->getSourceRange();
Eli Friedman51019072008-02-06 22:48:16 +00001145
1146 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +00001147 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +00001148 QualType MemberType = MemberDecl->getType();
1149 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +00001150 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Sebastian Redla11f42f2008-11-17 23:24:37 +00001151 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) {
1152 if (CXXMember->isMutable())
1153 combinedQualifiers &= ~QualType::Const;
1154 }
Eli Friedman51019072008-02-06 22:48:16 +00001155 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1156
Chris Lattner68a057b2008-07-21 04:36:39 +00001157 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +00001158 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001159 }
1160
Chris Lattnera38e6b12008-07-21 04:59:05 +00001161 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1162 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001163 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1164 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001165 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001166 OpKind == tok::arrow);
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001167 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001168 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001169 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001170 }
1171
Chris Lattnera38e6b12008-07-21 04:59:05 +00001172 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1173 // pointer to a (potentially qualified) interface type.
1174 const PointerType *PTy;
1175 const ObjCInterfaceType *IFTy;
1176 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1177 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1178 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001179
Daniel Dunbar2307d312008-09-03 01:05:41 +00001180 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001181 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1182 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1183
Daniel Dunbar2307d312008-09-03 01:05:41 +00001184 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001185 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1186 E = IFTy->qual_end(); I != E; ++I)
1187 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1188 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001189
1190 // If that failed, look for an "implicit" property by seeing if the nullary
1191 // selector is implemented.
1192
1193 // FIXME: The logic for looking up nullary and unary selectors should be
1194 // shared with the code in ActOnInstanceMessage.
1195
1196 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1197 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1198
1199 // If this reference is in an @implementation, check for 'private' methods.
1200 if (!Getter)
1201 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1202 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1203 if (ObjCImplementationDecl *ImpDecl =
1204 ObjCImplementations[ClassDecl->getIdentifier()])
1205 Getter = ImpDecl->getInstanceMethod(Sel);
1206
Steve Naroff7692ed62008-10-22 19:16:27 +00001207 // Look through local category implementations associated with the class.
1208 if (!Getter) {
1209 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1210 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1211 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1212 }
1213 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001214 if (Getter) {
1215 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001216 // will look for the matching setter, in case it is needed.
1217 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1218 &Member);
1219 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1220 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1221 if (!Setter) {
1222 // If this reference is in an @implementation, also check for 'private'
1223 // methods.
1224 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1225 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1226 if (ObjCImplementationDecl *ImpDecl =
1227 ObjCImplementations[ClassDecl->getIdentifier()])
1228 Setter = ImpDecl->getInstanceMethod(SetterSel);
1229 }
1230 // Look through local category implementations associated with the class.
1231 if (!Setter) {
1232 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1233 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1234 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1235 }
1236 }
1237
1238 // FIXME: we must check that the setter has property type.
1239 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00001240 MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001241 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001242 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001243 // Handle properties on qualified "id" protocols.
1244 const ObjCQualifiedIdType *QIdTy;
1245 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1246 // Check protocols on qualified interfaces.
1247 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1248 E = QIdTy->qual_end(); I != E; ++I)
1249 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1250 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1251 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001252 // Handle 'field access' to vectors, such as 'V.xx'.
1253 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1254 // Component access limited to variables (reject vec4.rg.g).
1255 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1256 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001257 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1258 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001259 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1260 if (ret.isNull())
1261 return true;
1262 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1263 }
1264
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001265 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattnerd1625842008-11-24 06:25:27 +00001266 << BaseType << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001267}
1268
Steve Narofff69936d2007-09-16 03:34:24 +00001269/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001270/// This provides the location of the left/right parens and a list of comma
1271/// locations.
1272Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001273ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001274 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001276 Expr *Fn = static_cast<Expr *>(fn);
1277 Expr **Args = reinterpret_cast<Expr**>(args);
1278 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001279 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001280 OverloadedFunctionDecl *Ovl = NULL;
1281
1282 // If we're directly calling a function or a set of overloaded
1283 // functions, get the appropriate declaration.
1284 {
1285 DeclRefExpr *DRExpr = NULL;
1286 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1287 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1288 else
1289 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1290
1291 if (DRExpr) {
1292 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1293 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1294 }
1295 }
1296
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001297 if (Ovl) {
Douglas Gregor0a396682008-11-26 06:01:48 +00001298 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1299 RParenLoc);
1300 if (!FDecl)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001301 return true;
1302
Douglas Gregor0a396682008-11-26 06:01:48 +00001303 // Update Fn to refer to the actual function selected.
1304 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1305 Fn->getSourceRange().getBegin());
1306 Fn->Destroy(Context);
1307 Fn = NewFn;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001308 }
Chris Lattner04421082008-04-08 04:40:51 +00001309
Douglas Gregorf9eb9052008-11-19 21:05:33 +00001310 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1311 return BuildCallToObjectOfClassType(Fn, LParenLoc, Args, NumArgs,
1312 CommaLocs, RParenLoc);
1313
Chris Lattner04421082008-04-08 04:40:51 +00001314 // Promote the function operand.
1315 UsualUnaryConversions(Fn);
1316
Chris Lattner925e60d2007-12-28 05:29:59 +00001317 // Make the call expr early, before semantic checks. This guarantees cleanup
1318 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001319 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001320 Context.BoolTy, RParenLoc));
Steve Naroffdd972f22008-09-05 22:11:13 +00001321 const FunctionType *FuncT;
1322 if (!Fn->getType()->isBlockPointerType()) {
1323 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1324 // have type pointer to function".
1325 const PointerType *PT = Fn->getType()->getAsPointerType();
1326 if (PT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001327 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerd1625842008-11-24 06:25:27 +00001328 << Fn->getType() << Fn->getSourceRange();
Steve Naroffdd972f22008-09-05 22:11:13 +00001329 FuncT = PT->getPointeeType()->getAsFunctionType();
1330 } else { // This is a block call.
1331 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1332 getAsFunctionType();
1333 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001334 if (FuncT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001335 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerd1625842008-11-24 06:25:27 +00001336 << Fn->getType() << Fn->getSourceRange();
Chris Lattner925e60d2007-12-28 05:29:59 +00001337
1338 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001339 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001340
Chris Lattner925e60d2007-12-28 05:29:59 +00001341 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1343 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001344 unsigned NumArgsInProto = Proto->getNumArgs();
1345 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001346
Chris Lattner04421082008-04-08 04:40:51 +00001347 // If too few arguments are available (and we don't have default
1348 // arguments for the remaining parameters), don't make the call.
1349 if (NumArgs < NumArgsInProto) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001350 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1351 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1352 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1353 // Use default arguments for missing arguments
1354 NumArgsToCheck = NumArgsInProto;
1355 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001356 }
1357
Chris Lattner925e60d2007-12-28 05:29:59 +00001358 // If too many are passed and not variadic, error on the extras and drop
1359 // them.
1360 if (NumArgs > NumArgsInProto) {
1361 if (!Proto->isVariadic()) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001362 Diag(Args[NumArgsInProto]->getLocStart(),
1363 diag::err_typecheck_call_too_many_args)
1364 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001365 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1366 Args[NumArgs-1]->getLocEnd());
Chris Lattner925e60d2007-12-28 05:29:59 +00001367 // This deletes the extra arguments.
1368 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 }
1370 NumArgsToCheck = NumArgsInProto;
1371 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001372
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001374 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001375 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001376
1377 Expr *Arg;
1378 if (i < NumArgs)
1379 Arg = Args[i];
1380 else
1381 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001382 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001383
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001384 // Pass the argument.
1385 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001386 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001387
1388 TheCall->setArg(i, Arg);
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001390
1391 // If this is a variadic call, handle args passed through "...".
1392 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001393 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001394 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1395 Expr *Arg = Args[i];
1396 DefaultArgumentPromotion(Arg);
1397 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001398 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001399 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001400 } else {
1401 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1402
Steve Naroffb291ab62007-08-28 23:30:39 +00001403 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001404 for (unsigned i = 0; i != NumArgs; i++) {
1405 Expr *Arg = Args[i];
1406 DefaultArgumentPromotion(Arg);
1407 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001408 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001410
Chris Lattner59907c42007-08-10 20:18:51 +00001411 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001412 if (FDecl)
1413 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001414
Chris Lattner925e60d2007-12-28 05:29:59 +00001415 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001416}
1417
1418Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001419ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001420 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001421 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001422 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001423 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001424 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001425 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001426
Eli Friedman6223c222008-05-20 05:22:08 +00001427 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001428 if (literalType->isVariableArrayType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001429 return Diag(LParenLoc, diag::err_variable_object_no_init)
1430 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001431 } else if (literalType->isIncompleteType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001432 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001433 << literalType
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001434 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001435 }
1436
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001437 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001438 DeclarationName()))
Steve Naroff58d18212008-01-09 20:58:06 +00001439 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001440
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001441 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001442 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001443 if (CheckForConstantInitializer(literalExpr, literalType))
1444 return true;
1445 }
Chris Lattner220ad7c2008-10-26 23:35:51 +00001446 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1447 isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001448}
1449
1450Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001451ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattner220ad7c2008-10-26 23:35:51 +00001452 InitListDesignations &Designators,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001453 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001454 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001455
Steve Naroff08d92e42007-09-15 18:49:24 +00001456 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001457 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001458
Chris Lattner418f6c72008-10-26 23:43:26 +00001459 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1460 Designators.hasAnyDesignators());
Chris Lattnerf0467b32008-04-02 04:24:33 +00001461 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1462 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001463}
1464
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001465/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001466bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001467 UsualUnaryConversions(castExpr);
1468
1469 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1470 // type needs to be scalar.
1471 if (castType->isVoidType()) {
1472 // Cast to void allows any expr type.
1473 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1474 // GCC struct/union extension: allow cast to self.
1475 if (Context.getCanonicalType(castType) !=
1476 Context.getCanonicalType(castExpr->getType()) ||
1477 (!castType->isStructureType() && !castType->isUnionType())) {
1478 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001479 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001480 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001481 }
1482
1483 // accept this, but emit an ext-warn.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001484 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001485 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001486 } else if (!castExpr->getType()->isScalarType() &&
1487 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001488 return Diag(castExpr->getLocStart(),
1489 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00001490 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001491 } else if (castExpr->getType()->isVectorType()) {
1492 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1493 return true;
1494 } else if (castType->isVectorType()) {
1495 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1496 return true;
1497 }
1498 return false;
1499}
1500
Chris Lattnerfe23e212007-12-20 00:44:32 +00001501bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001502 assert(VectorTy->isVectorType() && "Not a vector type!");
1503
1504 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001505 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001506 return Diag(R.getBegin(),
1507 Ty->isVectorType() ?
1508 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001509 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00001510 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001511 } else
1512 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001513 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001514 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001515
1516 return false;
1517}
1518
Steve Naroff4aa88f82007-07-19 01:06:55 +00001519Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001520ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001521 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001522 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001523
1524 Expr *castExpr = static_cast<Expr*>(Op);
1525 QualType castType = QualType::getFromOpaquePtr(Ty);
1526
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001527 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1528 return true;
Steve Naroffb2f9e512008-11-03 23:29:32 +00001529 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001530}
1531
Chris Lattnera21ddb32007-11-26 01:40:58 +00001532/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1533/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001534inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001535 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001536 UsualUnaryConversions(cond);
1537 UsualUnaryConversions(lex);
1538 UsualUnaryConversions(rex);
1539 QualType condT = cond->getType();
1540 QualType lexT = lex->getType();
1541 QualType rexT = rex->getType();
1542
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001544 if (!condT->isScalarType()) { // C99 6.5.15p2
Chris Lattnerd1625842008-11-24 06:25:27 +00001545 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 return QualType();
1547 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001548
1549 // Now check the two expressions.
1550
1551 // If both operands have arithmetic type, do the usual arithmetic conversions
1552 // to find a common type: C99 6.5.15p3,5.
1553 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001554 UsualArithmeticConversions(lex, rex);
1555 return lex->getType();
1556 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001557
1558 // If both operands are the same structure or union type, the result is that
1559 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001560 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001561 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001562 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001563 // "If both the operands have structure or union type, the result has
1564 // that type." This implies that CV qualifiers are dropped.
1565 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001567
1568 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001569 // The following || allows only one side to be void (a GCC-ism).
1570 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001571 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001572 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1573 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00001574 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001575 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1576 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00001577 ImpCastExprToType(lex, Context.VoidTy);
1578 ImpCastExprToType(rex, Context.VoidTy);
1579 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001580 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001581 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1582 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001583 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1584 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001585 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001586 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001587 return lexT;
1588 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001589 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1590 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001591 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001592 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001593 return rexT;
1594 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001595 // Handle the case where both operands are pointers before we handle null
1596 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001597 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1598 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1599 // get the "pointed to" types
1600 QualType lhptee = LHSPT->getPointeeType();
1601 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001602
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001603 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1604 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001605 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001606 // Figure out necessary qualifiers (C99 6.5.15p6)
1607 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001608 QualType destType = Context.getPointerType(destPointee);
1609 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1610 ImpCastExprToType(rex, destType); // promote to void*
1611 return destType;
1612 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001613 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001614 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001615 QualType destType = Context.getPointerType(destPointee);
1616 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1617 ImpCastExprToType(rex, destType); // promote to void*
1618 return destType;
1619 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001620
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001621 QualType compositeType = lexT;
1622
1623 // If either type is an Objective-C object type then check
1624 // compatibility according to Objective-C.
1625 if (Context.isObjCObjectPointerType(lexT) ||
1626 Context.isObjCObjectPointerType(rexT)) {
1627 // If both operands are interfaces and either operand can be
1628 // assigned to the other, use that type as the composite
1629 // type. This allows
1630 // xxx ? (A*) a : (B*) b
1631 // where B is a subclass of A.
1632 //
1633 // Additionally, as for assignment, if either type is 'id'
1634 // allow silent coercion. Finally, if the types are
1635 // incompatible then make sure to use 'id' as the composite
1636 // type so the result is acceptable for sending messages to.
1637
1638 // FIXME: This code should not be localized to here. Also this
1639 // should use a compatible check instead of abusing the
1640 // canAssignObjCInterfaces code.
1641 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1642 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1643 if (LHSIface && RHSIface &&
1644 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1645 compositeType = lexT;
1646 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00001647 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001648 compositeType = rexT;
1649 } else if (Context.isObjCIdType(lhptee) ||
1650 Context.isObjCIdType(rhptee)) {
1651 // FIXME: This code looks wrong, because isObjCIdType checks
1652 // the struct but getObjCIdType returns the pointer to
1653 // struct. This is horrible and should be fixed.
1654 compositeType = Context.getObjCIdType();
1655 } else {
1656 QualType incompatTy = Context.getObjCIdType();
1657 ImpCastExprToType(lex, incompatTy);
1658 ImpCastExprToType(rex, incompatTy);
1659 return incompatTy;
1660 }
1661 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1662 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001663 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00001664 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001665 // In this situation, we assume void* type. No especially good
1666 // reason, but this is what gcc does, and we do have to pick
1667 // to get a consistent AST.
1668 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00001669 ImpCastExprToType(lex, incompatTy);
1670 ImpCastExprToType(rex, incompatTy);
1671 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001672 }
1673 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001674 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1675 // differently qualified versions of compatible types, the result type is
1676 // a pointer to an appropriately qualified version of the *composite*
1677 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001678 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001679 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001680 ImpCastExprToType(lex, compositeType);
1681 ImpCastExprToType(rex, compositeType);
1682 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 }
1684 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001685 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1686 // evaluates to "struct objc_object *" (and is handled above when comparing
1687 // id with statically typed objects).
1688 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1689 // GCC allows qualified id and any Objective-C type to devolve to
1690 // id. Currently localizing to here until clear this should be
1691 // part of ObjCQualifiedIdTypesAreCompatible.
1692 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1693 (lexT->isObjCQualifiedIdType() &&
1694 Context.isObjCObjectPointerType(rexT)) ||
1695 (rexT->isObjCQualifiedIdType() &&
1696 Context.isObjCObjectPointerType(lexT))) {
1697 // FIXME: This is not the correct composite type. This only
1698 // happens to work because id can more or less be used anywhere,
1699 // however this may change the type of method sends.
1700 // FIXME: gcc adds some type-checking of the arguments and emits
1701 // (confusing) incompatible comparison warnings in some
1702 // cases. Investigate.
1703 QualType compositeType = Context.getObjCIdType();
1704 ImpCastExprToType(lex, compositeType);
1705 ImpCastExprToType(rex, compositeType);
1706 return compositeType;
1707 }
1708 }
1709
Steve Naroff61f40a22008-09-10 19:17:48 +00001710 // Selection between block pointer types is ok as long as they are the same.
1711 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1712 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1713 return lexT;
1714
Chris Lattner70d67a92008-01-06 22:42:25 +00001715 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001716 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattnerd1625842008-11-24 06:25:27 +00001717 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 return QualType();
1719}
1720
Steve Narofff69936d2007-09-16 03:34:24 +00001721/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001722/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001723Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 SourceLocation ColonLoc,
1725 ExprTy *Cond, ExprTy *LHS,
1726 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001727 Expr *CondExpr = (Expr *) Cond;
1728 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001729
1730 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1731 // was the condition.
1732 bool isLHSNull = LHSExpr == 0;
1733 if (isLHSNull)
1734 LHSExpr = CondExpr;
1735
Chris Lattner26824902007-07-16 21:39:03 +00001736 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1737 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 if (result.isNull())
1739 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001740 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1741 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001742}
1743
Reid Spencer5f016e22007-07-11 17:01:13 +00001744
1745// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1746// being closely modeled after the C99 spec:-). The odd characteristic of this
1747// routine is it effectively iqnores the qualifiers on the top level pointee.
1748// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1749// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001750Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001751Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1752 QualType lhptee, rhptee;
1753
1754 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001755 lhptee = lhsType->getAsPointerType()->getPointeeType();
1756 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001757
1758 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001759 lhptee = Context.getCanonicalType(lhptee);
1760 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001761
Chris Lattner5cf216b2008-01-04 18:04:52 +00001762 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001763
1764 // C99 6.5.16.1p1: This following citation is common to constraints
1765 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1766 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001767 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00001768 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001769 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001770
1771 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1772 // incomplete type and the other is a pointer to a qualified or unqualified
1773 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001774 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001775 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001776 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001777
1778 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001779 assert(rhptee->isFunctionType());
1780 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001781 }
1782
1783 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001784 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001785 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001786
1787 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001788 assert(lhptee->isFunctionType());
1789 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001790 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001791
1792 // Check for ObjC interfaces
1793 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1794 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1795 if (LHSIface && RHSIface &&
1796 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1797 return ConvTy;
1798
1799 // ID acts sort of like void* for ObjC interfaces
1800 if (LHSIface && Context.isObjCIdType(rhptee))
1801 return ConvTy;
1802 if (RHSIface && Context.isObjCIdType(lhptee))
1803 return ConvTy;
1804
Reid Spencer5f016e22007-07-11 17:01:13 +00001805 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1806 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001807 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1808 rhptee.getUnqualifiedType()))
1809 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001810 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001811}
1812
Steve Naroff1c7d0672008-09-04 15:10:53 +00001813/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1814/// block pointer types are compatible or whether a block and normal pointer
1815/// are compatible. It is more restrict than comparing two function pointer
1816// types.
1817Sema::AssignConvertType
1818Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1819 QualType rhsType) {
1820 QualType lhptee, rhptee;
1821
1822 // get the "pointed to" type (ignoring qualifiers at the top level)
1823 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1824 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1825
1826 // make sure we operate on the canonical type
1827 lhptee = Context.getCanonicalType(lhptee);
1828 rhptee = Context.getCanonicalType(rhptee);
1829
1830 AssignConvertType ConvTy = Compatible;
1831
1832 // For blocks we enforce that qualifiers are identical.
1833 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1834 ConvTy = CompatiblePointerDiscardsQualifiers;
1835
1836 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1837 return IncompatibleBlockPointer;
1838 return ConvTy;
1839}
1840
Reid Spencer5f016e22007-07-11 17:01:13 +00001841/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1842/// has code to accommodate several GCC extensions when type checking
1843/// pointers. Here are some objectionable examples that GCC considers warnings:
1844///
1845/// int a, *pint;
1846/// short *pshort;
1847/// struct foo *pfoo;
1848///
1849/// pint = pshort; // warning: assignment from incompatible pointer type
1850/// a = pint; // warning: assignment makes integer from pointer without a cast
1851/// pint = a; // warning: assignment makes pointer from integer without a cast
1852/// pint = pfoo; // warning: assignment from incompatible pointer type
1853///
1854/// As a result, the code for dealing with pointers is more complex than the
1855/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001856///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001857Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001858Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001859 // Get canonical types. We're not formatting these types, just comparing
1860 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001861 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1862 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001863
1864 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001865 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001866
Douglas Gregor9d293df2008-10-28 00:22:11 +00001867 // If the left-hand side is a reference type, then we are in a
1868 // (rare!) case where we've allowed the use of references in C,
1869 // e.g., as a parameter type in a built-in function. In this case,
1870 // just make sure that the type referenced is compatible with the
1871 // right-hand side type. The caller is responsible for adjusting
1872 // lhsType so that the resulting expression does not have reference
1873 // type.
1874 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1875 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001876 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001877 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001878 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001879
Chris Lattnereca7be62008-04-07 05:30:13 +00001880 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1881 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001882 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001883 // Relax integer conversions like we do for pointers below.
1884 if (rhsType->isIntegerType())
1885 return IntToPointer;
1886 if (lhsType->isIntegerType())
1887 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00001888 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001889 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001890
Nate Begemanbe2341d2008-07-14 18:02:46 +00001891 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001892 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001893 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1894 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001895 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001896
Nate Begemanbe2341d2008-07-14 18:02:46 +00001897 // If we are allowing lax vector conversions, and LHS and RHS are both
1898 // vectors, the total size only needs to be the same. This is a bitcast;
1899 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001900 if (getLangOptions().LaxVectorConversions &&
1901 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001902 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1903 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001904 }
1905 return Incompatible;
1906 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001907
Chris Lattnere8b3e962008-01-04 23:32:24 +00001908 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001910
Chris Lattner78eca282008-04-07 06:49:41 +00001911 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001913 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001914
Chris Lattner78eca282008-04-07 06:49:41 +00001915 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001916 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001917
Steve Naroffb4406862008-09-29 18:10:17 +00001918 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00001919 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00001920 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00001921
1922 // Treat block pointers as objects.
1923 if (getLangOptions().ObjC1 &&
1924 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1925 return Compatible;
1926 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001927 return Incompatible;
1928 }
1929
1930 if (isa<BlockPointerType>(lhsType)) {
1931 if (rhsType->isIntegerType())
1932 return IntToPointer;
1933
Steve Naroffb4406862008-09-29 18:10:17 +00001934 // Treat block pointers as objects.
1935 if (getLangOptions().ObjC1 &&
1936 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1937 return Compatible;
1938
Steve Naroff1c7d0672008-09-04 15:10:53 +00001939 if (rhsType->isBlockPointerType())
1940 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1941
1942 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1943 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00001944 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00001945 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001946 return Incompatible;
1947 }
1948
Chris Lattner78eca282008-04-07 06:49:41 +00001949 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001951 if (lhsType == Context.BoolTy)
1952 return Compatible;
1953
1954 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001955 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001956
Chris Lattner78eca282008-04-07 06:49:41 +00001957 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001958 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001959
1960 if (isa<BlockPointerType>(lhsType) &&
1961 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00001962 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001963 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001964 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001965
Chris Lattnerfc144e22008-01-04 23:18:45 +00001966 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001967 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 }
1970 return Incompatible;
1971}
1972
Chris Lattner5cf216b2008-01-04 18:04:52 +00001973Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001974Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001975 if (getLangOptions().CPlusPlus) {
1976 if (!lhsType->isRecordType()) {
1977 // C++ 5.17p3: If the left operand is not of class type, the
1978 // expression is implicitly converted (C++ 4) to the
1979 // cv-unqualified type of the left operand.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001980 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001981 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001982 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00001983 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001984 }
1985
1986 // FIXME: Currently, we fall through and treat C++ classes like C
1987 // structures.
1988 }
1989
Steve Naroff529a4ad2007-11-27 17:58:44 +00001990 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1991 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00001992 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1993 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001994 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001995 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001996 return Compatible;
1997 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001998
1999 // We don't allow conversion of non-null-pointer constants to integers.
2000 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2001 return IntToBlockPointer;
2002
Chris Lattner943140e2007-10-16 02:55:40 +00002003 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002004 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002005 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002006 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002007 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002008 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002009 if (!lhsType->isReferenceType())
2010 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002011
Chris Lattner5cf216b2008-01-04 18:04:52 +00002012 Sema::AssignConvertType result =
2013 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002014
2015 // C99 6.5.16.1p2: The value of the right operand is converted to the
2016 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002017 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2018 // so that we can use references in built-in functions even in C.
2019 // The getNonReferenceType() call makes sure that the resulting expression
2020 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002021 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002022 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002023 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002024}
2025
Chris Lattner5cf216b2008-01-04 18:04:52 +00002026Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002027Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2028 return CheckAssignmentConstraints(lhsType, rhsType);
2029}
2030
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002031QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002032 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002033 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002034 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002035 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002036}
2037
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002038inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002039 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002040 // For conversion purposes, we ignore any qualifiers.
2041 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002042 QualType lhsType =
2043 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2044 QualType rhsType =
2045 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002046
Nate Begemanbe2341d2008-07-14 18:02:46 +00002047 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002048 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002050
Nate Begemanbe2341d2008-07-14 18:02:46 +00002051 // Handle the case of a vector & extvector type of the same size and element
2052 // type. It would be nice if we only had one vector type someday.
2053 if (getLangOptions().LaxVectorConversions)
2054 if (const VectorType *LV = lhsType->getAsVectorType())
2055 if (const VectorType *RV = rhsType->getAsVectorType())
2056 if (LV->getElementType() == RV->getElementType() &&
2057 LV->getNumElements() == RV->getNumElements())
2058 return lhsType->isExtVectorType() ? lhsType : rhsType;
2059
2060 // If the lhs is an extended vector and the rhs is a scalar of the same type
2061 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002062 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002063 QualType eltType = V->getElementType();
2064
2065 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2066 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2067 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002068 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002069 return lhsType;
2070 }
2071 }
2072
Nate Begemanbe2341d2008-07-14 18:02:46 +00002073 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002074 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002075 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002076 QualType eltType = V->getElementType();
2077
2078 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2079 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2080 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002081 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002082 return rhsType;
2083 }
2084 }
2085
Reid Spencer5f016e22007-07-11 17:01:13 +00002086 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002087 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002088 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002089 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 return QualType();
2091}
2092
2093inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002094 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002095{
Steve Naroff90045e82007-07-13 23:32:42 +00002096 QualType lhsType = lex->getType(), rhsType = rex->getType();
2097
2098 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002099 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002100
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002101 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002102
Steve Naroffa4332e22007-07-17 00:58:39 +00002103 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002104 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002105 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002106}
2107
2108inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002109 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002110{
Steve Naroff90045e82007-07-13 23:32:42 +00002111 QualType lhsType = lex->getType(), rhsType = rex->getType();
2112
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002113 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002114
Steve Naroffa4332e22007-07-17 00:58:39 +00002115 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002116 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002117 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002118}
2119
2120inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002121 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002122{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002123 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002124 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002125
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002126 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002127
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002129 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002130 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002131
Eli Friedmand72d16e2008-05-18 18:08:51 +00002132 // Put any potential pointer into PExp
2133 Expr* PExp = lex, *IExp = rex;
2134 if (IExp->getType()->isPointerType())
2135 std::swap(PExp, IExp);
2136
2137 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2138 if (IExp->getType()->isIntegerType()) {
2139 // Check for arithmetic on pointers to incomplete types
2140 if (!PTy->getPointeeType()->isObjectType()) {
2141 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002142 Diag(Loc, diag::ext_gnu_void_ptr)
2143 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002144 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002145 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00002146 << lex->getType() << lex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002147 return QualType();
2148 }
2149 }
2150 return PExp->getType();
2151 }
2152 }
2153
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002154 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002155}
2156
Chris Lattnereca7be62008-04-07 05:30:13 +00002157// C99 6.5.6
2158QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002159 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002160 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002161 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002162
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002163 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002164
Chris Lattner6e4ab612007-12-09 21:53:25 +00002165 // Enforce type constraints: C99 6.5.6p3.
2166
2167 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002168 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002169 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002170
2171 // Either ptr - int or ptr - ptr.
2172 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002173 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002174
Chris Lattner6e4ab612007-12-09 21:53:25 +00002175 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002176 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002177 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002178 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002179 Diag(Loc, diag::ext_gnu_void_ptr)
2180 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002181 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002182 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002183 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002184 return QualType();
2185 }
2186 }
2187
2188 // The result type of a pointer-int computation is the pointer type.
2189 if (rex->getType()->isIntegerType())
2190 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002191
Chris Lattner6e4ab612007-12-09 21:53:25 +00002192 // Handle pointer-pointer subtractions.
2193 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002194 QualType rpointee = RHSPTy->getPointeeType();
2195
Chris Lattner6e4ab612007-12-09 21:53:25 +00002196 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002197 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002198 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002199 if (rpointee->isVoidType()) {
2200 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002201 Diag(Loc, diag::ext_gnu_void_ptr)
2202 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002203 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002204 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002205 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002206 return QualType();
2207 }
2208 }
2209
2210 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002211 if (!Context.typesAreCompatible(
2212 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2213 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002214 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00002215 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002216 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002217 return QualType();
2218 }
2219
2220 return Context.getPointerDiffType();
2221 }
2222 }
2223
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002224 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002225}
2226
Chris Lattnereca7be62008-04-07 05:30:13 +00002227// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002228QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002229 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002230 // C99 6.5.7p2: Each of the operands shall have integer type.
2231 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002232 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002233
Chris Lattnerca5eede2007-12-12 05:47:28 +00002234 // Shifts don't perform usual arithmetic conversions, they just do integer
2235 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002236 if (!isCompAssign)
2237 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002238 UsualUnaryConversions(rex);
2239
2240 // "The type of the result is that of the promoted left operand."
2241 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002242}
2243
Eli Friedman3d815e72008-08-22 00:56:42 +00002244static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2245 ASTContext& Context) {
2246 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2247 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2248 // ID acts sort of like void* for ObjC interfaces
2249 if (LHSIface && Context.isObjCIdType(RHS))
2250 return true;
2251 if (RHSIface && Context.isObjCIdType(LHS))
2252 return true;
2253 if (!LHSIface || !RHSIface)
2254 return false;
2255 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2256 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2257}
2258
Chris Lattnereca7be62008-04-07 05:30:13 +00002259// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002260QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002261 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002262 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002263 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002264
Chris Lattnera5937dd2007-08-26 01:18:55 +00002265 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002266 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2267 UsualArithmeticConversions(lex, rex);
2268 else {
2269 UsualUnaryConversions(lex);
2270 UsualUnaryConversions(rex);
2271 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002272 QualType lType = lex->getType();
2273 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002274
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002275 // For non-floating point types, check for self-comparisons of the form
2276 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2277 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002278 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002279 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2280 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002281 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002282 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002283 }
2284
Douglas Gregor447b69e2008-11-19 03:25:36 +00002285 // The result of comparisons is 'bool' in C++, 'int' in C.
2286 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2287
Chris Lattnera5937dd2007-08-26 01:18:55 +00002288 if (isRelational) {
2289 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002290 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002291 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002292 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002293 if (lType->isFloatingType()) {
2294 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002295 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002296 }
2297
Chris Lattnera5937dd2007-08-26 01:18:55 +00002298 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002299 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002300 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002301
Chris Lattnerd28f8152007-08-26 01:10:14 +00002302 bool LHSIsNull = lex->isNullPointerConstant(Context);
2303 bool RHSIsNull = rex->isNullPointerConstant(Context);
2304
Chris Lattnera5937dd2007-08-26 01:18:55 +00002305 // All of the following pointer related warnings are GCC extensions, except
2306 // when handling null pointer constants. One day, we can consider making them
2307 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002308 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002309 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002310 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002311 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002312 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002313
Steve Naroff66296cb2007-11-13 14:57:38 +00002314 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002315 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2316 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002317 RCanPointeeTy.getUnqualifiedType()) &&
2318 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002319 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002320 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002321 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002322 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002323 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002324 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002325 // Handle block pointer types.
2326 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2327 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2328 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2329
2330 if (!LHSIsNull && !RHSIsNull &&
2331 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002332 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002333 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002334 }
2335 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002336 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002337 }
Steve Naroff59f53942008-09-28 01:11:11 +00002338 // Allow block pointers to be compared with null pointer constants.
2339 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2340 (lType->isPointerType() && rType->isBlockPointerType())) {
2341 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002342 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002343 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002344 }
2345 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002346 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00002347 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002348
Steve Naroff20373222008-06-03 14:04:54 +00002349 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002350 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00002351 const PointerType *LPT = lType->getAsPointerType();
2352 const PointerType *RPT = rType->getAsPointerType();
2353 bool LPtrToVoid = LPT ?
2354 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2355 bool RPtrToVoid = RPT ?
2356 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2357
2358 if (!LPtrToVoid && !RPtrToVoid &&
2359 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002360 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002361 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00002362 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002363 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00002364 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002365 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002366 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002367 }
Steve Naroff20373222008-06-03 14:04:54 +00002368 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2369 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002370 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002371 } else {
2372 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002373 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002374 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002375 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002376 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002377 }
Steve Naroff20373222008-06-03 14:04:54 +00002378 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002379 }
Steve Naroff20373222008-06-03 14:04:54 +00002380 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2381 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002382 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002383 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002384 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002385 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002386 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002387 }
Steve Naroff20373222008-06-03 14:04:54 +00002388 if (lType->isIntegerType() &&
2389 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002390 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002391 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002392 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002393 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002394 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002395 }
Steve Naroff39218df2008-09-04 16:56:14 +00002396 // Handle block pointers.
2397 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2398 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002399 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002400 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002401 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002402 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002403 }
2404 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2405 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002406 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002407 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002408 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002409 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002410 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002411 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002412}
2413
Nate Begemanbe2341d2008-07-14 18:02:46 +00002414/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2415/// operates on extended vector types. Instead of producing an IntTy result,
2416/// like a scalar comparison, a vector comparison produces a vector of integer
2417/// types.
2418QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002419 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00002420 bool isRelational) {
2421 // Check to make sure we're operating on vectors of the same type and width,
2422 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002423 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002424 if (vType.isNull())
2425 return vType;
2426
2427 QualType lType = lex->getType();
2428 QualType rType = rex->getType();
2429
2430 // For non-floating point types, check for self-comparisons of the form
2431 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2432 // often indicate logic errors in the program.
2433 if (!lType->isFloatingType()) {
2434 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2435 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2436 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002437 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002438 }
2439
2440 // Check for comparisons of floating point operands using != and ==.
2441 if (!isRelational && lType->isFloatingType()) {
2442 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002443 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002444 }
2445
2446 // Return the type for the comparison, which is the same as vector type for
2447 // integer vectors, or an integer type of identical size and number of
2448 // elements for floating point vectors.
2449 if (lType->isIntegerType())
2450 return lType;
2451
2452 const VectorType *VTy = lType->getAsVectorType();
2453
2454 // FIXME: need to deal with non-32b int / non-64b long long
2455 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2456 if (TypeSize == 32) {
2457 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2458 }
2459 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2460 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2461}
2462
Reid Spencer5f016e22007-07-11 17:01:13 +00002463inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002464 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002465{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002466 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002467 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002468
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002469 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002470
Steve Naroffa4332e22007-07-17 00:58:39 +00002471 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002472 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002473 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002474}
2475
2476inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002477 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002478{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002479 UsualUnaryConversions(lex);
2480 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002481
Eli Friedman5773a6c2008-05-13 20:16:47 +00002482 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002483 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002484 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002485}
2486
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002487/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2488/// emit an error and return true. If so, return false.
2489static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2490 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2491 if (IsLV == Expr::MLV_Valid)
2492 return false;
2493
2494 unsigned Diag = 0;
2495 bool NeedType = false;
2496 switch (IsLV) { // C99 6.5.16p2
2497 default: assert(0 && "Unknown result from isModifiableLvalue!");
2498 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002499 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002500 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2501 NeedType = true;
2502 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002503 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002504 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2505 NeedType = true;
2506 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00002507 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002508 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2509 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002510 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002511 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2512 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002513 case Expr::MLV_IncompleteType:
2514 case Expr::MLV_IncompleteVoidType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002515 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2516 NeedType = true;
2517 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002518 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002519 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2520 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002521 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002522 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2523 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00002524 case Expr::MLV_ReadonlyProperty:
2525 Diag = diag::error_readonly_property_assignment;
2526 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00002527 case Expr::MLV_NoSetterProperty:
2528 Diag = diag::error_nosetter_property_assignment;
2529 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002530 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002531
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002532 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00002533 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002534 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002535 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002536 return true;
2537}
2538
2539
2540
2541// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002542QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2543 SourceLocation Loc,
2544 QualType CompoundType) {
2545 // Verify that LHS is a modifiable lvalue, and emit error if not.
2546 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002547 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002548
2549 QualType LHSType = LHS->getType();
2550 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002551
Chris Lattner5cf216b2008-01-04 18:04:52 +00002552 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002553 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00002554 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002555 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner2c156472008-08-21 18:04:13 +00002556
2557 // If the RHS is a unary plus or minus, check to see if they = and + are
2558 // right next to each other. If so, the user may have typo'd "x =+ 4"
2559 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002560 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00002561 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2562 RHSCheck = ICE->getSubExpr();
2563 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2564 if ((UO->getOpcode() == UnaryOperator::Plus ||
2565 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002566 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00002567 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002568 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002569 Diag(Loc, diag::warn_not_compound_assign)
2570 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2571 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00002572 }
2573 } else {
2574 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002575 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00002576 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002577
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002578 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2579 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002580 return QualType();
2581
Reid Spencer5f016e22007-07-11 17:01:13 +00002582 // C99 6.5.16p3: The type of an assignment expression is the type of the
2583 // left operand unless the left operand has qualified type, in which case
2584 // it is the unqualified version of the type of the left operand.
2585 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2586 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002587 // C++ 5.17p1: the type of the assignment expression is that of its left
2588 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002589 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002590}
2591
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002592// C99 6.5.17
2593QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2594 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00002595
2596 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002597 DefaultFunctionArrayConversion(RHS);
2598 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002599}
2600
Steve Naroff49b45262007-07-13 16:58:59 +00002601/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2602/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Chris Lattner3528d352008-11-21 07:05:48 +00002603QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc) {
2604 QualType ResType = Op->getType();
2605 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002606
Steve Naroff084f9ed2007-08-24 17:20:07 +00002607 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner3528d352008-11-21 07:05:48 +00002608 if (ResType->isRealType()) {
2609 // OK!
2610 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2611 // C99 6.5.2.4p2, 6.5.6p2
2612 if (PT->getPointeeType()->isObjectType()) {
2613 // Pointer to object is ok!
2614 } else if (PT->getPointeeType()->isVoidType()) {
2615 // Pointer to void is extension.
2616 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2617 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002618 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00002619 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 return QualType();
2621 }
Chris Lattner3528d352008-11-21 07:05:48 +00002622 } else if (ResType->isComplexType()) {
2623 // C99 does not support ++/-- on complex types, we allow as an extension.
2624 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00002625 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00002626 } else {
2627 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00002628 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00002629 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002631 // At this point, we know we have a real, complex or pointer type.
2632 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00002633 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00002634 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00002635 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002636}
2637
Anders Carlsson369dee42008-02-01 07:15:58 +00002638/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002639/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002640/// where the declaration is needed for type checking. We only need to
2641/// handle cases when the expression references a function designator
2642/// or is an lvalue. Here are some examples:
2643/// - &(x) => x
2644/// - &*****f => f for f a function designator.
2645/// - &s.xx => s
2646/// - &s.zz[1].yy -> s, if zz is an array
2647/// - *(x + 1) -> x, if x is an array
2648/// - &"123"[2] -> 0
2649/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002650static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002651 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002653 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002655 // Fields cannot be declared with a 'register' storage class.
2656 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002657 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002658 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002659 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002660 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002661 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002662
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002663 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00002664 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002665 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002666 return 0;
2667 else
2668 return VD;
2669 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002670 case Stmt::UnaryOperatorClass: {
2671 UnaryOperator *UO = cast<UnaryOperator>(E);
2672
2673 switch(UO->getOpcode()) {
2674 case UnaryOperator::Deref: {
2675 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002676 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2677 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2678 if (!VD || VD->getType()->isPointerType())
2679 return 0;
2680 return VD;
2681 }
2682 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002683 }
2684 case UnaryOperator::Real:
2685 case UnaryOperator::Imag:
2686 case UnaryOperator::Extension:
2687 return getPrimaryDecl(UO->getSubExpr());
2688 default:
2689 return 0;
2690 }
2691 }
2692 case Stmt::BinaryOperatorClass: {
2693 BinaryOperator *BO = cast<BinaryOperator>(E);
2694
2695 // Handle cases involving pointer arithmetic. The result of an
2696 // Assign or AddAssign is not an lvalue so they can be ignored.
2697
2698 // (x + n) or (n + x) => x
2699 if (BO->getOpcode() == BinaryOperator::Add) {
2700 if (BO->getLHS()->getType()->isPointerType()) {
2701 return getPrimaryDecl(BO->getLHS());
2702 } else if (BO->getRHS()->getType()->isPointerType()) {
2703 return getPrimaryDecl(BO->getRHS());
2704 }
2705 }
2706
2707 return 0;
2708 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002709 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002710 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002711 case Stmt::ImplicitCastExprClass:
2712 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002713 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002714 default:
2715 return 0;
2716 }
2717}
2718
2719/// CheckAddressOfOperand - The operand of & must be either a function
2720/// designator or an lvalue designating an object. If it is an lvalue, the
2721/// object cannot be declared with storage class register or be a bit field.
2722/// Note: The usual conversions are *not* applied to the operand of the &
2723/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00002724/// In C++, the operand might be an overloaded function name, in which case
2725/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002726QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002727 if (getLangOptions().C99) {
2728 // Implement C99-only parts of addressof rules.
2729 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2730 if (uOp->getOpcode() == UnaryOperator::Deref)
2731 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2732 // (assuming the deref expression is valid).
2733 return uOp->getSubExpr()->getType();
2734 }
2735 // Technically, there should be a check for array subscript
2736 // expressions here, but the result of one is always an lvalue anyway.
2737 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002738 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002739 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002740
2741 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002742 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2743 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002744 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2745 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 return QualType();
2747 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002748 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2749 if (MemExpr->getMemberDecl()->isBitField()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002750 Diag(OpLoc, diag::err_typecheck_address_of)
2751 << "bit-field" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00002752 return QualType();
2753 }
2754 // Check for Apple extension for accessing vector components.
2755 } else if (isa<ArraySubscriptExpr>(op) &&
2756 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002757 Diag(OpLoc, diag::err_typecheck_address_of)
2758 << "vector" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00002759 return QualType();
2760 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002761 // We have an lvalue with a decl. Make sure the decl is not declared
2762 // with the register storage-class specifier.
2763 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2764 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002765 Diag(OpLoc, diag::err_typecheck_address_of)
2766 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002767 return QualType();
2768 }
Douglas Gregor904eed32008-11-10 20:40:00 +00002769 } else if (isa<OverloadedFunctionDecl>(dcl))
2770 return Context.OverloadTy;
2771 else
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002774
Reid Spencer5f016e22007-07-11 17:01:13 +00002775 // If the operand has type "type", the result has type "pointer to type".
2776 return Context.getPointerType(op->getType());
2777}
2778
Chris Lattner22caddc2008-11-23 09:13:29 +00002779QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
2780 UsualUnaryConversions(Op);
2781 QualType Ty = Op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002782
Chris Lattner22caddc2008-11-23 09:13:29 +00002783 // Note that per both C89 and C99, this is always legal, even if ptype is an
2784 // incomplete type or void. It would be possible to warn about dereferencing
2785 // a void pointer, but it's completely well-defined, and such a warning is
2786 // unlikely to catch any mistakes.
2787 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00002788 return PT->getPointeeType();
Chris Lattner22caddc2008-11-23 09:13:29 +00002789
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002790 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00002791 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 return QualType();
2793}
2794
2795static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2796 tok::TokenKind Kind) {
2797 BinaryOperator::Opcode Opc;
2798 switch (Kind) {
2799 default: assert(0 && "Unknown binop!");
2800 case tok::star: Opc = BinaryOperator::Mul; break;
2801 case tok::slash: Opc = BinaryOperator::Div; break;
2802 case tok::percent: Opc = BinaryOperator::Rem; break;
2803 case tok::plus: Opc = BinaryOperator::Add; break;
2804 case tok::minus: Opc = BinaryOperator::Sub; break;
2805 case tok::lessless: Opc = BinaryOperator::Shl; break;
2806 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2807 case tok::lessequal: Opc = BinaryOperator::LE; break;
2808 case tok::less: Opc = BinaryOperator::LT; break;
2809 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2810 case tok::greater: Opc = BinaryOperator::GT; break;
2811 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2812 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2813 case tok::amp: Opc = BinaryOperator::And; break;
2814 case tok::caret: Opc = BinaryOperator::Xor; break;
2815 case tok::pipe: Opc = BinaryOperator::Or; break;
2816 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2817 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2818 case tok::equal: Opc = BinaryOperator::Assign; break;
2819 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2820 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2821 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2822 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2823 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2824 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2825 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2826 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2827 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2828 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2829 case tok::comma: Opc = BinaryOperator::Comma; break;
2830 }
2831 return Opc;
2832}
2833
2834static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2835 tok::TokenKind Kind) {
2836 UnaryOperator::Opcode Opc;
2837 switch (Kind) {
2838 default: assert(0 && "Unknown unary op!");
2839 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2840 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2841 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2842 case tok::star: Opc = UnaryOperator::Deref; break;
2843 case tok::plus: Opc = UnaryOperator::Plus; break;
2844 case tok::minus: Opc = UnaryOperator::Minus; break;
2845 case tok::tilde: Opc = UnaryOperator::Not; break;
2846 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 case tok::kw___real: Opc = UnaryOperator::Real; break;
2848 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2849 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2850 }
2851 return Opc;
2852}
2853
Douglas Gregoreaebc752008-11-06 23:29:22 +00002854/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2855/// operator @p Opc at location @c TokLoc. This routine only supports
2856/// built-in operations; ActOnBinOp handles overloaded operators.
2857Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2858 unsigned Op,
2859 Expr *lhs, Expr *rhs) {
2860 QualType ResultTy; // Result type of the binary operator.
2861 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2862 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2863
2864 switch (Opc) {
2865 default:
2866 assert(0 && "Unknown binary expr!");
2867 case BinaryOperator::Assign:
2868 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2869 break;
2870 case BinaryOperator::Mul:
2871 case BinaryOperator::Div:
2872 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2873 break;
2874 case BinaryOperator::Rem:
2875 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2876 break;
2877 case BinaryOperator::Add:
2878 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2879 break;
2880 case BinaryOperator::Sub:
2881 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2882 break;
2883 case BinaryOperator::Shl:
2884 case BinaryOperator::Shr:
2885 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2886 break;
2887 case BinaryOperator::LE:
2888 case BinaryOperator::LT:
2889 case BinaryOperator::GE:
2890 case BinaryOperator::GT:
2891 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2892 break;
2893 case BinaryOperator::EQ:
2894 case BinaryOperator::NE:
2895 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2896 break;
2897 case BinaryOperator::And:
2898 case BinaryOperator::Xor:
2899 case BinaryOperator::Or:
2900 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2901 break;
2902 case BinaryOperator::LAnd:
2903 case BinaryOperator::LOr:
2904 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2905 break;
2906 case BinaryOperator::MulAssign:
2907 case BinaryOperator::DivAssign:
2908 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2909 if (!CompTy.isNull())
2910 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2911 break;
2912 case BinaryOperator::RemAssign:
2913 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2914 if (!CompTy.isNull())
2915 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2916 break;
2917 case BinaryOperator::AddAssign:
2918 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2919 if (!CompTy.isNull())
2920 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2921 break;
2922 case BinaryOperator::SubAssign:
2923 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2924 if (!CompTy.isNull())
2925 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2926 break;
2927 case BinaryOperator::ShlAssign:
2928 case BinaryOperator::ShrAssign:
2929 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2930 if (!CompTy.isNull())
2931 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2932 break;
2933 case BinaryOperator::AndAssign:
2934 case BinaryOperator::XorAssign:
2935 case BinaryOperator::OrAssign:
2936 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2937 if (!CompTy.isNull())
2938 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2939 break;
2940 case BinaryOperator::Comma:
2941 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2942 break;
2943 }
2944 if (ResultTy.isNull())
2945 return true;
2946 if (CompTy.isNull())
2947 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2948 else
2949 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2950}
2951
Reid Spencer5f016e22007-07-11 17:01:13 +00002952// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00002953Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2954 tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002955 ExprTy *LHS, ExprTy *RHS) {
2956 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2957 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2958
Steve Narofff69936d2007-09-16 03:34:24 +00002959 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2960 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002961
Douglas Gregoreaebc752008-11-06 23:29:22 +00002962 if (getLangOptions().CPlusPlus &&
2963 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2964 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002965 // If this is one of the assignment operators, we only perform
2966 // overload resolution if the left-hand side is a class or
2967 // enumeration type (C++ [expr.ass]p3).
2968 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
2969 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
2970 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
2971 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00002972
2973 // Determine which overloaded operator we're dealing with.
2974 static const OverloadedOperatorKind OverOps[] = {
2975 OO_Star, OO_Slash, OO_Percent,
2976 OO_Plus, OO_Minus,
2977 OO_LessLess, OO_GreaterGreater,
2978 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2979 OO_EqualEqual, OO_ExclaimEqual,
2980 OO_Amp,
2981 OO_Caret,
2982 OO_Pipe,
2983 OO_AmpAmp,
2984 OO_PipePipe,
2985 OO_Equal, OO_StarEqual,
2986 OO_SlashEqual, OO_PercentEqual,
2987 OO_PlusEqual, OO_MinusEqual,
2988 OO_LessLessEqual, OO_GreaterGreaterEqual,
2989 OO_AmpEqual, OO_CaretEqual,
2990 OO_PipeEqual,
2991 OO_Comma
2992 };
2993 OverloadedOperatorKind OverOp = OverOps[Opc];
2994
Douglas Gregor96176b32008-11-18 23:14:02 +00002995 // Add the appropriate overloaded operators (C++ [over.match.oper])
2996 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00002997 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00002998 Expr *Args[2] = { lhs, rhs };
Douglas Gregor96176b32008-11-18 23:14:02 +00002999 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregoreaebc752008-11-06 23:29:22 +00003000
3001 // Perform overload resolution.
3002 OverloadCandidateSet::iterator Best;
3003 switch (BestViableFunction(CandidateSet, Best)) {
3004 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003005 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003006 FunctionDecl *FnDecl = Best->Function;
3007
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003008 if (FnDecl) {
3009 // We matched an overloaded operator. Build a call to that
3010 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003011
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003012 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3014 if (PerformObjectArgumentInitialization(lhs, Method) ||
3015 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3016 "passing"))
3017 return true;
3018 } else {
3019 // Convert the arguments.
3020 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3021 "passing") ||
3022 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3023 "passing"))
3024 return true;
3025 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003026
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003027 // Determine the result type
3028 QualType ResultTy
3029 = FnDecl->getType()->getAsFunctionType()->getResultType();
3030 ResultTy = ResultTy.getNonReferenceType();
3031
3032 // Build the actual expression node.
Douglas Gregorb4609802008-11-14 16:09:21 +00003033 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3034 SourceLocation());
3035 UsualUnaryConversions(FnExpr);
3036
Douglas Gregorb4609802008-11-14 16:09:21 +00003037 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003038 } else {
3039 // We matched a built-in operator. Convert the arguments, then
3040 // break out so that we will build the appropriate built-in
3041 // operator node.
3042 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3043 "passing") ||
3044 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3045 "passing"))
3046 return true;
3047
3048 break;
3049 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003050 }
3051
3052 case OR_No_Viable_Function:
3053 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003054 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003055 break;
3056
3057 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003058 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3059 << BinaryOperator::getOpcodeStr(Opc)
3060 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003061 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3062 return true;
3063 }
3064
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003065 // Either we found no viable overloaded operator or we matched a
3066 // built-in operator. In either case, fall through to trying to
3067 // build a built-in operation.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003068 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003069
Douglas Gregoreaebc752008-11-06 23:29:22 +00003070 // Build a built-in binary operation.
3071 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003072}
3073
3074// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor74253732008-11-19 15:42:04 +00003075Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3076 tok::TokenKind Op, ExprTy *input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003077 Expr *Input = (Expr*)input;
3078 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003079
3080 if (getLangOptions().CPlusPlus &&
3081 (Input->getType()->isRecordType()
3082 || Input->getType()->isEnumeralType())) {
3083 // Determine which overloaded operator we're dealing with.
3084 static const OverloadedOperatorKind OverOps[] = {
3085 OO_None, OO_None,
3086 OO_PlusPlus, OO_MinusMinus,
3087 OO_Amp, OO_Star,
3088 OO_Plus, OO_Minus,
3089 OO_Tilde, OO_Exclaim,
3090 OO_None, OO_None,
3091 OO_None,
3092 OO_None
3093 };
3094 OverloadedOperatorKind OverOp = OverOps[Opc];
3095
3096 // Add the appropriate overloaded operators (C++ [over.match.oper])
3097 // to the candidate set.
3098 OverloadCandidateSet CandidateSet;
3099 if (OverOp != OO_None)
3100 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3101
3102 // Perform overload resolution.
3103 OverloadCandidateSet::iterator Best;
3104 switch (BestViableFunction(CandidateSet, Best)) {
3105 case OR_Success: {
3106 // We found a built-in operator or an overloaded operator.
3107 FunctionDecl *FnDecl = Best->Function;
3108
3109 if (FnDecl) {
3110 // We matched an overloaded operator. Build a call to that
3111 // operator.
3112
3113 // Convert the arguments.
3114 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3115 if (PerformObjectArgumentInitialization(Input, Method))
3116 return true;
3117 } else {
3118 // Convert the arguments.
3119 if (PerformCopyInitialization(Input,
3120 FnDecl->getParamDecl(0)->getType(),
3121 "passing"))
3122 return true;
3123 }
3124
3125 // Determine the result type
3126 QualType ResultTy
3127 = FnDecl->getType()->getAsFunctionType()->getResultType();
3128 ResultTy = ResultTy.getNonReferenceType();
3129
3130 // Build the actual expression node.
3131 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3132 SourceLocation());
3133 UsualUnaryConversions(FnExpr);
3134
3135 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3136 } else {
3137 // We matched a built-in operator. Convert the arguments, then
3138 // break out so that we will build the appropriate built-in
3139 // operator node.
3140 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3141 "passing"))
3142 return true;
3143
3144 break;
3145 }
3146 }
3147
3148 case OR_No_Viable_Function:
3149 // No viable function; fall through to handling this as a
3150 // built-in operator, which will produce an error message for us.
3151 break;
3152
3153 case OR_Ambiguous:
3154 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3155 << UnaryOperator::getOpcodeStr(Opc)
3156 << Input->getSourceRange();
3157 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3158 return true;
3159 }
3160
3161 // Either we found no viable overloaded operator or we matched a
3162 // built-in operator. In either case, fall through to trying to
3163 // build a built-in operation.
3164 }
3165
Reid Spencer5f016e22007-07-11 17:01:13 +00003166 QualType resultType;
3167 switch (Opc) {
3168 default:
3169 assert(0 && "Unimplemented unary expr!");
3170 case UnaryOperator::PreInc:
3171 case UnaryOperator::PreDec:
3172 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
3173 break;
3174 case UnaryOperator::AddrOf:
3175 resultType = CheckAddressOfOperand(Input, OpLoc);
3176 break;
3177 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003178 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003179 resultType = CheckIndirectionOperand(Input, OpLoc);
3180 break;
3181 case UnaryOperator::Plus:
3182 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003183 UsualUnaryConversions(Input);
3184 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00003185 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3186 break;
3187 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3188 resultType->isEnumeralType())
3189 break;
3190 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3191 Opc == UnaryOperator::Plus &&
3192 resultType->isPointerType())
3193 break;
3194
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003195 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003196 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003197 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003198 UsualUnaryConversions(Input);
3199 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00003200 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3201 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3202 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003203 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003204 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00003205 else if (!resultType->isIntegerType())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003206 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003207 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003208 break;
3209 case UnaryOperator::LNot: // logical negation
3210 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003211 DefaultFunctionArrayConversion(Input);
3212 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003213 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003214 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003215 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003216 // LNot always has type int. C99 6.5.3.3p5.
3217 resultType = Context.IntTy;
3218 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00003219 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00003220 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00003221 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00003222 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003223 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00003224 resultType = Input->getType();
3225 break;
3226 }
3227 if (resultType.isNull())
3228 return true;
3229 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3230}
3231
Steve Naroff1b273c42007-09-16 14:56:35 +00003232/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3233Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003234 SourceLocation LabLoc,
3235 IdentifierInfo *LabelII) {
3236 // Look up the record for this label identifier.
3237 LabelStmt *&LabelDecl = LabelMap[LabelII];
3238
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00003239 // If we haven't seen this label yet, create a forward reference. It
3240 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00003241 if (LabelDecl == 0)
3242 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3243
3244 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00003245 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3246 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00003247}
3248
Steve Naroff1b273c42007-09-16 14:56:35 +00003249Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003250 SourceLocation RPLoc) { // "({..})"
3251 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3252 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3253 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3254
3255 // FIXME: there are a variety of strange constraints to enforce here, for
3256 // example, it is not possible to goto into a stmt expression apparently.
3257 // More semantic analysis is needed.
3258
3259 // FIXME: the last statement in the compount stmt has its value used. We
3260 // should not warn about it being unused.
3261
3262 // If there are sub stmts in the compound stmt, take the type of the last one
3263 // as the type of the stmtexpr.
3264 QualType Ty = Context.VoidTy;
3265
Chris Lattner611b2ec2008-07-26 19:51:01 +00003266 if (!Compound->body_empty()) {
3267 Stmt *LastStmt = Compound->body_back();
3268 // If LastStmt is a label, skip down through into the body.
3269 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3270 LastStmt = Label->getSubStmt();
3271
3272 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003273 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00003274 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003275
3276 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3277}
Steve Naroffd34e9152007-08-01 22:05:33 +00003278
Steve Naroff1b273c42007-09-16 14:56:35 +00003279Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003280 SourceLocation TypeLoc,
3281 TypeTy *argty,
3282 OffsetOfComponent *CompPtr,
3283 unsigned NumComponents,
3284 SourceLocation RPLoc) {
3285 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3286 assert(!ArgTy.isNull() && "Missing type argument!");
3287
3288 // We must have at least one component that refers to the type, and the first
3289 // one is known to be a field designator. Verify that the ArgTy represents
3290 // a struct/union/class.
3291 if (!ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00003292 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003293
3294 // Otherwise, create a compound literal expression as the base, and
3295 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00003296 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003297
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003298 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3299 // GCC extension, diagnose them.
3300 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003301 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3302 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003303
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003304 for (unsigned i = 0; i != NumComponents; ++i) {
3305 const OffsetOfComponent &OC = CompPtr[i];
3306 if (OC.isBrackets) {
3307 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003308 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003309 if (!AT) {
3310 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003311 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003312 }
3313
Chris Lattner704fe352007-08-30 17:59:59 +00003314 // FIXME: C++: Verify that operator[] isn't overloaded.
3315
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003316 // C99 6.5.2.1p1
3317 Expr *Idx = static_cast<Expr*>(OC.U.E);
3318 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003319 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3320 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003321
3322 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3323 continue;
3324 }
3325
3326 const RecordType *RC = Res->getType()->getAsRecordType();
3327 if (!RC) {
3328 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003329 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003330 }
3331
3332 // Get the decl corresponding to this.
3333 RecordDecl *RD = RC->getDecl();
3334 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3335 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00003336 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3337 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00003338
3339 // FIXME: C++: Verify that MemberDecl isn't a static field.
3340 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00003341 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3342 // matter here.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003343 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3344 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003345 }
3346
3347 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3348 BuiltinLoc);
3349}
3350
3351
Steve Naroff1b273c42007-09-16 14:56:35 +00003352Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00003353 TypeTy *arg1, TypeTy *arg2,
3354 SourceLocation RPLoc) {
3355 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3356 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3357
3358 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3359
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003360 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00003361}
3362
Steve Naroff1b273c42007-09-16 14:56:35 +00003363Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00003364 ExprTy *expr1, ExprTy *expr2,
3365 SourceLocation RPLoc) {
3366 Expr *CondExpr = static_cast<Expr*>(cond);
3367 Expr *LHSExpr = static_cast<Expr*>(expr1);
3368 Expr *RHSExpr = static_cast<Expr*>(expr2);
3369
3370 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3371
3372 // The conditional expression is required to be a constant expression.
3373 llvm::APSInt condEval(32);
3374 SourceLocation ExpLoc;
3375 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003376 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3377 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00003378
3379 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3380 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3381 RHSExpr->getType();
3382 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3383}
3384
Steve Naroff4eb206b2008-09-03 18:15:37 +00003385//===----------------------------------------------------------------------===//
3386// Clang Extensions.
3387//===----------------------------------------------------------------------===//
3388
3389/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00003390void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003391 // Analyze block parameters.
3392 BlockSemaInfo *BSI = new BlockSemaInfo();
3393
3394 // Add BSI to CurBlock.
3395 BSI->PrevBlockInfo = CurBlock;
3396 CurBlock = BSI;
3397
3398 BSI->ReturnType = 0;
3399 BSI->TheScope = BlockScope;
3400
Steve Naroff090276f2008-10-10 01:28:17 +00003401 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3402 PushDeclContext(BSI->TheDecl);
3403}
3404
3405void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003406 // Analyze arguments to block.
3407 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3408 "Not a function declarator!");
3409 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3410
Steve Naroff090276f2008-10-10 01:28:17 +00003411 CurBlock->hasPrototype = FTI.hasPrototype;
3412 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003413
3414 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3415 // no arguments, not a function that takes a single void argument.
3416 if (FTI.hasPrototype &&
3417 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3418 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3419 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3420 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00003421 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003422 } else if (FTI.hasPrototype) {
3423 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00003424 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3425 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003426 }
Steve Naroff090276f2008-10-10 01:28:17 +00003427 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3428
3429 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3430 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3431 // If this has an identifier, add it to the scope stack.
3432 if ((*AI)->getIdentifier())
3433 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003434}
3435
3436/// ActOnBlockError - If there is an error parsing a block, this callback
3437/// is invoked to pop the information about the block from the action impl.
3438void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3439 // Ensure that CurBlock is deleted.
3440 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3441
3442 // Pop off CurBlock, handle nested blocks.
3443 CurBlock = CurBlock->PrevBlockInfo;
3444
3445 // FIXME: Delete the ParmVarDecl objects as well???
3446
3447}
3448
3449/// ActOnBlockStmtExpr - This is called when the body of a block statement
3450/// literal was successfully completed. ^(int x){...}
3451Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3452 Scope *CurScope) {
3453 // Ensure that CurBlock is deleted.
3454 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3455 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3456
Steve Naroff090276f2008-10-10 01:28:17 +00003457 PopDeclContext();
3458
Steve Naroff4eb206b2008-09-03 18:15:37 +00003459 // Pop off CurBlock, handle nested blocks.
3460 CurBlock = CurBlock->PrevBlockInfo;
3461
3462 QualType RetTy = Context.VoidTy;
3463 if (BSI->ReturnType)
3464 RetTy = QualType(BSI->ReturnType, 0);
3465
3466 llvm::SmallVector<QualType, 8> ArgTypes;
3467 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3468 ArgTypes.push_back(BSI->Params[i]->getType());
3469
3470 QualType BlockTy;
3471 if (!BSI->hasPrototype)
3472 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3473 else
3474 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003475 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003476
3477 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003478
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003479 BSI->TheDecl->setBody(Body.take());
3480 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003481}
3482
Nate Begeman67295d02008-01-30 20:50:20 +00003483/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003484/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003485/// The number of arguments has already been validated to match the number of
3486/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003487static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3488 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003489 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003490 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003491 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3492 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003493
3494 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00003495 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00003496 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003497 return true;
3498}
3499
3500Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3501 SourceLocation *CommaLocs,
3502 SourceLocation BuiltinLoc,
3503 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003504 // __builtin_overload requires at least 2 arguments
3505 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003506 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3507 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003508
Nate Begemane2ce1d92008-01-17 17:46:27 +00003509 // The first argument is required to be a constant expression. It tells us
3510 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003511 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003512 Expr *NParamsExpr = Args[0];
3513 llvm::APSInt constEval(32);
3514 SourceLocation ExpLoc;
3515 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003516 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3517 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003518
3519 // Verify that the number of parameters is > 0
3520 unsigned NumParams = constEval.getZExtValue();
3521 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003522 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3523 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003524 // Verify that we have at least 1 + NumParams arguments to the builtin.
3525 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003526 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3527 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003528
3529 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00003530 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003531 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003532 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3533 // UsualUnaryConversions will convert the function DeclRefExpr into a
3534 // pointer to function.
3535 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00003536 const FunctionTypeProto *FnType = 0;
3537 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3538 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003539
3540 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3541 // parameters, and the number of parameters must match the value passed to
3542 // the builtin.
3543 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003544 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3545 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003546
3547 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00003548 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00003549 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003550 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003551 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003552 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3553 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00003554 // Remember our match, and continue processing the remaining arguments
3555 // to catch any errors.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003556 OE = new OverloadExpr(Args, NumArgs, i,
3557 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00003558 BuiltinLoc, RParenLoc);
3559 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003560 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00003561 // Return the newly created OverloadExpr node, if we succeded in matching
3562 // exactly one of the candidate functions.
3563 if (OE)
3564 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003565
3566 // If we didn't find a matching function Expr in the __builtin_overload list
3567 // the return an error.
3568 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00003569 for (unsigned i = 0; i != NumParams; ++i) {
3570 if (i != 0) typeNames += ", ";
3571 typeNames += Args[i+1]->getType().getAsString();
3572 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003573
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003574 return Diag(BuiltinLoc, diag::err_overload_no_match)
3575 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003576}
3577
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003578Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3579 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00003580 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003581 Expr *E = static_cast<Expr*>(expr);
3582 QualType T = QualType::getFromOpaquePtr(type);
3583
3584 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003585
3586 // Get the va_list type
3587 QualType VaListType = Context.getBuiltinVaListType();
3588 // Deal with implicit array decay; for example, on x86-64,
3589 // va_list is an array, but it's supposed to decay to
3590 // a pointer for va_arg.
3591 if (VaListType->isArrayType())
3592 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00003593 // Make sure the input expression also decays appropriately.
3594 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003595
3596 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003597 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003598 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00003599 << E->getType() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003600
3601 // FIXME: Warn if a non-POD type is passed in.
3602
Douglas Gregor9d293df2008-10-28 00:22:11 +00003603 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003604}
3605
Douglas Gregor2d8b2732008-11-29 04:51:27 +00003606Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
3607 // The type of __null will be int or long, depending on the size of
3608 // pointers on the target.
3609 QualType Ty;
3610 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
3611 Ty = Context.IntTy;
3612 else
3613 Ty = Context.LongTy;
3614
3615 return new GNUNullExpr(Ty, TokenLoc);
3616}
3617
Chris Lattner5cf216b2008-01-04 18:04:52 +00003618bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3619 SourceLocation Loc,
3620 QualType DstType, QualType SrcType,
3621 Expr *SrcExpr, const char *Flavor) {
3622 // Decode the result (notice that AST's are still created for extensions).
3623 bool isInvalid = false;
3624 unsigned DiagKind;
3625 switch (ConvTy) {
3626 default: assert(0 && "Unknown conversion type");
3627 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003628 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00003629 DiagKind = diag::ext_typecheck_convert_pointer_int;
3630 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003631 case IntToPointer:
3632 DiagKind = diag::ext_typecheck_convert_int_pointer;
3633 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003634 case IncompatiblePointer:
3635 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3636 break;
3637 case FunctionVoidPointer:
3638 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3639 break;
3640 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00003641 // If the qualifiers lost were because we were applying the
3642 // (deprecated) C++ conversion from a string literal to a char*
3643 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3644 // Ideally, this check would be performed in
3645 // CheckPointerTypesForAssignment. However, that would require a
3646 // bit of refactoring (so that the second argument is an
3647 // expression, rather than a type), which should be done as part
3648 // of a larger effort to fix CheckPointerTypesForAssignment for
3649 // C++ semantics.
3650 if (getLangOptions().CPlusPlus &&
3651 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3652 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003653 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3654 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003655 case IntToBlockPointer:
3656 DiagKind = diag::err_int_to_block_pointer;
3657 break;
3658 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00003659 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003660 break;
Steve Naroff39579072008-10-14 22:18:38 +00003661 case IncompatibleObjCQualifiedId:
3662 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3663 // it can give a more specific diagnostic.
3664 DiagKind = diag::warn_incompatible_qualified_id;
3665 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003666 case Incompatible:
3667 DiagKind = diag::err_typecheck_convert_incompatible;
3668 isInvalid = true;
3669 break;
3670 }
3671
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003672 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3673 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00003674 return isInvalid;
3675}
Anders Carlssone21555e2008-11-30 19:50:32 +00003676
3677bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
3678{
3679 Expr::EvalResult EvalResult;
3680
3681 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
3682 EvalResult.HasSideEffects) {
3683 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
3684
3685 if (EvalResult.Diag) {
3686 // We only show the note if it's not the usual "invalid subexpression"
3687 // or if it's actually in a subexpression.
3688 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
3689 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
3690 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3691 }
3692
3693 return true;
3694 }
3695
3696 if (EvalResult.Diag) {
3697 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
3698 E->getSourceRange();
3699
3700 // Print the reason it's not a constant.
3701 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
3702 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3703 }
3704
3705 if (Result)
3706 *Result = EvalResult.Val.getInt();
3707 return false;
3708}