blob: ba1bb2544d25800b23715cc6124282ac9c382550 [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)
420 << Name.getAsString() << 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 Lattnerfa25bbb2008-11-19 05:08:23 +0000425 return Diag(Loc, diag::err_undeclared_var_use) << Name.getAsString();
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)
434 << FD->getName();
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)
438 << FD->getName();
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 Lattnerfa25bbb2008-11-19 05:08:23 +0000448 return Diag(Loc, diag::err_invalid_non_static_member_use) << FD->getName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000449 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 if (isa<TypedefDecl>(D))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000451 return Diag(Loc, diag::err_unexpected_typedef) << Name.getAsString();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000452 if (isa<ObjCInterfaceDecl>(D))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000453 return Diag(Loc, diag::err_unexpected_interface) << Name.getAsString();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000454 if (isa<NamespaceDecl>(D))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000455 return Diag(Loc, diag::err_unexpected_namespace) << Name.getAsString();
Reid Spencer5f016e22007-07-11 17:01:13 +0000456
Steve Naroffdd972f22008-09-05 22:11:13 +0000457 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000458 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
459 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
460
Steve Naroffdd972f22008-09-05 22:11:13 +0000461 ValueDecl *VD = cast<ValueDecl>(D);
462
463 // check if referencing an identifier with __attribute__((deprecated)).
464 if (VD->getAttr<DeprecatedAttr>())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000465 Diag(Loc, diag::warn_deprecated) << VD->getName();
Steve Naroffdd972f22008-09-05 22:11:13 +0000466
467 // Only create DeclRefExpr's for valid Decl's.
468 if (VD->isInvalidDecl())
469 return true;
Chris Lattner639e2d32008-10-20 05:16:36 +0000470
471 // If the identifier reference is inside a block, and it refers to a value
472 // that is outside the block, create a BlockDeclRefExpr instead of a
473 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
474 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000475 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000476 // We do not do this for things like enum constants, global variables, etc,
477 // as they do not get snapshotted.
478 //
479 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000480 // The BlocksAttr indicates the variable is bound by-reference.
481 if (VD->getAttr<BlocksAttr>())
Douglas Gregor9d293df2008-10-28 00:22:11 +0000482 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
483 Loc, true);
Steve Naroff090276f2008-10-10 01:28:17 +0000484
485 // Variable will be bound by-copy, make it const within the closure.
486 VD->getType().addConst();
Douglas Gregor9d293df2008-10-28 00:22:11 +0000487 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
488 Loc, false);
Steve Naroff090276f2008-10-10 01:28:17 +0000489 }
490 // If this reference is not in a block or if the referenced variable is
491 // within the block, create a normal DeclRefExpr.
Douglas Gregore0a5d5f2008-10-22 04:14:44 +0000492 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000493}
494
Chris Lattnerd9f69102008-08-10 01:53:14 +0000495Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000496 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000497 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000498
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000500 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000501 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
502 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
503 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000504 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000505
506 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000507 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000508 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000509
Chris Lattnerfa28b302008-01-12 08:14:25 +0000510 // Pre-defined identifiers are of type char[x], where x is the length of the
511 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000512 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000513 if (getCurFunctionDecl())
514 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000515 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000516 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000517
Chris Lattner8f978d52008-01-12 19:32:28 +0000518 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000519 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000520 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000521 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000522}
523
Steve Narofff69936d2007-09-16 03:34:24 +0000524Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000525 llvm::SmallString<16> CharBuffer;
526 CharBuffer.resize(Tok.getLength());
527 const char *ThisTokBegin = &CharBuffer[0];
528 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
529
530 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
531 Tok.getLocation(), PP);
532 if (Literal.hadError())
533 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000534
535 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
536
Chris Lattnerc250aae2008-06-07 22:35:38 +0000537 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
538 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000539}
540
Steve Narofff69936d2007-09-16 03:34:24 +0000541Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 // fast path for a single digit (which is quite common). A single digit
543 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
544 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000545 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000546
Chris Lattner98be4942008-03-05 18:54:05 +0000547 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000548 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 Context.IntTy,
550 Tok.getLocation()));
551 }
552 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000553 // Add padding so that NumericLiteralParser can overread by one character.
554 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 const char *ThisTokBegin = &IntegerBuffer[0];
556
557 // Get the spelling of the token, which eliminates trigraphs, etc.
558 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner28997ec2008-09-30 20:51:14 +0000559
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
561 Tok.getLocation(), PP);
562 if (Literal.hadError)
563 return ExprResult(true);
564
Chris Lattner5d661452007-08-26 03:42:43 +0000565 Expr *Res;
566
567 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000568 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000569 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000570 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000571 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000572 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000573 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000574 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000575
576 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
577
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000578 // isExact will be set by GetFloatValue().
579 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000580 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000581 Ty, Tok.getLocation());
582
Chris Lattner5d661452007-08-26 03:42:43 +0000583 } else if (!Literal.isIntegerLiteral()) {
584 return ExprResult(true);
585 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000586 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000587
Neil Boothb9449512007-08-29 22:00:19 +0000588 // long long is a C99 feature.
589 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000590 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000591 Diag(Tok.getLocation(), diag::ext_longlong);
592
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000594 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000595
596 if (Literal.GetIntegerValue(ResultVal)) {
597 // If this value didn't fit into uintmax_t, warn and force to ull.
598 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000599 Ty = Context.UnsignedLongLongTy;
600 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000601 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 } else {
603 // If this value fits into a ULL, try to figure out what else it fits into
604 // according to the rules of C99 6.4.4.1p5.
605
606 // Octal, Hexadecimal, and integers with a U suffix are allowed to
607 // be an unsigned int.
608 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
609
610 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000611 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000612 if (!Literal.isLong && !Literal.isLongLong) {
613 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000614 unsigned IntSize = Context.Target.getIntWidth();
615
Reid Spencer5f016e22007-07-11 17:01:13 +0000616 // Does it fit in a unsigned int?
617 if (ResultVal.isIntN(IntSize)) {
618 // Does it fit in a signed int?
619 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000620 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000621 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000622 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000623 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 }
626
627 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000628 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000629 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000630
631 // Does it fit in a unsigned long?
632 if (ResultVal.isIntN(LongSize)) {
633 // Does it fit in a signed long?
634 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000635 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000636 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000637 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000638 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 }
641
642 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000643 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000644 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000645
646 // Does it fit in a unsigned long long?
647 if (ResultVal.isIntN(LongLongSize)) {
648 // Does it fit in a signed long long?
649 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000650 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000651 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000652 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000653 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 }
655 }
656
657 // If we still couldn't decide a type, we probably have something that
658 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000659 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000661 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000662 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000663 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000664
665 if (ResultVal.getBitWidth() != Width)
666 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 }
668
Chris Lattnerf0467b32008-04-02 04:24:33 +0000669 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 }
Chris Lattner5d661452007-08-26 03:42:43 +0000671
672 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
673 if (Literal.isImaginary)
674 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
675
676 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000677}
678
Steve Narofff69936d2007-09-16 03:34:24 +0000679Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000680 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000681 Expr *E = (Expr *)Val;
682 assert((E != 0) && "ActOnParenExpr() missing expr");
683 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000684}
685
686/// The UsualUnaryConversions() function is *not* called by this routine.
687/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +0000688bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
689 SourceLocation OpLoc,
690 const SourceRange &ExprRange,
691 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 // C99 6.5.3.4p1:
693 if (isa<FunctionType>(exprType) && isSizeof)
694 // alignof(function) is allowed.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000695 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 else if (exprType->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000697 Diag(OpLoc, diag::ext_sizeof_void_type)
698 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
699 else if (exprType->isIncompleteType())
700 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
701 diag::err_alignof_incomplete_type)
702 << exprType.getAsString() << ExprRange;
Sebastian Redl05189992008-11-11 17:56:53 +0000703
704 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000705}
706
Sebastian Redl05189992008-11-11 17:56:53 +0000707/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
708/// the same for @c alignof and @c __alignof
709/// Note that the ArgRange is invalid if isType is false.
710Action::ExprResult
711Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
712 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 // If error parsing type, ignore.
Sebastian Redl05189992008-11-11 17:56:53 +0000714 if (TyOrEx == 0) return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000715
Sebastian Redl05189992008-11-11 17:56:53 +0000716 QualType ArgTy;
717 SourceRange Range;
718 if (isType) {
719 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
720 Range = ArgRange;
721 } else {
722 // Get the end location.
723 Expr *ArgEx = (Expr *)TyOrEx;
724 Range = ArgEx->getSourceRange();
725 ArgTy = ArgEx->getType();
726 }
727
728 // Verify that the operand is valid.
729 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 return true;
Sebastian Redl05189992008-11-11 17:56:53 +0000731
732 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
733 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
734 OpLoc, Range.getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +0000735}
736
Chris Lattner5d794252007-08-24 21:41:10 +0000737QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000738 DefaultFunctionArrayConversion(V);
739
Chris Lattnercc26ed72007-08-26 05:39:26 +0000740 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000741 if (const ComplexType *CT = V->getType()->getAsComplexType())
742 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000743
744 // Otherwise they pass through real integer and floating point types here.
745 if (V->getType()->isArithmeticType())
746 return V->getType();
747
748 // Reject anything else.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000749 Diag(Loc, diag::err_realimag_invalid_type) << V->getType().getAsString();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000750 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000751}
752
753
Reid Spencer5f016e22007-07-11 17:01:13 +0000754
Douglas Gregor74253732008-11-19 15:42:04 +0000755Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 tok::TokenKind Kind,
757 ExprTy *Input) {
Douglas Gregor74253732008-11-19 15:42:04 +0000758 Expr *Arg = (Expr *)Input;
759
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 UnaryOperator::Opcode Opc;
761 switch (Kind) {
762 default: assert(0 && "Unknown unary op!");
763 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
764 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
765 }
Douglas Gregor74253732008-11-19 15:42:04 +0000766
767 if (getLangOptions().CPlusPlus &&
768 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
769 // Which overloaded operator?
770 OverloadedOperatorKind OverOp =
771 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
772
773 // C++ [over.inc]p1:
774 //
775 // [...] If the function is a member function with one
776 // parameter (which shall be of type int) or a non-member
777 // function with two parameters (the second of which shall be
778 // of type int), it defines the postfix increment operator ++
779 // for objects of that type. When the postfix increment is
780 // called as a result of using the ++ operator, the int
781 // argument will have value zero.
782 Expr *Args[2] = {
783 Arg,
784 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
785 /*isSigned=*/true),
786 Context.IntTy, SourceLocation())
787 };
788
789 // Build the candidate set for overloading
790 OverloadCandidateSet CandidateSet;
791 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
792
793 // Perform overload resolution.
794 OverloadCandidateSet::iterator Best;
795 switch (BestViableFunction(CandidateSet, Best)) {
796 case OR_Success: {
797 // We found a built-in operator or an overloaded operator.
798 FunctionDecl *FnDecl = Best->Function;
799
800 if (FnDecl) {
801 // We matched an overloaded operator. Build a call to that
802 // operator.
803
804 // Convert the arguments.
805 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
806 if (PerformObjectArgumentInitialization(Arg, Method))
807 return true;
808 } else {
809 // Convert the arguments.
810 if (PerformCopyInitialization(Arg,
811 FnDecl->getParamDecl(0)->getType(),
812 "passing"))
813 return true;
814 }
815
816 // Determine the result type
817 QualType ResultTy
818 = FnDecl->getType()->getAsFunctionType()->getResultType();
819 ResultTy = ResultTy.getNonReferenceType();
820
821 // Build the actual expression node.
822 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
823 SourceLocation());
824 UsualUnaryConversions(FnExpr);
825
826 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
827 } else {
828 // We matched a built-in operator. Convert the arguments, then
829 // break out so that we will build the appropriate built-in
830 // operator node.
831 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
832 "passing"))
833 return true;
834
835 break;
836 }
837 }
838
839 case OR_No_Viable_Function:
840 // No viable function; fall through to handling this as a
841 // built-in operator, which will produce an error message for us.
842 break;
843
844 case OR_Ambiguous:
845 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
846 << UnaryOperator::getOpcodeStr(Opc)
847 << Arg->getSourceRange();
848 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
849 return true;
850 }
851
852 // Either we found no viable overloaded operator or we matched a
853 // built-in operator. In either case, fall through to trying to
854 // build a built-in operation.
855 }
856
857 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 if (result.isNull())
859 return true;
Douglas Gregor74253732008-11-19 15:42:04 +0000860 return new UnaryOperator(Arg, Opc, result, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000861}
862
863Action::ExprResult Sema::
Douglas Gregor337c6b92008-11-19 17:17:41 +0000864ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000866 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000867
Douglas Gregor337c6b92008-11-19 17:17:41 +0000868 if (getLangOptions().CPlusPlus &&
869 LHSExp->getType()->isRecordType() ||
870 LHSExp->getType()->isEnumeralType() ||
871 RHSExp->getType()->isRecordType() ||
872 RHSExp->getType()->isRecordType()) {
873 // Add the appropriate overloaded operators (C++ [over.match.oper])
874 // to the candidate set.
875 OverloadCandidateSet CandidateSet;
876 Expr *Args[2] = { LHSExp, RHSExp };
877 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
878
879 // Perform overload resolution.
880 OverloadCandidateSet::iterator Best;
881 switch (BestViableFunction(CandidateSet, Best)) {
882 case OR_Success: {
883 // We found a built-in operator or an overloaded operator.
884 FunctionDecl *FnDecl = Best->Function;
885
886 if (FnDecl) {
887 // We matched an overloaded operator. Build a call to that
888 // operator.
889
890 // Convert the arguments.
891 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
892 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
893 PerformCopyInitialization(RHSExp,
894 FnDecl->getParamDecl(0)->getType(),
895 "passing"))
896 return true;
897 } else {
898 // Convert the arguments.
899 if (PerformCopyInitialization(LHSExp,
900 FnDecl->getParamDecl(0)->getType(),
901 "passing") ||
902 PerformCopyInitialization(RHSExp,
903 FnDecl->getParamDecl(1)->getType(),
904 "passing"))
905 return true;
906 }
907
908 // Determine the result type
909 QualType ResultTy
910 = FnDecl->getType()->getAsFunctionType()->getResultType();
911 ResultTy = ResultTy.getNonReferenceType();
912
913 // Build the actual expression node.
914 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
915 SourceLocation());
916 UsualUnaryConversions(FnExpr);
917
918 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
919 } else {
920 // We matched a built-in operator. Convert the arguments, then
921 // break out so that we will build the appropriate built-in
922 // operator node.
923 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
924 "passing") ||
925 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
926 "passing"))
927 return true;
928
929 break;
930 }
931 }
932
933 case OR_No_Viable_Function:
934 // No viable function; fall through to handling this as a
935 // built-in operator, which will produce an error message for us.
936 break;
937
938 case OR_Ambiguous:
939 Diag(LLoc, diag::err_ovl_ambiguous_oper)
940 << "[]"
941 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
942 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
943 return true;
944 }
945
946 // Either we found no viable overloaded operator or we matched a
947 // built-in operator. In either case, fall through to trying to
948 // build a built-in operation.
949 }
950
Chris Lattner12d9ff62007-07-16 00:14:47 +0000951 // Perform default conversions.
952 DefaultFunctionArrayConversion(LHSExp);
953 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000954
Chris Lattner12d9ff62007-07-16 00:14:47 +0000955 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000956
Reid Spencer5f016e22007-07-11 17:01:13 +0000957 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000958 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000959 // in the subscript position. As a result, we need to derive the array base
960 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000961 Expr *BaseExpr, *IndexExpr;
962 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000963 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000964 BaseExpr = LHSExp;
965 IndexExpr = RHSExp;
966 // FIXME: need to deal with const...
967 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000968 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000969 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000970 BaseExpr = RHSExp;
971 IndexExpr = LHSExp;
972 // FIXME: need to deal with const...
973 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000974 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
975 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000976 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000977
978 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000979 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
980 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000981 return Diag(LLoc, diag::err_ext_vector_component_access)
982 << SourceRange(LLoc, RLoc);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000983 // FIXME: need to deal with const...
984 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000985 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000986 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
987 << RHSExp->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 }
989 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000990 if (!IndexExpr->getType()->isIntegerType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000991 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
992 << IndexExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +0000993
Chris Lattner12d9ff62007-07-16 00:14:47 +0000994 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
995 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000996 // void (*)(int)) and pointers to incomplete types. Functions are not
997 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000998 if (!ResultType->isObjectType())
999 return Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001000 diag::err_typecheck_subscript_not_object)
1001 << BaseExpr->getType().getAsString() << BaseExpr->getSourceRange();
Chris Lattner12d9ff62007-07-16 00:14:47 +00001002
1003 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001004}
1005
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001006QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001007CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001008 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001009 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001010
1011 // This flag determines whether or not the component is to be treated as a
1012 // special name, or a regular GLSL-style component access.
1013 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001014
1015 // The vector accessor can't exceed the number of elements.
1016 const char *compStr = CompName.getName();
1017 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001018 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1019 << baseType.getAsString() << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001020 return QualType();
1021 }
Nate Begeman8a997642008-05-09 06:41:27 +00001022
1023 // Check that we've found one of the special components, or that the component
1024 // names must come from the same set.
1025 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1026 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1027 SpecialComponent = true;
1028 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001029 do
1030 compStr++;
1031 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1032 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1033 do
1034 compStr++;
1035 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1036 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1037 do
1038 compStr++;
1039 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1040 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001041
Nate Begeman8a997642008-05-09 06:41:27 +00001042 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001043 // We didn't get to the end of the string. This means the component names
1044 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001045 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1046 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001047 return QualType();
1048 }
1049 // Each component accessor can't exceed the vector type.
1050 compStr = CompName.getName();
1051 while (*compStr) {
1052 if (vecType->isAccessorWithinNumElements(*compStr))
1053 compStr++;
1054 else
1055 break;
1056 }
Nate Begeman8a997642008-05-09 06:41:27 +00001057 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001058 // We didn't get to the end of the string. This means a component accessor
1059 // exceeds the number of elements in the vector.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001060 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1061 << baseType.getAsString() << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001062 return QualType();
1063 }
Nate Begeman8a997642008-05-09 06:41:27 +00001064
1065 // If we have a special component name, verify that the current vector length
1066 // is an even number, since all special component names return exactly half
1067 // the elements.
1068 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001069 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1070 << baseType.getAsString() << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001071 return QualType();
1072 }
1073
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001074 // The component accessor looks fine - now we need to compute the actual type.
1075 // The vector type is implied by the component accessor. For example,
1076 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001077 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1078 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner3c73c412008-11-19 08:23:25 +00001079 : CompName.getLength();
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001080 if (CompSize == 1)
1081 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001082
Nate Begeman213541a2008-04-18 23:10:10 +00001083 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001084 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001085 // diagostics look bad. We want extended vector types to appear built-in.
1086 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1087 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1088 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001089 }
1090 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001091}
1092
Daniel Dunbar2307d312008-09-03 01:05:41 +00001093/// constructSetterName - Return the setter name for the given
1094/// identifier, i.e. "set" + Name where the initial character of Name
1095/// has been capitalized.
1096// FIXME: Merge with same routine in Parser. But where should this
1097// live?
1098static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1099 const IdentifierInfo *Name) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001100 llvm::SmallString<100> SelectorName;
Chris Lattner69d27b92008-11-20 07:09:32 +00001101 SelectorName = "set";
Chris Lattner3c73c412008-11-19 08:23:25 +00001102 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
Daniel Dunbar2307d312008-09-03 01:05:41 +00001103 SelectorName[3] = toupper(SelectorName[3]);
Chris Lattner3c73c412008-11-19 08:23:25 +00001104 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001105}
1106
Reid Spencer5f016e22007-07-11 17:01:13 +00001107Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001108ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 tok::TokenKind OpKind, SourceLocation MemberLoc,
1110 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001111 Expr *BaseExpr = static_cast<Expr *>(Base);
1112 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001113
1114 // Perform default conversions.
1115 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001116
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001117 QualType BaseType = BaseExpr->getType();
1118 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001119
Chris Lattner68a057b2008-07-21 04:36:39 +00001120 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1121 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001123 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001124 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001125 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1126 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001127 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001128 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1129 << BaseType.getAsString() << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001131
Chris Lattner68a057b2008-07-21 04:36:39 +00001132 // Handle field access to simple records. This also handles access to fields
1133 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001134 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001135 RecordDecl *RDecl = RTy->getDecl();
1136 if (RTy->isIncompleteType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001137 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
1138 << RDecl->getName() << BaseExpr->getSourceRange();
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001139 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001140 FieldDecl *MemberDecl = RDecl->getMember(&Member);
1141 if (!MemberDecl)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001142 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner3c73c412008-11-19 08:23:25 +00001143 << &Member << BaseExpr->getSourceRange();
Eli Friedman51019072008-02-06 22:48:16 +00001144
1145 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +00001146 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +00001147 QualType MemberType = MemberDecl->getType();
1148 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +00001149 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Sebastian Redla11f42f2008-11-17 23:24:37 +00001150 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) {
1151 if (CXXMember->isMutable())
1152 combinedQualifiers &= ~QualType::Const;
1153 }
Eli Friedman51019072008-02-06 22:48:16 +00001154 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1155
Chris Lattner68a057b2008-07-21 04:36:39 +00001156 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +00001157 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001158 }
1159
Chris Lattnera38e6b12008-07-21 04:59:05 +00001160 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1161 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001162 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1163 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001164 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001165 OpKind == tok::arrow);
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001166 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner3c73c412008-11-19 08:23:25 +00001167 << IFTy->getDecl()->getName() << &Member
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001168 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001169 }
1170
Chris Lattnera38e6b12008-07-21 04:59:05 +00001171 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1172 // pointer to a (potentially qualified) interface type.
1173 const PointerType *PTy;
1174 const ObjCInterfaceType *IFTy;
1175 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1176 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1177 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001178
Daniel Dunbar2307d312008-09-03 01:05:41 +00001179 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001180 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1181 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1182
Daniel Dunbar2307d312008-09-03 01:05:41 +00001183 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001184 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1185 E = IFTy->qual_end(); I != E; ++I)
1186 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1187 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001188
1189 // If that failed, look for an "implicit" property by seeing if the nullary
1190 // selector is implemented.
1191
1192 // FIXME: The logic for looking up nullary and unary selectors should be
1193 // shared with the code in ActOnInstanceMessage.
1194
1195 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1196 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1197
1198 // If this reference is in an @implementation, check for 'private' methods.
1199 if (!Getter)
1200 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1201 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1202 if (ObjCImplementationDecl *ImpDecl =
1203 ObjCImplementations[ClassDecl->getIdentifier()])
1204 Getter = ImpDecl->getInstanceMethod(Sel);
1205
Steve Naroff7692ed62008-10-22 19:16:27 +00001206 // Look through local category implementations associated with the class.
1207 if (!Getter) {
1208 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1209 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1210 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1211 }
1212 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001213 if (Getter) {
1214 // If we found a getter then this may be a valid dot-reference, we
1215 // need to also look for the matching setter.
1216 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1217 &Member);
1218 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1219 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1220
1221 if (!Setter) {
1222 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1223 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1224 if (ObjCImplementationDecl *ImpDecl =
1225 ObjCImplementations[ClassDecl->getIdentifier()])
1226 Setter = ImpDecl->getInstanceMethod(SetterSel);
1227 }
1228
1229 // FIXME: There are some issues here. First, we are not
1230 // diagnosing accesses to read-only properties because we do not
1231 // know if this is a getter or setter yet. Second, we are
1232 // checking that the type of the setter matches the type we
1233 // expect.
1234 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1235 MemberLoc, BaseExpr);
1236 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001237 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001238 // Handle properties on qualified "id" protocols.
1239 const ObjCQualifiedIdType *QIdTy;
1240 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1241 // Check protocols on qualified interfaces.
1242 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1243 E = QIdTy->qual_end(); I != E; ++I)
1244 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1245 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1246 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001247 // Handle 'field access' to vectors, such as 'V.xx'.
1248 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1249 // Component access limited to variables (reject vec4.rg.g).
1250 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1251 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001252 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1253 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001254 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1255 if (ret.isNull())
1256 return true;
1257 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1258 }
1259
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001260 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1261 << BaseType.getAsString() << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001262}
1263
Steve Narofff69936d2007-09-16 03:34:24 +00001264/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001265/// This provides the location of the left/right parens and a list of comma
1266/// locations.
1267Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001268ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001269 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001271 Expr *Fn = static_cast<Expr *>(fn);
1272 Expr **Args = reinterpret_cast<Expr**>(args);
1273 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001274 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001275 OverloadedFunctionDecl *Ovl = NULL;
1276
1277 // If we're directly calling a function or a set of overloaded
1278 // functions, get the appropriate declaration.
1279 {
1280 DeclRefExpr *DRExpr = NULL;
1281 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1282 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1283 else
1284 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1285
1286 if (DRExpr) {
1287 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1288 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1289 }
1290 }
1291
1292 // If we have a set of overloaded functions, perform overload
1293 // resolution to pick the function.
1294 if (Ovl) {
1295 OverloadCandidateSet CandidateSet;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001296 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00001297 OverloadCandidateSet::iterator Best;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001298 switch (BestViableFunction(CandidateSet, Best)) {
1299 case OR_Success:
1300 {
1301 // Success! Let the remainder of this function build a call to
1302 // the function selected by overload resolution.
1303 FDecl = Best->Function;
1304 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1305 Fn->getSourceRange().getBegin());
1306 delete Fn;
1307 Fn = NewFn;
1308 }
1309 break;
1310
1311 case OR_No_Viable_Function:
1312 if (CandidateSet.empty())
1313 Diag(Fn->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001314 diag::err_ovl_no_viable_function_in_call)
1315 << Ovl->getName() << Fn->getSourceRange();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001316 else {
1317 Diag(Fn->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001318 diag::err_ovl_no_viable_function_in_call_with_cands)
1319 << Ovl->getName() << Fn->getSourceRange();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001320 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1321 }
1322 return true;
1323
1324 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001325 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
1326 << Ovl->getName() << Fn->getSourceRange();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001327 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1328 return true;
1329 }
1330 }
Chris Lattner04421082008-04-08 04:40:51 +00001331
Douglas Gregorf9eb9052008-11-19 21:05:33 +00001332 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1333 return BuildCallToObjectOfClassType(Fn, LParenLoc, Args, NumArgs,
1334 CommaLocs, RParenLoc);
1335
Chris Lattner04421082008-04-08 04:40:51 +00001336 // Promote the function operand.
1337 UsualUnaryConversions(Fn);
1338
Chris Lattner925e60d2007-12-28 05:29:59 +00001339 // Make the call expr early, before semantic checks. This guarantees cleanup
1340 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001341 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001342 Context.BoolTy, RParenLoc));
Steve Naroffdd972f22008-09-05 22:11:13 +00001343 const FunctionType *FuncT;
1344 if (!Fn->getType()->isBlockPointerType()) {
1345 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1346 // have type pointer to function".
1347 const PointerType *PT = Fn->getType()->getAsPointerType();
1348 if (PT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001349 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerb1b4d332008-11-21 18:27:34 +00001350 << Fn->getType().getAsString() << Fn->getSourceRange();
Steve Naroffdd972f22008-09-05 22:11:13 +00001351 FuncT = PT->getPointeeType()->getAsFunctionType();
1352 } else { // This is a block call.
1353 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1354 getAsFunctionType();
1355 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001356 if (FuncT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001357 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerb1b4d332008-11-21 18:27:34 +00001358 << Fn->getType().getAsString() << Fn->getSourceRange();
Chris Lattner925e60d2007-12-28 05:29:59 +00001359
1360 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001361 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001362
Chris Lattner925e60d2007-12-28 05:29:59 +00001363 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1365 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001366 unsigned NumArgsInProto = Proto->getNumArgs();
1367 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001368
Chris Lattner04421082008-04-08 04:40:51 +00001369 // If too few arguments are available (and we don't have default
1370 // arguments for the remaining parameters), don't make the call.
1371 if (NumArgs < NumArgsInProto) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001372 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1373 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1374 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1375 // Use default arguments for missing arguments
1376 NumArgsToCheck = NumArgsInProto;
1377 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001378 }
1379
Chris Lattner925e60d2007-12-28 05:29:59 +00001380 // If too many are passed and not variadic, error on the extras and drop
1381 // them.
1382 if (NumArgs > NumArgsInProto) {
1383 if (!Proto->isVariadic()) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001384 Diag(Args[NumArgsInProto]->getLocStart(),
1385 diag::err_typecheck_call_too_many_args)
1386 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001387 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1388 Args[NumArgs-1]->getLocEnd());
Chris Lattner925e60d2007-12-28 05:29:59 +00001389 // This deletes the extra arguments.
1390 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 }
1392 NumArgsToCheck = NumArgsInProto;
1393 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001394
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001396 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001397 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001398
1399 Expr *Arg;
1400 if (i < NumArgs)
1401 Arg = Args[i];
1402 else
1403 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001404 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001405
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001406 // Pass the argument.
1407 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001408 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001409
1410 TheCall->setArg(i, Arg);
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001412
1413 // If this is a variadic call, handle args passed through "...".
1414 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001415 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001416 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1417 Expr *Arg = Args[i];
1418 DefaultArgumentPromotion(Arg);
1419 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001420 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001421 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001422 } else {
1423 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1424
Steve Naroffb291ab62007-08-28 23:30:39 +00001425 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001426 for (unsigned i = 0; i != NumArgs; i++) {
1427 Expr *Arg = Args[i];
1428 DefaultArgumentPromotion(Arg);
1429 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001430 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001432
Chris Lattner59907c42007-08-10 20:18:51 +00001433 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001434 if (FDecl)
1435 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001436
Chris Lattner925e60d2007-12-28 05:29:59 +00001437 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001438}
1439
1440Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001441ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001442 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001443 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001444 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001445 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001446 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001447 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001448
Eli Friedman6223c222008-05-20 05:22:08 +00001449 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001450 if (literalType->isVariableArrayType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001451 return Diag(LParenLoc, diag::err_variable_object_no_init)
1452 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001453 } else if (literalType->isIncompleteType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001454 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
1455 << literalType.getAsString()
1456 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001457 }
1458
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001459 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
1460 "temporary"))
Steve Naroff58d18212008-01-09 20:58:06 +00001461 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001462
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001463 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001464 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001465 if (CheckForConstantInitializer(literalExpr, literalType))
1466 return true;
1467 }
Chris Lattner220ad7c2008-10-26 23:35:51 +00001468 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1469 isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001470}
1471
1472Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001473ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattner220ad7c2008-10-26 23:35:51 +00001474 InitListDesignations &Designators,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001475 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001476 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001477
Steve Naroff08d92e42007-09-15 18:49:24 +00001478 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001479 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001480
Chris Lattner418f6c72008-10-26 23:43:26 +00001481 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1482 Designators.hasAnyDesignators());
Chris Lattnerf0467b32008-04-02 04:24:33 +00001483 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1484 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001485}
1486
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001487/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001488bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001489 UsualUnaryConversions(castExpr);
1490
1491 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1492 // type needs to be scalar.
1493 if (castType->isVoidType()) {
1494 // Cast to void allows any expr type.
1495 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1496 // GCC struct/union extension: allow cast to self.
1497 if (Context.getCanonicalType(castType) !=
1498 Context.getCanonicalType(castExpr->getType()) ||
1499 (!castType->isStructureType() && !castType->isUnionType())) {
1500 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001501 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
1502 << castType.getAsString() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001503 }
1504
1505 // accept this, but emit an ext-warn.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001506 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
1507 << castType.getAsString() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001508 } else if (!castExpr->getType()->isScalarType() &&
1509 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001510 return Diag(castExpr->getLocStart(),
1511 diag::err_typecheck_expect_scalar_operand)
1512 << castExpr->getType().getAsString() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001513 } else if (castExpr->getType()->isVectorType()) {
1514 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1515 return true;
1516 } else if (castType->isVectorType()) {
1517 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1518 return true;
1519 }
1520 return false;
1521}
1522
Chris Lattnerfe23e212007-12-20 00:44:32 +00001523bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001524 assert(VectorTy->isVectorType() && "Not a vector type!");
1525
1526 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001527 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001528 return Diag(R.getBegin(),
1529 Ty->isVectorType() ?
1530 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001531 diag::err_invalid_conversion_between_vector_and_integer)
1532 << VectorTy.getAsString() << Ty.getAsString() << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001533 } else
1534 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001535 diag::err_invalid_conversion_between_vector_and_scalar)
1536 << VectorTy.getAsString() << Ty.getAsString() << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001537
1538 return false;
1539}
1540
Steve Naroff4aa88f82007-07-19 01:06:55 +00001541Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001542ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001544 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001545
1546 Expr *castExpr = static_cast<Expr*>(Op);
1547 QualType castType = QualType::getFromOpaquePtr(Ty);
1548
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001549 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1550 return true;
Steve Naroffb2f9e512008-11-03 23:29:32 +00001551 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001552}
1553
Chris Lattnera21ddb32007-11-26 01:40:58 +00001554/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1555/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001556inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001557 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001558 UsualUnaryConversions(cond);
1559 UsualUnaryConversions(lex);
1560 UsualUnaryConversions(rex);
1561 QualType condT = cond->getType();
1562 QualType lexT = lex->getType();
1563 QualType rexT = rex->getType();
1564
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001566 if (!condT->isScalarType()) { // C99 6.5.15p2
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001567 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
1568 << condT.getAsString();
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 return QualType();
1570 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001571
1572 // Now check the two expressions.
1573
1574 // If both operands have arithmetic type, do the usual arithmetic conversions
1575 // to find a common type: C99 6.5.15p3,5.
1576 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001577 UsualArithmeticConversions(lex, rex);
1578 return lex->getType();
1579 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001580
1581 // If both operands are the same structure or union type, the result is that
1582 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001583 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001584 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001585 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001586 // "If both the operands have structure or union type, the result has
1587 // that type." This implies that CV qualifiers are dropped.
1588 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001590
1591 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001592 // The following || allows only one side to be void (a GCC-ism).
1593 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001594 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001595 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1596 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00001597 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001598 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1599 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00001600 ImpCastExprToType(lex, Context.VoidTy);
1601 ImpCastExprToType(rex, Context.VoidTy);
1602 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001603 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001604 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1605 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001606 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1607 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001608 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001609 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001610 return lexT;
1611 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001612 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1613 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001614 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001615 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001616 return rexT;
1617 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001618 // Handle the case where both operands are pointers before we handle null
1619 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001620 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1621 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1622 // get the "pointed to" types
1623 QualType lhptee = LHSPT->getPointeeType();
1624 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001625
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001626 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1627 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001628 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001629 // Figure out necessary qualifiers (C99 6.5.15p6)
1630 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001631 QualType destType = Context.getPointerType(destPointee);
1632 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1633 ImpCastExprToType(rex, destType); // promote to void*
1634 return destType;
1635 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001636 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001637 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001638 QualType destType = Context.getPointerType(destPointee);
1639 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1640 ImpCastExprToType(rex, destType); // promote to void*
1641 return destType;
1642 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001643
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001644 QualType compositeType = lexT;
1645
1646 // If either type is an Objective-C object type then check
1647 // compatibility according to Objective-C.
1648 if (Context.isObjCObjectPointerType(lexT) ||
1649 Context.isObjCObjectPointerType(rexT)) {
1650 // If both operands are interfaces and either operand can be
1651 // assigned to the other, use that type as the composite
1652 // type. This allows
1653 // xxx ? (A*) a : (B*) b
1654 // where B is a subclass of A.
1655 //
1656 // Additionally, as for assignment, if either type is 'id'
1657 // allow silent coercion. Finally, if the types are
1658 // incompatible then make sure to use 'id' as the composite
1659 // type so the result is acceptable for sending messages to.
1660
1661 // FIXME: This code should not be localized to here. Also this
1662 // should use a compatible check instead of abusing the
1663 // canAssignObjCInterfaces code.
1664 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1665 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1666 if (LHSIface && RHSIface &&
1667 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1668 compositeType = lexT;
1669 } else if (LHSIface && RHSIface &&
1670 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1671 compositeType = rexT;
1672 } else if (Context.isObjCIdType(lhptee) ||
1673 Context.isObjCIdType(rhptee)) {
1674 // FIXME: This code looks wrong, because isObjCIdType checks
1675 // the struct but getObjCIdType returns the pointer to
1676 // struct. This is horrible and should be fixed.
1677 compositeType = Context.getObjCIdType();
1678 } else {
1679 QualType incompatTy = Context.getObjCIdType();
1680 ImpCastExprToType(lex, incompatTy);
1681 ImpCastExprToType(rex, incompatTy);
1682 return incompatTy;
1683 }
1684 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1685 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001686 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
1687 << lexT.getAsString() << rexT.getAsString()
1688 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001689 // In this situation, we assume void* type. No especially good
1690 // reason, but this is what gcc does, and we do have to pick
1691 // to get a consistent AST.
1692 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00001693 ImpCastExprToType(lex, incompatTy);
1694 ImpCastExprToType(rex, incompatTy);
1695 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001696 }
1697 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001698 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1699 // differently qualified versions of compatible types, the result type is
1700 // a pointer to an appropriately qualified version of the *composite*
1701 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001702 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001703 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001704 ImpCastExprToType(lex, compositeType);
1705 ImpCastExprToType(rex, compositeType);
1706 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 }
1708 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001709 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1710 // evaluates to "struct objc_object *" (and is handled above when comparing
1711 // id with statically typed objects).
1712 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1713 // GCC allows qualified id and any Objective-C type to devolve to
1714 // id. Currently localizing to here until clear this should be
1715 // part of ObjCQualifiedIdTypesAreCompatible.
1716 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1717 (lexT->isObjCQualifiedIdType() &&
1718 Context.isObjCObjectPointerType(rexT)) ||
1719 (rexT->isObjCQualifiedIdType() &&
1720 Context.isObjCObjectPointerType(lexT))) {
1721 // FIXME: This is not the correct composite type. This only
1722 // happens to work because id can more or less be used anywhere,
1723 // however this may change the type of method sends.
1724 // FIXME: gcc adds some type-checking of the arguments and emits
1725 // (confusing) incompatible comparison warnings in some
1726 // cases. Investigate.
1727 QualType compositeType = Context.getObjCIdType();
1728 ImpCastExprToType(lex, compositeType);
1729 ImpCastExprToType(rex, compositeType);
1730 return compositeType;
1731 }
1732 }
1733
Steve Naroff61f40a22008-09-10 19:17:48 +00001734 // Selection between block pointer types is ok as long as they are the same.
1735 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1736 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1737 return lexT;
1738
Chris Lattner70d67a92008-01-06 22:42:25 +00001739 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001740 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
1741 << lexT.getAsString() << rexT.getAsString()
1742 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001743 return QualType();
1744}
1745
Steve Narofff69936d2007-09-16 03:34:24 +00001746/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001747/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001748Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 SourceLocation ColonLoc,
1750 ExprTy *Cond, ExprTy *LHS,
1751 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001752 Expr *CondExpr = (Expr *) Cond;
1753 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001754
1755 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1756 // was the condition.
1757 bool isLHSNull = LHSExpr == 0;
1758 if (isLHSNull)
1759 LHSExpr = CondExpr;
1760
Chris Lattner26824902007-07-16 21:39:03 +00001761 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1762 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001763 if (result.isNull())
1764 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001765 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1766 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001767}
1768
Reid Spencer5f016e22007-07-11 17:01:13 +00001769
1770// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1771// being closely modeled after the C99 spec:-). The odd characteristic of this
1772// routine is it effectively iqnores the qualifiers on the top level pointee.
1773// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1774// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001775Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001776Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1777 QualType lhptee, rhptee;
1778
1779 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001780 lhptee = lhsType->getAsPointerType()->getPointeeType();
1781 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001782
1783 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001784 lhptee = Context.getCanonicalType(lhptee);
1785 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001786
Chris Lattner5cf216b2008-01-04 18:04:52 +00001787 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001788
1789 // C99 6.5.16.1p1: This following citation is common to constraints
1790 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1791 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001792 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00001793 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001794 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001795
1796 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1797 // incomplete type and the other is a pointer to a qualified or unqualified
1798 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001799 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001800 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001801 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001802
1803 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001804 assert(rhptee->isFunctionType());
1805 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001806 }
1807
1808 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001809 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001810 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001811
1812 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001813 assert(lhptee->isFunctionType());
1814 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001815 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001816
1817 // Check for ObjC interfaces
1818 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1819 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1820 if (LHSIface && RHSIface &&
1821 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1822 return ConvTy;
1823
1824 // ID acts sort of like void* for ObjC interfaces
1825 if (LHSIface && Context.isObjCIdType(rhptee))
1826 return ConvTy;
1827 if (RHSIface && Context.isObjCIdType(lhptee))
1828 return ConvTy;
1829
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1831 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001832 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1833 rhptee.getUnqualifiedType()))
1834 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001835 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001836}
1837
Steve Naroff1c7d0672008-09-04 15:10:53 +00001838/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1839/// block pointer types are compatible or whether a block and normal pointer
1840/// are compatible. It is more restrict than comparing two function pointer
1841// types.
1842Sema::AssignConvertType
1843Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1844 QualType rhsType) {
1845 QualType lhptee, rhptee;
1846
1847 // get the "pointed to" type (ignoring qualifiers at the top level)
1848 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1849 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1850
1851 // make sure we operate on the canonical type
1852 lhptee = Context.getCanonicalType(lhptee);
1853 rhptee = Context.getCanonicalType(rhptee);
1854
1855 AssignConvertType ConvTy = Compatible;
1856
1857 // For blocks we enforce that qualifiers are identical.
1858 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1859 ConvTy = CompatiblePointerDiscardsQualifiers;
1860
1861 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1862 return IncompatibleBlockPointer;
1863 return ConvTy;
1864}
1865
Reid Spencer5f016e22007-07-11 17:01:13 +00001866/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1867/// has code to accommodate several GCC extensions when type checking
1868/// pointers. Here are some objectionable examples that GCC considers warnings:
1869///
1870/// int a, *pint;
1871/// short *pshort;
1872/// struct foo *pfoo;
1873///
1874/// pint = pshort; // warning: assignment from incompatible pointer type
1875/// a = pint; // warning: assignment makes integer from pointer without a cast
1876/// pint = a; // warning: assignment makes pointer from integer without a cast
1877/// pint = pfoo; // warning: assignment from incompatible pointer type
1878///
1879/// As a result, the code for dealing with pointers is more complex than the
1880/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001881///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001882Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001883Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001884 // Get canonical types. We're not formatting these types, just comparing
1885 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001886 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1887 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001888
1889 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001890 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001891
Douglas Gregor9d293df2008-10-28 00:22:11 +00001892 // If the left-hand side is a reference type, then we are in a
1893 // (rare!) case where we've allowed the use of references in C,
1894 // e.g., as a parameter type in a built-in function. In this case,
1895 // just make sure that the type referenced is compatible with the
1896 // right-hand side type. The caller is responsible for adjusting
1897 // lhsType so that the resulting expression does not have reference
1898 // type.
1899 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1900 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001901 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001902 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001903 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001904
Chris Lattnereca7be62008-04-07 05:30:13 +00001905 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1906 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001907 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001908 // Relax integer conversions like we do for pointers below.
1909 if (rhsType->isIntegerType())
1910 return IntToPointer;
1911 if (lhsType->isIntegerType())
1912 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00001913 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001914 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001915
Nate Begemanbe2341d2008-07-14 18:02:46 +00001916 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001917 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001918 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1919 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001920 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001921
Nate Begemanbe2341d2008-07-14 18:02:46 +00001922 // If we are allowing lax vector conversions, and LHS and RHS are both
1923 // vectors, the total size only needs to be the same. This is a bitcast;
1924 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001925 if (getLangOptions().LaxVectorConversions &&
1926 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001927 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1928 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001929 }
1930 return Incompatible;
1931 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001932
Chris Lattnere8b3e962008-01-04 23:32:24 +00001933 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001934 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001935
Chris Lattner78eca282008-04-07 06:49:41 +00001936 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001937 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001938 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001939
Chris Lattner78eca282008-04-07 06:49:41 +00001940 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001942
Steve Naroffb4406862008-09-29 18:10:17 +00001943 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00001944 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff1c7d0672008-09-04 15:10:53 +00001945 return BlockVoidPointer;
Steve Naroffb4406862008-09-29 18:10:17 +00001946
1947 // Treat block pointers as objects.
1948 if (getLangOptions().ObjC1 &&
1949 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1950 return Compatible;
1951 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001952 return Incompatible;
1953 }
1954
1955 if (isa<BlockPointerType>(lhsType)) {
1956 if (rhsType->isIntegerType())
1957 return IntToPointer;
1958
Steve Naroffb4406862008-09-29 18:10:17 +00001959 // Treat block pointers as objects.
1960 if (getLangOptions().ObjC1 &&
1961 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1962 return Compatible;
1963
Steve Naroff1c7d0672008-09-04 15:10:53 +00001964 if (rhsType->isBlockPointerType())
1965 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1966
1967 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1968 if (RHSPT->getPointeeType()->isVoidType())
1969 return BlockVoidPointer;
1970 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001971 return Incompatible;
1972 }
1973
Chris Lattner78eca282008-04-07 06:49:41 +00001974 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001976 if (lhsType == Context.BoolTy)
1977 return Compatible;
1978
1979 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001980 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001981
Chris Lattner78eca282008-04-07 06:49:41 +00001982 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001984
1985 if (isa<BlockPointerType>(lhsType) &&
1986 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1987 return BlockVoidPointer;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001988 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001989 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001990
Chris Lattnerfc144e22008-01-04 23:18:45 +00001991 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001992 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 }
1995 return Incompatible;
1996}
1997
Chris Lattner5cf216b2008-01-04 18:04:52 +00001998Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001999Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002000 if (getLangOptions().CPlusPlus) {
2001 if (!lhsType->isRecordType()) {
2002 // C++ 5.17p3: If the left operand is not of class type, the
2003 // expression is implicitly converted (C++ 4) to the
2004 // cv-unqualified type of the left operand.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002005 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002006 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002007 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002008 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002009 }
2010
2011 // FIXME: Currently, we fall through and treat C++ classes like C
2012 // structures.
2013 }
2014
Steve Naroff529a4ad2007-11-27 17:58:44 +00002015 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2016 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00002017 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2018 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002019 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002020 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002021 return Compatible;
2022 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002023
2024 // We don't allow conversion of non-null-pointer constants to integers.
2025 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2026 return IntToBlockPointer;
2027
Chris Lattner943140e2007-10-16 02:55:40 +00002028 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002029 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002030 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002031 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002032 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002033 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002034 if (!lhsType->isReferenceType())
2035 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002036
Chris Lattner5cf216b2008-01-04 18:04:52 +00002037 Sema::AssignConvertType result =
2038 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002039
2040 // C99 6.5.16.1p2: The value of the right operand is converted to the
2041 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002042 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2043 // so that we can use references in built-in functions even in C.
2044 // The getNonReferenceType() call makes sure that the resulting expression
2045 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002046 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002047 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002048 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002049}
2050
Chris Lattner5cf216b2008-01-04 18:04:52 +00002051Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002052Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2053 return CheckAssignmentConstraints(lhsType, rhsType);
2054}
2055
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002056QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002057 Diag(Loc, diag::err_typecheck_invalid_operands)
2058 << lex->getType().getAsString() << rex->getType().getAsString()
2059 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002060 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002061}
2062
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002063inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002064 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002065 // For conversion purposes, we ignore any qualifiers.
2066 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002067 QualType lhsType =
2068 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2069 QualType rhsType =
2070 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002071
Nate Begemanbe2341d2008-07-14 18:02:46 +00002072 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002073 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002075
Nate Begemanbe2341d2008-07-14 18:02:46 +00002076 // Handle the case of a vector & extvector type of the same size and element
2077 // type. It would be nice if we only had one vector type someday.
2078 if (getLangOptions().LaxVectorConversions)
2079 if (const VectorType *LV = lhsType->getAsVectorType())
2080 if (const VectorType *RV = rhsType->getAsVectorType())
2081 if (LV->getElementType() == RV->getElementType() &&
2082 LV->getNumElements() == RV->getNumElements())
2083 return lhsType->isExtVectorType() ? lhsType : rhsType;
2084
2085 // If the lhs is an extended vector and the rhs is a scalar of the same type
2086 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002087 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002088 QualType eltType = V->getElementType();
2089
2090 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2091 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2092 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002093 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002094 return lhsType;
2095 }
2096 }
2097
Nate Begemanbe2341d2008-07-14 18:02:46 +00002098 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002099 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002100 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002101 QualType eltType = V->getElementType();
2102
2103 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2104 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2105 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002106 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002107 return rhsType;
2108 }
2109 }
2110
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002112 Diag(Loc, diag::err_typecheck_vector_not_convertable)
2113 << lex->getType().getAsString() << rex->getType().getAsString()
2114 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 return QualType();
2116}
2117
2118inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002119 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002120{
Steve Naroff90045e82007-07-13 23:32:42 +00002121 QualType lhsType = lex->getType(), rhsType = rex->getType();
2122
2123 if (lhsType->isVectorType() || rhsType->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);
Reid Spencer5f016e22007-07-11 17:01:13 +00002127
Steve Naroffa4332e22007-07-17 00:58:39 +00002128 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002129 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002130 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002131}
2132
2133inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002134 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002135{
Steve Naroff90045e82007-07-13 23:32:42 +00002136 QualType lhsType = lex->getType(), rhsType = rex->getType();
2137
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002138 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002139
Steve Naroffa4332e22007-07-17 00:58:39 +00002140 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002141 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002142 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002143}
2144
2145inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002146 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002147{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002148 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002149 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002150
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002151 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002152
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002154 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002155 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002156
Eli Friedmand72d16e2008-05-18 18:08:51 +00002157 // Put any potential pointer into PExp
2158 Expr* PExp = lex, *IExp = rex;
2159 if (IExp->getType()->isPointerType())
2160 std::swap(PExp, IExp);
2161
2162 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2163 if (IExp->getType()->isIntegerType()) {
2164 // Check for arithmetic on pointers to incomplete types
2165 if (!PTy->getPointeeType()->isObjectType()) {
2166 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002167 Diag(Loc, diag::ext_gnu_void_ptr)
2168 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002169 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002170 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
2171 << lex->getType().getAsString() << lex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002172 return QualType();
2173 }
2174 }
2175 return PExp->getType();
2176 }
2177 }
2178
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002179 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002180}
2181
Chris Lattnereca7be62008-04-07 05:30:13 +00002182// C99 6.5.6
2183QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002184 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002185 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002186 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002187
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002188 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002189
Chris Lattner6e4ab612007-12-09 21:53:25 +00002190 // Enforce type constraints: C99 6.5.6p3.
2191
2192 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002193 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002194 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002195
2196 // Either ptr - int or ptr - ptr.
2197 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002198 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002199
Chris Lattner6e4ab612007-12-09 21:53:25 +00002200 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002201 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002202 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002203 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002204 Diag(Loc, diag::ext_gnu_void_ptr)
2205 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002206 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002207 Diag(Loc, diag::err_typecheck_sub_ptr_object)
2208 << lex->getType().getAsString() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002209 return QualType();
2210 }
2211 }
2212
2213 // The result type of a pointer-int computation is the pointer type.
2214 if (rex->getType()->isIntegerType())
2215 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002216
Chris Lattner6e4ab612007-12-09 21:53:25 +00002217 // Handle pointer-pointer subtractions.
2218 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002219 QualType rpointee = RHSPTy->getPointeeType();
2220
Chris Lattner6e4ab612007-12-09 21:53:25 +00002221 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002222 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002223 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002224 if (rpointee->isVoidType()) {
2225 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002226 Diag(Loc, diag::ext_gnu_void_ptr)
2227 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002228 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002229 Diag(Loc, diag::err_typecheck_sub_ptr_object)
2230 << rex->getType().getAsString() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002231 return QualType();
2232 }
2233 }
2234
2235 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002236 if (!Context.typesAreCompatible(
2237 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2238 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002239 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
2240 << lex->getType().getAsString() << rex->getType().getAsString()
2241 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002242 return QualType();
2243 }
2244
2245 return Context.getPointerDiffType();
2246 }
2247 }
2248
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002249 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002250}
2251
Chris Lattnereca7be62008-04-07 05:30:13 +00002252// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002253QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002254 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002255 // C99 6.5.7p2: Each of the operands shall have integer type.
2256 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002257 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002258
Chris Lattnerca5eede2007-12-12 05:47:28 +00002259 // Shifts don't perform usual arithmetic conversions, they just do integer
2260 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002261 if (!isCompAssign)
2262 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002263 UsualUnaryConversions(rex);
2264
2265 // "The type of the result is that of the promoted left operand."
2266 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002267}
2268
Eli Friedman3d815e72008-08-22 00:56:42 +00002269static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2270 ASTContext& Context) {
2271 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2272 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2273 // ID acts sort of like void* for ObjC interfaces
2274 if (LHSIface && Context.isObjCIdType(RHS))
2275 return true;
2276 if (RHSIface && Context.isObjCIdType(LHS))
2277 return true;
2278 if (!LHSIface || !RHSIface)
2279 return false;
2280 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2281 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2282}
2283
Chris Lattnereca7be62008-04-07 05:30:13 +00002284// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002285QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002286 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002287 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002288 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002289
Chris Lattnera5937dd2007-08-26 01:18:55 +00002290 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002291 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2292 UsualArithmeticConversions(lex, rex);
2293 else {
2294 UsualUnaryConversions(lex);
2295 UsualUnaryConversions(rex);
2296 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002297 QualType lType = lex->getType();
2298 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002299
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002300 // For non-floating point types, check for self-comparisons of the form
2301 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2302 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002303 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002304 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2305 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002306 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002307 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002308 }
2309
Douglas Gregor447b69e2008-11-19 03:25:36 +00002310 // The result of comparisons is 'bool' in C++, 'int' in C.
2311 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2312
Chris Lattnera5937dd2007-08-26 01:18:55 +00002313 if (isRelational) {
2314 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002315 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002316 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002317 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002318 if (lType->isFloatingType()) {
2319 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002320 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002321 }
2322
Chris Lattnera5937dd2007-08-26 01:18:55 +00002323 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002324 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002325 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002326
Chris Lattnerd28f8152007-08-26 01:10:14 +00002327 bool LHSIsNull = lex->isNullPointerConstant(Context);
2328 bool RHSIsNull = rex->isNullPointerConstant(Context);
2329
Chris Lattnera5937dd2007-08-26 01:18:55 +00002330 // All of the following pointer related warnings are GCC extensions, except
2331 // when handling null pointer constants. One day, we can consider making them
2332 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002333 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002334 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002335 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002336 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002337 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002338
Steve Naroff66296cb2007-11-13 14:57:38 +00002339 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002340 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2341 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002342 RCanPointeeTy.getUnqualifiedType()) &&
2343 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002344 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
2345 << lType.getAsString() << rType.getAsString()
2346 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002347 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002348 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002349 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002350 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002351 // Handle block pointer types.
2352 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2353 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2354 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2355
2356 if (!LHSIsNull && !RHSIsNull &&
2357 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002358 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
2359 << lType.getAsString() << rType.getAsString()
2360 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002361 }
2362 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002363 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002364 }
Steve Naroff59f53942008-09-28 01:11:11 +00002365 // Allow block pointers to be compared with null pointer constants.
2366 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2367 (lType->isPointerType() && rType->isBlockPointerType())) {
2368 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002369 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
2370 << lType.getAsString() << rType.getAsString()
2371 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002372 }
2373 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002374 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00002375 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002376
Steve Naroff20373222008-06-03 14:04:54 +00002377 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002378 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00002379 const PointerType *LPT = lType->getAsPointerType();
2380 const PointerType *RPT = rType->getAsPointerType();
2381 bool LPtrToVoid = LPT ?
2382 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2383 bool RPtrToVoid = RPT ?
2384 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2385
2386 if (!LPtrToVoid && !RPtrToVoid &&
2387 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002388 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
2389 << lType.getAsString() << rType.getAsString()
2390 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00002391 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002392 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00002393 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002394 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002395 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002396 }
Steve Naroff20373222008-06-03 14:04:54 +00002397 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2398 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002399 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002400 } else {
2401 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002402 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
2403 << lType.getAsString() << rType.getAsString()
2404 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002405 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002406 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002407 }
Steve Naroff20373222008-06-03 14:04:54 +00002408 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002409 }
Steve Naroff20373222008-06-03 14:04:54 +00002410 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2411 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002412 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002413 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2414 << lType.getAsString() << rType.getAsString()
2415 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002416 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002417 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002418 }
Steve Naroff20373222008-06-03 14:04:54 +00002419 if (lType->isIntegerType() &&
2420 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002421 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002422 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2423 << lType.getAsString() << rType.getAsString()
2424 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002425 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002426 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002427 }
Steve Naroff39218df2008-09-04 16:56:14 +00002428 // Handle block pointers.
2429 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2430 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002431 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2432 << lType.getAsString() << rType.getAsString()
2433 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002434 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002435 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002436 }
2437 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2438 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002439 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2440 << lType.getAsString() << rType.getAsString()
2441 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002442 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002443 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002444 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002445 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002446}
2447
Nate Begemanbe2341d2008-07-14 18:02:46 +00002448/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2449/// operates on extended vector types. Instead of producing an IntTy result,
2450/// like a scalar comparison, a vector comparison produces a vector of integer
2451/// types.
2452QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002453 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00002454 bool isRelational) {
2455 // Check to make sure we're operating on vectors of the same type and width,
2456 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002457 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002458 if (vType.isNull())
2459 return vType;
2460
2461 QualType lType = lex->getType();
2462 QualType rType = rex->getType();
2463
2464 // For non-floating point types, check for self-comparisons of the form
2465 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2466 // often indicate logic errors in the program.
2467 if (!lType->isFloatingType()) {
2468 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2469 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2470 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002471 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002472 }
2473
2474 // Check for comparisons of floating point operands using != and ==.
2475 if (!isRelational && lType->isFloatingType()) {
2476 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002477 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002478 }
2479
2480 // Return the type for the comparison, which is the same as vector type for
2481 // integer vectors, or an integer type of identical size and number of
2482 // elements for floating point vectors.
2483 if (lType->isIntegerType())
2484 return lType;
2485
2486 const VectorType *VTy = lType->getAsVectorType();
2487
2488 // FIXME: need to deal with non-32b int / non-64b long long
2489 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2490 if (TypeSize == 32) {
2491 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2492 }
2493 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2494 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2495}
2496
Reid Spencer5f016e22007-07-11 17:01:13 +00002497inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002498 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002499{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002500 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002501 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002502
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002503 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002504
Steve Naroffa4332e22007-07-17 00:58:39 +00002505 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002506 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002507 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002508}
2509
2510inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002511 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002512{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002513 UsualUnaryConversions(lex);
2514 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002515
Eli Friedman5773a6c2008-05-13 20:16:47 +00002516 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002518 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002519}
2520
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002521/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2522/// emit an error and return true. If so, return false.
2523static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2524 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2525 if (IsLV == Expr::MLV_Valid)
2526 return false;
2527
2528 unsigned Diag = 0;
2529 bool NeedType = false;
2530 switch (IsLV) { // C99 6.5.16p2
2531 default: assert(0 && "Unknown result from isModifiableLvalue!");
2532 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002533 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002534 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2535 NeedType = true;
2536 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002537 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002538 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2539 NeedType = true;
2540 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00002541 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002542 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2543 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002544 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002545 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2546 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002547 case Expr::MLV_IncompleteType:
2548 case Expr::MLV_IncompleteVoidType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002549 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2550 NeedType = true;
2551 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002552 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002553 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2554 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002555 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002556 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2557 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002558 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002559
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002560 if (NeedType)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002561 S.Diag(Loc, Diag) << E->getType().getAsString() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002562 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002563 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002564 return true;
2565}
2566
2567
2568
2569// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002570QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2571 SourceLocation Loc,
2572 QualType CompoundType) {
2573 // Verify that LHS is a modifiable lvalue, and emit error if not.
2574 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002575 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002576
2577 QualType LHSType = LHS->getType();
2578 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002579
Chris Lattner5cf216b2008-01-04 18:04:52 +00002580 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002581 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00002582 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002583 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner2c156472008-08-21 18:04:13 +00002584
2585 // If the RHS is a unary plus or minus, check to see if they = and + are
2586 // right next to each other. If so, the user may have typo'd "x =+ 4"
2587 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002588 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00002589 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2590 RHSCheck = ICE->getSubExpr();
2591 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2592 if ((UO->getOpcode() == UnaryOperator::Plus ||
2593 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002594 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00002595 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002596 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002597 Diag(Loc, diag::warn_not_compound_assign)
2598 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2599 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00002600 }
2601 } else {
2602 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002603 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00002604 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002605
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002606 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2607 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002608 return QualType();
2609
Reid Spencer5f016e22007-07-11 17:01:13 +00002610 // C99 6.5.16p3: The type of an assignment expression is the type of the
2611 // left operand unless the left operand has qualified type, in which case
2612 // it is the unqualified version of the type of the left operand.
2613 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2614 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002615 // C++ 5.17p1: the type of the assignment expression is that of its left
2616 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002617 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002618}
2619
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002620// C99 6.5.17
2621QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2622 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00002623
2624 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002625 DefaultFunctionArrayConversion(RHS);
2626 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002627}
2628
Steve Naroff49b45262007-07-13 16:58:59 +00002629/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2630/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Chris Lattner3528d352008-11-21 07:05:48 +00002631QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc) {
2632 QualType ResType = Op->getType();
2633 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002634
Steve Naroff084f9ed2007-08-24 17:20:07 +00002635 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner3528d352008-11-21 07:05:48 +00002636 if (ResType->isRealType()) {
2637 // OK!
2638 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2639 // C99 6.5.2.4p2, 6.5.6p2
2640 if (PT->getPointeeType()->isObjectType()) {
2641 // Pointer to object is ok!
2642 } else if (PT->getPointeeType()->isVoidType()) {
2643 // Pointer to void is extension.
2644 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2645 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002646 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner3528d352008-11-21 07:05:48 +00002647 << ResType.getAsString() << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 return QualType();
2649 }
Chris Lattner3528d352008-11-21 07:05:48 +00002650 } else if (ResType->isComplexType()) {
2651 // C99 does not support ++/-- on complex types, we allow as an extension.
2652 Diag(OpLoc, diag::ext_integer_increment_complex)
2653 << ResType.getAsString() << Op->getSourceRange();
2654 } else {
2655 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
2656 << ResType.getAsString() << Op->getSourceRange();
2657 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002658 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002659 // At this point, we know we have a real, complex or pointer type.
2660 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00002661 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00002663 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002664}
2665
Anders Carlsson369dee42008-02-01 07:15:58 +00002666/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002667/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002668/// where the declaration is needed for type checking. We only need to
2669/// handle cases when the expression references a function designator
2670/// or is an lvalue. Here are some examples:
2671/// - &(x) => x
2672/// - &*****f => f for f a function designator.
2673/// - &s.xx => s
2674/// - &s.zz[1].yy -> s, if zz is an array
2675/// - *(x + 1) -> x, if x is an array
2676/// - &"123"[2] -> 0
2677/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002678static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002679 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002681 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002682 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002683 // Fields cannot be declared with a 'register' storage class.
2684 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002685 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002686 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002687 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002688 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002689 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002690
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002691 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00002692 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002693 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002694 return 0;
2695 else
2696 return VD;
2697 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002698 case Stmt::UnaryOperatorClass: {
2699 UnaryOperator *UO = cast<UnaryOperator>(E);
2700
2701 switch(UO->getOpcode()) {
2702 case UnaryOperator::Deref: {
2703 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002704 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2705 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2706 if (!VD || VD->getType()->isPointerType())
2707 return 0;
2708 return VD;
2709 }
2710 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002711 }
2712 case UnaryOperator::Real:
2713 case UnaryOperator::Imag:
2714 case UnaryOperator::Extension:
2715 return getPrimaryDecl(UO->getSubExpr());
2716 default:
2717 return 0;
2718 }
2719 }
2720 case Stmt::BinaryOperatorClass: {
2721 BinaryOperator *BO = cast<BinaryOperator>(E);
2722
2723 // Handle cases involving pointer arithmetic. The result of an
2724 // Assign or AddAssign is not an lvalue so they can be ignored.
2725
2726 // (x + n) or (n + x) => x
2727 if (BO->getOpcode() == BinaryOperator::Add) {
2728 if (BO->getLHS()->getType()->isPointerType()) {
2729 return getPrimaryDecl(BO->getLHS());
2730 } else if (BO->getRHS()->getType()->isPointerType()) {
2731 return getPrimaryDecl(BO->getRHS());
2732 }
2733 }
2734
2735 return 0;
2736 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002738 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002739 case Stmt::ImplicitCastExprClass:
2740 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002741 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002742 default:
2743 return 0;
2744 }
2745}
2746
2747/// CheckAddressOfOperand - The operand of & must be either a function
2748/// designator or an lvalue designating an object. If it is an lvalue, the
2749/// object cannot be declared with storage class register or be a bit field.
2750/// Note: The usual conversions are *not* applied to the operand of the &
2751/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00002752/// In C++, the operand might be an overloaded function name, in which case
2753/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002754QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002755 if (getLangOptions().C99) {
2756 // Implement C99-only parts of addressof rules.
2757 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2758 if (uOp->getOpcode() == UnaryOperator::Deref)
2759 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2760 // (assuming the deref expression is valid).
2761 return uOp->getSubExpr()->getType();
2762 }
2763 // Technically, there should be a check for array subscript
2764 // expressions here, but the result of one is always an lvalue anyway.
2765 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002766 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002767 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002768
2769 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002770 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2771 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002772 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2773 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002774 return QualType();
2775 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002776 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2777 if (MemExpr->getMemberDecl()->isBitField()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002778 Diag(OpLoc, diag::err_typecheck_address_of)
2779 << "bit-field" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00002780 return QualType();
2781 }
2782 // Check for Apple extension for accessing vector components.
2783 } else if (isa<ArraySubscriptExpr>(op) &&
2784 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002785 Diag(OpLoc, diag::err_typecheck_address_of)
2786 << "vector" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00002787 return QualType();
2788 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002789 // We have an lvalue with a decl. Make sure the decl is not declared
2790 // with the register storage-class specifier.
2791 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2792 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002793 Diag(OpLoc, diag::err_typecheck_address_of)
2794 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002795 return QualType();
2796 }
Douglas Gregor904eed32008-11-10 20:40:00 +00002797 } else if (isa<OverloadedFunctionDecl>(dcl))
2798 return Context.OverloadTy;
2799 else
Reid Spencer5f016e22007-07-11 17:01:13 +00002800 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002802
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 // If the operand has type "type", the result has type "pointer to type".
2804 return Context.getPointerType(op->getType());
2805}
2806
2807QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002808 UsualUnaryConversions(op);
2809 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002810
Chris Lattnerbefee482007-07-31 16:53:04 +00002811 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002812 // Note that per both C89 and C99, this is always legal, even
2813 // if ptype is an incomplete type or void.
2814 // It would be possible to warn about dereferencing a
2815 // void pointer, but it's completely well-defined,
2816 // and such a warning is unlikely to catch any mistakes.
2817 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002818 }
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002819 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
2820 << qType.getAsString() << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 return QualType();
2822}
2823
2824static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2825 tok::TokenKind Kind) {
2826 BinaryOperator::Opcode Opc;
2827 switch (Kind) {
2828 default: assert(0 && "Unknown binop!");
2829 case tok::star: Opc = BinaryOperator::Mul; break;
2830 case tok::slash: Opc = BinaryOperator::Div; break;
2831 case tok::percent: Opc = BinaryOperator::Rem; break;
2832 case tok::plus: Opc = BinaryOperator::Add; break;
2833 case tok::minus: Opc = BinaryOperator::Sub; break;
2834 case tok::lessless: Opc = BinaryOperator::Shl; break;
2835 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2836 case tok::lessequal: Opc = BinaryOperator::LE; break;
2837 case tok::less: Opc = BinaryOperator::LT; break;
2838 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2839 case tok::greater: Opc = BinaryOperator::GT; break;
2840 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2841 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2842 case tok::amp: Opc = BinaryOperator::And; break;
2843 case tok::caret: Opc = BinaryOperator::Xor; break;
2844 case tok::pipe: Opc = BinaryOperator::Or; break;
2845 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2846 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2847 case tok::equal: Opc = BinaryOperator::Assign; break;
2848 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2849 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2850 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2851 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2852 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2853 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2854 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2855 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2856 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2857 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2858 case tok::comma: Opc = BinaryOperator::Comma; break;
2859 }
2860 return Opc;
2861}
2862
2863static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2864 tok::TokenKind Kind) {
2865 UnaryOperator::Opcode Opc;
2866 switch (Kind) {
2867 default: assert(0 && "Unknown unary op!");
2868 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2869 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2870 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2871 case tok::star: Opc = UnaryOperator::Deref; break;
2872 case tok::plus: Opc = UnaryOperator::Plus; break;
2873 case tok::minus: Opc = UnaryOperator::Minus; break;
2874 case tok::tilde: Opc = UnaryOperator::Not; break;
2875 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002876 case tok::kw___real: Opc = UnaryOperator::Real; break;
2877 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2878 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2879 }
2880 return Opc;
2881}
2882
Douglas Gregoreaebc752008-11-06 23:29:22 +00002883/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2884/// operator @p Opc at location @c TokLoc. This routine only supports
2885/// built-in operations; ActOnBinOp handles overloaded operators.
2886Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2887 unsigned Op,
2888 Expr *lhs, Expr *rhs) {
2889 QualType ResultTy; // Result type of the binary operator.
2890 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2891 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2892
2893 switch (Opc) {
2894 default:
2895 assert(0 && "Unknown binary expr!");
2896 case BinaryOperator::Assign:
2897 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2898 break;
2899 case BinaryOperator::Mul:
2900 case BinaryOperator::Div:
2901 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2902 break;
2903 case BinaryOperator::Rem:
2904 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2905 break;
2906 case BinaryOperator::Add:
2907 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2908 break;
2909 case BinaryOperator::Sub:
2910 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2911 break;
2912 case BinaryOperator::Shl:
2913 case BinaryOperator::Shr:
2914 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2915 break;
2916 case BinaryOperator::LE:
2917 case BinaryOperator::LT:
2918 case BinaryOperator::GE:
2919 case BinaryOperator::GT:
2920 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2921 break;
2922 case BinaryOperator::EQ:
2923 case BinaryOperator::NE:
2924 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2925 break;
2926 case BinaryOperator::And:
2927 case BinaryOperator::Xor:
2928 case BinaryOperator::Or:
2929 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2930 break;
2931 case BinaryOperator::LAnd:
2932 case BinaryOperator::LOr:
2933 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2934 break;
2935 case BinaryOperator::MulAssign:
2936 case BinaryOperator::DivAssign:
2937 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2938 if (!CompTy.isNull())
2939 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2940 break;
2941 case BinaryOperator::RemAssign:
2942 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2943 if (!CompTy.isNull())
2944 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2945 break;
2946 case BinaryOperator::AddAssign:
2947 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2948 if (!CompTy.isNull())
2949 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2950 break;
2951 case BinaryOperator::SubAssign:
2952 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2953 if (!CompTy.isNull())
2954 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2955 break;
2956 case BinaryOperator::ShlAssign:
2957 case BinaryOperator::ShrAssign:
2958 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2959 if (!CompTy.isNull())
2960 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2961 break;
2962 case BinaryOperator::AndAssign:
2963 case BinaryOperator::XorAssign:
2964 case BinaryOperator::OrAssign:
2965 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2966 if (!CompTy.isNull())
2967 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2968 break;
2969 case BinaryOperator::Comma:
2970 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2971 break;
2972 }
2973 if (ResultTy.isNull())
2974 return true;
2975 if (CompTy.isNull())
2976 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2977 else
2978 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2979}
2980
Reid Spencer5f016e22007-07-11 17:01:13 +00002981// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00002982Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2983 tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002984 ExprTy *LHS, ExprTy *RHS) {
2985 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2986 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2987
Steve Narofff69936d2007-09-16 03:34:24 +00002988 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2989 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002990
Douglas Gregoreaebc752008-11-06 23:29:22 +00002991 if (getLangOptions().CPlusPlus &&
2992 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2993 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002994 // If this is one of the assignment operators, we only perform
2995 // overload resolution if the left-hand side is a class or
2996 // enumeration type (C++ [expr.ass]p3).
2997 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
2998 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
2999 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3000 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003001
3002 // Determine which overloaded operator we're dealing with.
3003 static const OverloadedOperatorKind OverOps[] = {
3004 OO_Star, OO_Slash, OO_Percent,
3005 OO_Plus, OO_Minus,
3006 OO_LessLess, OO_GreaterGreater,
3007 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3008 OO_EqualEqual, OO_ExclaimEqual,
3009 OO_Amp,
3010 OO_Caret,
3011 OO_Pipe,
3012 OO_AmpAmp,
3013 OO_PipePipe,
3014 OO_Equal, OO_StarEqual,
3015 OO_SlashEqual, OO_PercentEqual,
3016 OO_PlusEqual, OO_MinusEqual,
3017 OO_LessLessEqual, OO_GreaterGreaterEqual,
3018 OO_AmpEqual, OO_CaretEqual,
3019 OO_PipeEqual,
3020 OO_Comma
3021 };
3022 OverloadedOperatorKind OverOp = OverOps[Opc];
3023
Douglas Gregor96176b32008-11-18 23:14:02 +00003024 // Add the appropriate overloaded operators (C++ [over.match.oper])
3025 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003026 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003027 Expr *Args[2] = { lhs, rhs };
Douglas Gregor96176b32008-11-18 23:14:02 +00003028 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregoreaebc752008-11-06 23:29:22 +00003029
3030 // Perform overload resolution.
3031 OverloadCandidateSet::iterator Best;
3032 switch (BestViableFunction(CandidateSet, Best)) {
3033 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003034 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003035 FunctionDecl *FnDecl = Best->Function;
3036
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003037 if (FnDecl) {
3038 // We matched an overloaded operator. Build a call to that
3039 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003040
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003041 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3043 if (PerformObjectArgumentInitialization(lhs, Method) ||
3044 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3045 "passing"))
3046 return true;
3047 } else {
3048 // Convert the arguments.
3049 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3050 "passing") ||
3051 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3052 "passing"))
3053 return true;
3054 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003055
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003056 // Determine the result type
3057 QualType ResultTy
3058 = FnDecl->getType()->getAsFunctionType()->getResultType();
3059 ResultTy = ResultTy.getNonReferenceType();
3060
3061 // Build the actual expression node.
Douglas Gregorb4609802008-11-14 16:09:21 +00003062 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3063 SourceLocation());
3064 UsualUnaryConversions(FnExpr);
3065
Douglas Gregorb4609802008-11-14 16:09:21 +00003066 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003067 } else {
3068 // We matched a built-in operator. Convert the arguments, then
3069 // break out so that we will build the appropriate built-in
3070 // operator node.
3071 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3072 "passing") ||
3073 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3074 "passing"))
3075 return true;
3076
3077 break;
3078 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003079 }
3080
3081 case OR_No_Viable_Function:
3082 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003083 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003084 break;
3085
3086 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003087 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3088 << BinaryOperator::getOpcodeStr(Opc)
3089 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003090 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3091 return true;
3092 }
3093
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003094 // Either we found no viable overloaded operator or we matched a
3095 // built-in operator. In either case, fall through to trying to
3096 // build a built-in operation.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003097 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003098
Douglas Gregoreaebc752008-11-06 23:29:22 +00003099 // Build a built-in binary operation.
3100 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003101}
3102
3103// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor74253732008-11-19 15:42:04 +00003104Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3105 tok::TokenKind Op, ExprTy *input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003106 Expr *Input = (Expr*)input;
3107 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003108
3109 if (getLangOptions().CPlusPlus &&
3110 (Input->getType()->isRecordType()
3111 || Input->getType()->isEnumeralType())) {
3112 // Determine which overloaded operator we're dealing with.
3113 static const OverloadedOperatorKind OverOps[] = {
3114 OO_None, OO_None,
3115 OO_PlusPlus, OO_MinusMinus,
3116 OO_Amp, OO_Star,
3117 OO_Plus, OO_Minus,
3118 OO_Tilde, OO_Exclaim,
3119 OO_None, OO_None,
3120 OO_None,
3121 OO_None
3122 };
3123 OverloadedOperatorKind OverOp = OverOps[Opc];
3124
3125 // Add the appropriate overloaded operators (C++ [over.match.oper])
3126 // to the candidate set.
3127 OverloadCandidateSet CandidateSet;
3128 if (OverOp != OO_None)
3129 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3130
3131 // Perform overload resolution.
3132 OverloadCandidateSet::iterator Best;
3133 switch (BestViableFunction(CandidateSet, Best)) {
3134 case OR_Success: {
3135 // We found a built-in operator or an overloaded operator.
3136 FunctionDecl *FnDecl = Best->Function;
3137
3138 if (FnDecl) {
3139 // We matched an overloaded operator. Build a call to that
3140 // operator.
3141
3142 // Convert the arguments.
3143 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3144 if (PerformObjectArgumentInitialization(Input, Method))
3145 return true;
3146 } else {
3147 // Convert the arguments.
3148 if (PerformCopyInitialization(Input,
3149 FnDecl->getParamDecl(0)->getType(),
3150 "passing"))
3151 return true;
3152 }
3153
3154 // Determine the result type
3155 QualType ResultTy
3156 = FnDecl->getType()->getAsFunctionType()->getResultType();
3157 ResultTy = ResultTy.getNonReferenceType();
3158
3159 // Build the actual expression node.
3160 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3161 SourceLocation());
3162 UsualUnaryConversions(FnExpr);
3163
3164 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3165 } else {
3166 // We matched a built-in operator. Convert the arguments, then
3167 // break out so that we will build the appropriate built-in
3168 // operator node.
3169 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3170 "passing"))
3171 return true;
3172
3173 break;
3174 }
3175 }
3176
3177 case OR_No_Viable_Function:
3178 // No viable function; fall through to handling this as a
3179 // built-in operator, which will produce an error message for us.
3180 break;
3181
3182 case OR_Ambiguous:
3183 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3184 << UnaryOperator::getOpcodeStr(Opc)
3185 << Input->getSourceRange();
3186 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3187 return true;
3188 }
3189
3190 // Either we found no viable overloaded operator or we matched a
3191 // built-in operator. In either case, fall through to trying to
3192 // build a built-in operation.
3193 }
3194
3195
Reid Spencer5f016e22007-07-11 17:01:13 +00003196 QualType resultType;
3197 switch (Opc) {
3198 default:
3199 assert(0 && "Unimplemented unary expr!");
3200 case UnaryOperator::PreInc:
3201 case UnaryOperator::PreDec:
3202 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
3203 break;
3204 case UnaryOperator::AddrOf:
3205 resultType = CheckAddressOfOperand(Input, OpLoc);
3206 break;
3207 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003208 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003209 resultType = CheckIndirectionOperand(Input, OpLoc);
3210 break;
3211 case UnaryOperator::Plus:
3212 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003213 UsualUnaryConversions(Input);
3214 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00003215 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3216 break;
3217 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3218 resultType->isEnumeralType())
3219 break;
3220 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3221 Opc == UnaryOperator::Plus &&
3222 resultType->isPointerType())
3223 break;
3224
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003225 return Diag(OpLoc, diag::err_typecheck_unary_expr)
3226 << resultType.getAsString();
Reid Spencer5f016e22007-07-11 17:01:13 +00003227 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003228 UsualUnaryConversions(Input);
3229 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00003230 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3231 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3232 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003233 Diag(OpLoc, diag::ext_integer_complement_complex)
3234 << resultType.getAsString() << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00003235 else if (!resultType->isIntegerType())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003236 return Diag(OpLoc, diag::err_typecheck_unary_expr)
3237 << resultType.getAsString() << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003238 break;
3239 case UnaryOperator::LNot: // logical negation
3240 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003241 DefaultFunctionArrayConversion(Input);
3242 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003243 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003244 return Diag(OpLoc, diag::err_typecheck_unary_expr)
3245 << resultType.getAsString();
Reid Spencer5f016e22007-07-11 17:01:13 +00003246 // LNot always has type int. C99 6.5.3.3p5.
3247 resultType = Context.IntTy;
3248 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00003249 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00003250 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00003251 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00003252 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003253 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00003254 resultType = Input->getType();
3255 break;
3256 }
3257 if (resultType.isNull())
3258 return true;
3259 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3260}
3261
Steve Naroff1b273c42007-09-16 14:56:35 +00003262/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3263Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003264 SourceLocation LabLoc,
3265 IdentifierInfo *LabelII) {
3266 // Look up the record for this label identifier.
3267 LabelStmt *&LabelDecl = LabelMap[LabelII];
3268
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00003269 // If we haven't seen this label yet, create a forward reference. It
3270 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00003271 if (LabelDecl == 0)
3272 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3273
3274 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00003275 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3276 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00003277}
3278
Steve Naroff1b273c42007-09-16 14:56:35 +00003279Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003280 SourceLocation RPLoc) { // "({..})"
3281 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3282 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3283 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3284
3285 // FIXME: there are a variety of strange constraints to enforce here, for
3286 // example, it is not possible to goto into a stmt expression apparently.
3287 // More semantic analysis is needed.
3288
3289 // FIXME: the last statement in the compount stmt has its value used. We
3290 // should not warn about it being unused.
3291
3292 // If there are sub stmts in the compound stmt, take the type of the last one
3293 // as the type of the stmtexpr.
3294 QualType Ty = Context.VoidTy;
3295
Chris Lattner611b2ec2008-07-26 19:51:01 +00003296 if (!Compound->body_empty()) {
3297 Stmt *LastStmt = Compound->body_back();
3298 // If LastStmt is a label, skip down through into the body.
3299 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3300 LastStmt = Label->getSubStmt();
3301
3302 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003303 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00003304 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003305
3306 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3307}
Steve Naroffd34e9152007-08-01 22:05:33 +00003308
Steve Naroff1b273c42007-09-16 14:56:35 +00003309Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003310 SourceLocation TypeLoc,
3311 TypeTy *argty,
3312 OffsetOfComponent *CompPtr,
3313 unsigned NumComponents,
3314 SourceLocation RPLoc) {
3315 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3316 assert(!ArgTy.isNull() && "Missing type argument!");
3317
3318 // We must have at least one component that refers to the type, and the first
3319 // one is known to be a field designator. Verify that the ArgTy represents
3320 // a struct/union/class.
3321 if (!ArgTy->isRecordType())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003322 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy.getAsString();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003323
3324 // Otherwise, create a compound literal expression as the base, and
3325 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00003326 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003327
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003328 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3329 // GCC extension, diagnose them.
3330 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003331 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3332 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003333
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003334 for (unsigned i = 0; i != NumComponents; ++i) {
3335 const OffsetOfComponent &OC = CompPtr[i];
3336 if (OC.isBrackets) {
3337 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003338 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003339 if (!AT) {
3340 delete Res;
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003341 return Diag(OC.LocEnd, diag::err_offsetof_array_type)
3342 << Res->getType().getAsString();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003343 }
3344
Chris Lattner704fe352007-08-30 17:59:59 +00003345 // FIXME: C++: Verify that operator[] isn't overloaded.
3346
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003347 // C99 6.5.2.1p1
3348 Expr *Idx = static_cast<Expr*>(OC.U.E);
3349 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003350 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3351 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003352
3353 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3354 continue;
3355 }
3356
3357 const RecordType *RC = Res->getType()->getAsRecordType();
3358 if (!RC) {
3359 delete Res;
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003360 return Diag(OC.LocEnd, diag::err_offsetof_record_type)
3361 << Res->getType().getAsString();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003362 }
3363
3364 // Get the decl corresponding to this.
3365 RecordDecl *RD = RC->getDecl();
3366 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3367 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00003368 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3369 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00003370
3371 // FIXME: C++: Verify that MemberDecl isn't a static field.
3372 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00003373 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3374 // matter here.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003375 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3376 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003377 }
3378
3379 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3380 BuiltinLoc);
3381}
3382
3383
Steve Naroff1b273c42007-09-16 14:56:35 +00003384Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00003385 TypeTy *arg1, TypeTy *arg2,
3386 SourceLocation RPLoc) {
3387 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3388 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3389
3390 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3391
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003392 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00003393}
3394
Steve Naroff1b273c42007-09-16 14:56:35 +00003395Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00003396 ExprTy *expr1, ExprTy *expr2,
3397 SourceLocation RPLoc) {
3398 Expr *CondExpr = static_cast<Expr*>(cond);
3399 Expr *LHSExpr = static_cast<Expr*>(expr1);
3400 Expr *RHSExpr = static_cast<Expr*>(expr2);
3401
3402 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3403
3404 // The conditional expression is required to be a constant expression.
3405 llvm::APSInt condEval(32);
3406 SourceLocation ExpLoc;
3407 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003408 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3409 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00003410
3411 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3412 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3413 RHSExpr->getType();
3414 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3415}
3416
Steve Naroff4eb206b2008-09-03 18:15:37 +00003417//===----------------------------------------------------------------------===//
3418// Clang Extensions.
3419//===----------------------------------------------------------------------===//
3420
3421/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00003422void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003423 // Analyze block parameters.
3424 BlockSemaInfo *BSI = new BlockSemaInfo();
3425
3426 // Add BSI to CurBlock.
3427 BSI->PrevBlockInfo = CurBlock;
3428 CurBlock = BSI;
3429
3430 BSI->ReturnType = 0;
3431 BSI->TheScope = BlockScope;
3432
Steve Naroff090276f2008-10-10 01:28:17 +00003433 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3434 PushDeclContext(BSI->TheDecl);
3435}
3436
3437void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003438 // Analyze arguments to block.
3439 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3440 "Not a function declarator!");
3441 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3442
Steve Naroff090276f2008-10-10 01:28:17 +00003443 CurBlock->hasPrototype = FTI.hasPrototype;
3444 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003445
3446 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3447 // no arguments, not a function that takes a single void argument.
3448 if (FTI.hasPrototype &&
3449 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3450 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3451 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3452 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00003453 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003454 } else if (FTI.hasPrototype) {
3455 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00003456 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3457 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003458 }
Steve Naroff090276f2008-10-10 01:28:17 +00003459 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3460
3461 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3462 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3463 // If this has an identifier, add it to the scope stack.
3464 if ((*AI)->getIdentifier())
3465 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003466}
3467
3468/// ActOnBlockError - If there is an error parsing a block, this callback
3469/// is invoked to pop the information about the block from the action impl.
3470void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3471 // Ensure that CurBlock is deleted.
3472 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3473
3474 // Pop off CurBlock, handle nested blocks.
3475 CurBlock = CurBlock->PrevBlockInfo;
3476
3477 // FIXME: Delete the ParmVarDecl objects as well???
3478
3479}
3480
3481/// ActOnBlockStmtExpr - This is called when the body of a block statement
3482/// literal was successfully completed. ^(int x){...}
3483Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3484 Scope *CurScope) {
3485 // Ensure that CurBlock is deleted.
3486 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3487 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3488
Steve Naroff090276f2008-10-10 01:28:17 +00003489 PopDeclContext();
3490
Steve Naroff4eb206b2008-09-03 18:15:37 +00003491 // Pop off CurBlock, handle nested blocks.
3492 CurBlock = CurBlock->PrevBlockInfo;
3493
3494 QualType RetTy = Context.VoidTy;
3495 if (BSI->ReturnType)
3496 RetTy = QualType(BSI->ReturnType, 0);
3497
3498 llvm::SmallVector<QualType, 8> ArgTypes;
3499 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3500 ArgTypes.push_back(BSI->Params[i]->getType());
3501
3502 QualType BlockTy;
3503 if (!BSI->hasPrototype)
3504 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3505 else
3506 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003507 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003508
3509 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003510
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003511 BSI->TheDecl->setBody(Body.take());
3512 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003513}
3514
Nate Begeman67295d02008-01-30 20:50:20 +00003515/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003516/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003517/// The number of arguments has already been validated to match the number of
3518/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003519static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3520 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003521 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003522 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003523 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3524 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003525
3526 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00003527 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00003528 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003529 return true;
3530}
3531
3532Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3533 SourceLocation *CommaLocs,
3534 SourceLocation BuiltinLoc,
3535 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003536 // __builtin_overload requires at least 2 arguments
3537 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003538 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3539 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003540
Nate Begemane2ce1d92008-01-17 17:46:27 +00003541 // The first argument is required to be a constant expression. It tells us
3542 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003543 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003544 Expr *NParamsExpr = Args[0];
3545 llvm::APSInt constEval(32);
3546 SourceLocation ExpLoc;
3547 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003548 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3549 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003550
3551 // Verify that the number of parameters is > 0
3552 unsigned NumParams = constEval.getZExtValue();
3553 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003554 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3555 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003556 // Verify that we have at least 1 + NumParams arguments to the builtin.
3557 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003558 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3559 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003560
3561 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00003562 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003563 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003564 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3565 // UsualUnaryConversions will convert the function DeclRefExpr into a
3566 // pointer to function.
3567 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00003568 const FunctionTypeProto *FnType = 0;
3569 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3570 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003571
3572 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3573 // parameters, and the number of parameters must match the value passed to
3574 // the builtin.
3575 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003576 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3577 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003578
3579 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00003580 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00003581 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003582 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003583 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003584 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3585 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00003586 // Remember our match, and continue processing the remaining arguments
3587 // to catch any errors.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003588 OE = new OverloadExpr(Args, NumArgs, i,
3589 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00003590 BuiltinLoc, RParenLoc);
3591 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003592 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00003593 // Return the newly created OverloadExpr node, if we succeded in matching
3594 // exactly one of the candidate functions.
3595 if (OE)
3596 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003597
3598 // If we didn't find a matching function Expr in the __builtin_overload list
3599 // the return an error.
3600 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00003601 for (unsigned i = 0; i != NumParams; ++i) {
3602 if (i != 0) typeNames += ", ";
3603 typeNames += Args[i+1]->getType().getAsString();
3604 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003605
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003606 return Diag(BuiltinLoc, diag::err_overload_no_match)
3607 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003608}
3609
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003610Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3611 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00003612 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003613 Expr *E = static_cast<Expr*>(expr);
3614 QualType T = QualType::getFromOpaquePtr(type);
3615
3616 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003617
3618 // Get the va_list type
3619 QualType VaListType = Context.getBuiltinVaListType();
3620 // Deal with implicit array decay; for example, on x86-64,
3621 // va_list is an array, but it's supposed to decay to
3622 // a pointer for va_arg.
3623 if (VaListType->isArrayType())
3624 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00003625 // Make sure the input expression also decays appropriately.
3626 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003627
3628 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003629 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003630 diag::err_first_argument_to_va_arg_not_of_type_va_list)
3631 << E->getType().getAsString() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003632
3633 // FIXME: Warn if a non-POD type is passed in.
3634
Douglas Gregor9d293df2008-10-28 00:22:11 +00003635 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003636}
3637
Chris Lattner5cf216b2008-01-04 18:04:52 +00003638bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3639 SourceLocation Loc,
3640 QualType DstType, QualType SrcType,
3641 Expr *SrcExpr, const char *Flavor) {
3642 // Decode the result (notice that AST's are still created for extensions).
3643 bool isInvalid = false;
3644 unsigned DiagKind;
3645 switch (ConvTy) {
3646 default: assert(0 && "Unknown conversion type");
3647 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003648 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00003649 DiagKind = diag::ext_typecheck_convert_pointer_int;
3650 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003651 case IntToPointer:
3652 DiagKind = diag::ext_typecheck_convert_int_pointer;
3653 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003654 case IncompatiblePointer:
3655 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3656 break;
3657 case FunctionVoidPointer:
3658 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3659 break;
3660 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00003661 // If the qualifiers lost were because we were applying the
3662 // (deprecated) C++ conversion from a string literal to a char*
3663 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3664 // Ideally, this check would be performed in
3665 // CheckPointerTypesForAssignment. However, that would require a
3666 // bit of refactoring (so that the second argument is an
3667 // expression, rather than a type), which should be done as part
3668 // of a larger effort to fix CheckPointerTypesForAssignment for
3669 // C++ semantics.
3670 if (getLangOptions().CPlusPlus &&
3671 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3672 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003673 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3674 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003675 case IntToBlockPointer:
3676 DiagKind = diag::err_int_to_block_pointer;
3677 break;
3678 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00003679 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003680 break;
3681 case BlockVoidPointer:
3682 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3683 break;
Steve Naroff39579072008-10-14 22:18:38 +00003684 case IncompatibleObjCQualifiedId:
3685 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3686 // it can give a more specific diagnostic.
3687 DiagKind = diag::warn_incompatible_qualified_id;
3688 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003689 case Incompatible:
3690 DiagKind = diag::err_typecheck_convert_incompatible;
3691 isInvalid = true;
3692 break;
3693 }
3694
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003695 Diag(Loc, DiagKind) << DstType.getAsString() << SrcType.getAsString()
3696 << Flavor << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00003697 return isInvalid;
3698}