blob: d3650c8ae19f55ce413d745ea7560ad9fe70de1b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-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).
Argiris Kirtzidisf580b4d2008-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 Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-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 Lattner299b8842008-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 Lattner9305c3d2008-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 Lattner299b8842008-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 }
102 // For conversion purposes, we ignore any qualifiers.
103 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000104 QualType lhs =
105 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
106 QualType rhs =
107 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattner299b8842008-07-25 21:10:04 +0000108
109 // If both types are identical, no conversion is needed.
110 if (lhs == rhs)
111 return lhs;
112
113 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
114 // The caller can deal with this (e.g. pointer + int).
115 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
116 return lhs;
117
118 // At this point, we have two different arithmetic types.
119
120 // Handle complex types first (C99 6.3.1.8p1).
121 if (lhs->isComplexType() || rhs->isComplexType()) {
122 // if we have an integer operand, the result is the complex type.
123 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
124 // convert the rhs to the lhs complex type.
125 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
126 return lhs;
127 }
128 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
129 // convert the lhs to the rhs complex type.
130 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
131 return rhs;
132 }
133 // This handles complex/complex, complex/float, or float/complex.
134 // When both operands are complex, the shorter operand is converted to the
135 // type of the longer, and that is the type of the result. This corresponds
136 // to what is done when combining two real floating-point operands.
137 // The fun begins when size promotion occur across type domains.
138 // From H&S 6.3.4: When one operand is complex and the other is a real
139 // floating-point type, the less precise type is converted, within it's
140 // real or complex domain, to the precision of the other type. For example,
141 // when combining a "long double" with a "double _Complex", the
142 // "double _Complex" is promoted to "long double _Complex".
143 int result = Context.getFloatingTypeOrder(lhs, rhs);
144
145 if (result > 0) { // The left side is bigger, convert rhs.
146 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
147 if (!isCompAssign)
148 ImpCastExprToType(rhsExpr, rhs);
149 } else if (result < 0) { // The right side is bigger, convert lhs.
150 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
151 if (!isCompAssign)
152 ImpCastExprToType(lhsExpr, lhs);
153 }
154 // At this point, lhs and rhs have the same rank/size. Now, make sure the
155 // domains match. This is a requirement for our implementation, C99
156 // does not require this promotion.
157 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
158 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
159 if (!isCompAssign)
160 ImpCastExprToType(lhsExpr, rhs);
161 return rhs;
162 } else { // handle "_Complex double, double".
163 if (!isCompAssign)
164 ImpCastExprToType(rhsExpr, lhs);
165 return lhs;
166 }
167 }
168 return lhs; // The domain/size match exactly.
169 }
170 // Now handle "real" floating types (i.e. float, double, long double).
171 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
172 // if we have an integer operand, the result is the real floating type.
173 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
174 // convert rhs to the lhs floating point type.
175 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
176 return lhs;
177 }
178 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
179 // convert lhs to the rhs floating point type.
180 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
181 return rhs;
182 }
183 // We have two real floating types, float/complex combos were handled above.
184 // Convert the smaller operand to the bigger result.
185 int result = Context.getFloatingTypeOrder(lhs, rhs);
186
187 if (result > 0) { // convert the rhs
188 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
189 return lhs;
190 }
191 if (result < 0) { // convert the lhs
192 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
193 return rhs;
194 }
195 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
196 }
197 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
198 // Handle GCC complex int extension.
199 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
200 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
201
202 if (lhsComplexInt && rhsComplexInt) {
203 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
204 rhsComplexInt->getElementType()) >= 0) {
205 // convert the rhs
206 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
207 return lhs;
208 }
209 if (!isCompAssign)
210 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
211 return rhs;
212 } else if (lhsComplexInt && rhs->isIntegerType()) {
213 // convert the rhs to the lhs complex type.
214 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
215 return lhs;
216 } else if (rhsComplexInt && lhs->isIntegerType()) {
217 // convert the lhs to the rhs complex type.
218 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
219 return rhs;
220 }
221 }
222 // Finally, we have two differing integer types.
223 // The rules for this case are in C99 6.3.1.8
224 int compare = Context.getIntegerTypeOrder(lhs, rhs);
225 bool lhsSigned = lhs->isSignedIntegerType(),
226 rhsSigned = rhs->isSignedIntegerType();
227 QualType destType;
228 if (lhsSigned == rhsSigned) {
229 // Same signedness; use the higher-ranked type
230 destType = compare >= 0 ? lhs : rhs;
231 } else if (compare != (lhsSigned ? 1 : -1)) {
232 // The unsigned type has greater than or equal rank to the
233 // signed type, so use the unsigned type
234 destType = lhsSigned ? rhs : lhs;
235 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
236 // The two types are different widths; if we are here, that
237 // means the signed type is larger than the unsigned type, so
238 // use the signed type.
239 destType = lhsSigned ? lhs : rhs;
240 } else {
241 // The signed type is higher-ranked than the unsigned type,
242 // but isn't actually any bigger (like unsigned int and long
243 // on most 32-bit systems). Use the unsigned type corresponding
244 // to the signed type.
245 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
246 }
247 if (!isCompAssign) {
248 ImpCastExprToType(lhsExpr, destType);
249 ImpCastExprToType(rhsExpr, destType);
250 }
251 return destType;
252}
253
254//===----------------------------------------------------------------------===//
255// Semantic Analysis for various Expression Types
256//===----------------------------------------------------------------------===//
257
258
Steve Naroff87d58b42007-09-16 03:34:24 +0000259/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000260/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
261/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
262/// multiple tokens. However, the common case is that StringToks points to one
263/// string.
264///
265Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000266Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000267 assert(NumStringToks && "Must have at least one string!");
268
269 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
270 if (Literal.hadError)
271 return ExprResult(true);
272
273 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
274 for (unsigned i = 0; i != NumStringToks; ++i)
275 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000276
277 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000278 if (Literal.Pascal && Literal.GetStringLength() > 256)
279 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
280 SourceRange(StringToks[0].getLocation(),
281 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000282
Chris Lattnera6dcce32008-02-11 00:02:17 +0000283 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000284 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000285 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000286
287 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
288 if (getLangOptions().CPlusPlus)
289 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000290
291 // Get an array type for the string, according to C99 6.4.5. This includes
292 // the nul terminator character as well as the string length for pascal
293 // strings.
294 StrTy = Context.getConstantArrayType(StrTy,
295 llvm::APInt(32, Literal.GetStringLength()+1),
296 ArrayType::Normal, 0);
297
Chris Lattner4b009652007-07-25 00:24:17 +0000298 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
299 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000300 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000301 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000302 StringToks[NumStringToks-1].getLocation());
303}
304
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000305/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
306/// CurBlock to VD should cause it to be snapshotted (as we do for auto
307/// variables defined outside the block) or false if this is not needed (e.g.
308/// for values inside the block or for globals).
309///
310/// FIXME: This will create BlockDeclRefExprs for global variables,
311/// function references, etc which is suboptimal :) and breaks
312/// things like "integer constant expression" tests.
313static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
314 ValueDecl *VD) {
315 // If the value is defined inside the block, we couldn't snapshot it even if
316 // we wanted to.
317 if (CurBlock->TheDecl == VD->getDeclContext())
318 return false;
319
320 // If this is an enum constant or function, it is constant, don't snapshot.
321 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
322 return false;
323
324 // If this is a reference to an extern, static, or global variable, no need to
325 // snapshot it.
326 // FIXME: What about 'const' variables in C++?
327 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
328 return Var->hasLocalStorage();
329
330 return true;
331}
332
333
334
Steve Naroff0acc9c92007-09-15 18:49:24 +0000335/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000336/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000337/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000338Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000339 IdentifierInfo &II,
340 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000341 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000342 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000343
344 // If this reference is in an Objective-C method, then ivar lookup happens as
345 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000346 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000347 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000348 // There are two cases to handle here. 1) scoped lookup could have failed,
349 // in which case we should look for an ivar. 2) scoped lookup could have
350 // found a decl, but that decl is outside the current method (i.e. a global
351 // variable). In these two cases, we do a lookup for an ivar with this
352 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000353 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000354 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000355 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000356 // FIXME: This should use a new expr for a direct reference, don't turn
357 // this into Self->ivar, just return a BareIVarExpr or something.
358 IdentifierInfo &II = Context.Idents.get("self");
359 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
360 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
361 static_cast<Expr*>(SelfExpr.Val), true, true);
362 }
363 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000364 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000365 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000366 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000367 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000368 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000369 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000370 }
Chris Lattner4b009652007-07-25 00:24:17 +0000371 if (D == 0) {
372 // Otherwise, this could be an implicitly declared function reference (legal
373 // in C90, extension in C99).
374 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000375 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000376 D = ImplicitlyDefineFunction(Loc, II, S);
377 else {
378 // If this name wasn't predeclared and if this is not a function call,
379 // diagnose the problem.
380 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
381 }
382 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000383
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000384 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
385 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
386 if (MD->isStatic())
387 // "invalid use of member 'x' in static member function"
388 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
389 FD->getName());
390 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
391 // "invalid use of nonstatic data member 'x'"
392 return Diag(Loc, diag::err_invalid_non_static_member_use,
393 FD->getName());
394
395 if (FD->isInvalidDecl())
396 return true;
397
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000398 // FIXME: Handle 'mutable'.
399 return new DeclRefExpr(FD,
400 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000401 }
402
403 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
404 }
Chris Lattner4b009652007-07-25 00:24:17 +0000405 if (isa<TypedefDecl>(D))
406 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000407 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000408 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000409 if (isa<NamespaceDecl>(D))
410 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000411
Steve Naroffd6163f32008-09-05 22:11:13 +0000412 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000413 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
414 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
415
Steve Naroffd6163f32008-09-05 22:11:13 +0000416 ValueDecl *VD = cast<ValueDecl>(D);
417
418 // check if referencing an identifier with __attribute__((deprecated)).
419 if (VD->getAttr<DeprecatedAttr>())
420 Diag(Loc, diag::warn_deprecated, VD->getName());
421
422 // Only create DeclRefExpr's for valid Decl's.
423 if (VD->isInvalidDecl())
424 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000425
426 // If the identifier reference is inside a block, and it refers to a value
427 // that is outside the block, create a BlockDeclRefExpr instead of a
428 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
429 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000430 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000431 // We do not do this for things like enum constants, global variables, etc,
432 // as they do not get snapshotted.
433 //
434 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000435 // The BlocksAttr indicates the variable is bound by-reference.
436 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000437 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
438 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000439
440 // Variable will be bound by-copy, make it const within the closure.
441 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000442 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
443 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000444 }
445 // If this reference is not in a block or if the referenced variable is
446 // within the block, create a normal DeclRefExpr.
Douglas Gregor3fb675a2008-10-22 04:14:44 +0000447 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000448}
449
Chris Lattner69909292008-08-10 01:53:14 +0000450Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000451 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000452 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000453
454 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000455 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000456 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
457 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
458 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000459 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000460
461 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000462 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000463 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000464
Chris Lattner7e637512008-01-12 08:14:25 +0000465 // Pre-defined identifiers are of type char[x], where x is the length of the
466 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000467 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000468 if (getCurFunctionDecl())
469 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000470 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000471 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000472
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000473 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000474 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000475 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000476 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000477}
478
Steve Naroff87d58b42007-09-16 03:34:24 +0000479Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000480 llvm::SmallString<16> CharBuffer;
481 CharBuffer.resize(Tok.getLength());
482 const char *ThisTokBegin = &CharBuffer[0];
483 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
484
485 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
486 Tok.getLocation(), PP);
487 if (Literal.hadError())
488 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000489
490 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
491
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000492 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
493 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000494}
495
Steve Naroff87d58b42007-09-16 03:34:24 +0000496Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000497 // fast path for a single digit (which is quite common). A single digit
498 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
499 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000500 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000501
Chris Lattner8cd0e932008-03-05 18:54:05 +0000502 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000503 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000504 Context.IntTy,
505 Tok.getLocation()));
506 }
507 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000508 // Add padding so that NumericLiteralParser can overread by one character.
509 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000510 const char *ThisTokBegin = &IntegerBuffer[0];
511
512 // Get the spelling of the token, which eliminates trigraphs, etc.
513 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000514
Chris Lattner4b009652007-07-25 00:24:17 +0000515 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
516 Tok.getLocation(), PP);
517 if (Literal.hadError)
518 return ExprResult(true);
519
Chris Lattner1de66eb2007-08-26 03:42:43 +0000520 Expr *Res;
521
522 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000523 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000524 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000525 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000526 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000527 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000528 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000529 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000530
531 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
532
Ted Kremenekddedbe22007-11-29 00:56:49 +0000533 // isExact will be set by GetFloatValue().
534 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000535 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000536 Ty, Tok.getLocation());
537
Chris Lattner1de66eb2007-08-26 03:42:43 +0000538 } else if (!Literal.isIntegerLiteral()) {
539 return ExprResult(true);
540 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000541 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000542
Neil Booth7421e9c2007-08-29 22:00:19 +0000543 // long long is a C99 feature.
544 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000545 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000546 Diag(Tok.getLocation(), diag::ext_longlong);
547
Chris Lattner4b009652007-07-25 00:24:17 +0000548 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000549 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000550
551 if (Literal.GetIntegerValue(ResultVal)) {
552 // If this value didn't fit into uintmax_t, warn and force to ull.
553 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000554 Ty = Context.UnsignedLongLongTy;
555 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000556 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000557 } else {
558 // If this value fits into a ULL, try to figure out what else it fits into
559 // according to the rules of C99 6.4.4.1p5.
560
561 // Octal, Hexadecimal, and integers with a U suffix are allowed to
562 // be an unsigned int.
563 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
564
565 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000566 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000567 if (!Literal.isLong && !Literal.isLongLong) {
568 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000569 unsigned IntSize = Context.Target.getIntWidth();
570
Chris Lattner4b009652007-07-25 00:24:17 +0000571 // Does it fit in a unsigned int?
572 if (ResultVal.isIntN(IntSize)) {
573 // Does it fit in a signed int?
574 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000575 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000576 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000577 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000578 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000579 }
Chris Lattner4b009652007-07-25 00:24:17 +0000580 }
581
582 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000583 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000584 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000585
586 // Does it fit in a unsigned long?
587 if (ResultVal.isIntN(LongSize)) {
588 // Does it fit in a signed long?
589 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000590 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000591 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000592 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000593 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000594 }
Chris Lattner4b009652007-07-25 00:24:17 +0000595 }
596
597 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000598 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000599 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000600
601 // Does it fit in a unsigned long long?
602 if (ResultVal.isIntN(LongLongSize)) {
603 // Does it fit in a signed long long?
604 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000605 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000606 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000607 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000608 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000609 }
610 }
611
612 // If we still couldn't decide a type, we probably have something that
613 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000614 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000615 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000616 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000617 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000618 }
Chris Lattnere4068872008-05-09 05:59:00 +0000619
620 if (ResultVal.getBitWidth() != Width)
621 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000622 }
623
Chris Lattner48d7f382008-04-02 04:24:33 +0000624 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000625 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000626
627 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
628 if (Literal.isImaginary)
629 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
630
631 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000632}
633
Steve Naroff87d58b42007-09-16 03:34:24 +0000634Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000635 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000636 Expr *E = (Expr *)Val;
637 assert((E != 0) && "ActOnParenExpr() missing expr");
638 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000639}
640
641/// The UsualUnaryConversions() function is *not* called by this routine.
642/// See C99 6.3.2.1p[2-4] for more details.
643QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000644 SourceLocation OpLoc,
645 const SourceRange &ExprRange,
646 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000647 // C99 6.5.3.4p1:
648 if (isa<FunctionType>(exprType) && isSizeof)
649 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000650 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000651 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000652 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
653 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000654 else if (exprType->isIncompleteType()) {
655 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
656 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000657 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000658 return QualType(); // error
659 }
660 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
661 return Context.getSizeType();
662}
663
664Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000665ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000666 SourceLocation LPLoc, TypeTy *Ty,
667 SourceLocation RPLoc) {
668 // If error parsing type, ignore.
669 if (Ty == 0) return true;
670
671 // Verify that this is a valid expression.
672 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
673
Chris Lattnerf814d882008-07-25 21:45:37 +0000674 QualType resultType =
675 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000676
677 if (resultType.isNull())
678 return true;
679 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
680}
681
Chris Lattner5110ad52007-08-24 21:41:10 +0000682QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000683 DefaultFunctionArrayConversion(V);
684
Chris Lattnera16e42d2007-08-26 05:39:26 +0000685 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000686 if (const ComplexType *CT = V->getType()->getAsComplexType())
687 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000688
689 // Otherwise they pass through real integer and floating point types here.
690 if (V->getType()->isArithmeticType())
691 return V->getType();
692
693 // Reject anything else.
694 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
695 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000696}
697
698
Chris Lattner4b009652007-07-25 00:24:17 +0000699
Steve Naroff87d58b42007-09-16 03:34:24 +0000700Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000701 tok::TokenKind Kind,
702 ExprTy *Input) {
703 UnaryOperator::Opcode Opc;
704 switch (Kind) {
705 default: assert(0 && "Unknown unary op!");
706 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
707 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
708 }
709 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
710 if (result.isNull())
711 return true;
712 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
713}
714
715Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000716ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000717 ExprTy *Idx, SourceLocation RLoc) {
718 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
719
720 // Perform default conversions.
721 DefaultFunctionArrayConversion(LHSExp);
722 DefaultFunctionArrayConversion(RHSExp);
723
724 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
725
726 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000727 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000728 // in the subscript position. As a result, we need to derive the array base
729 // and index from the expression types.
730 Expr *BaseExpr, *IndexExpr;
731 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000732 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000733 BaseExpr = LHSExp;
734 IndexExpr = RHSExp;
735 // FIXME: need to deal with const...
736 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000737 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000738 // Handle the uncommon case of "123[Ptr]".
739 BaseExpr = RHSExp;
740 IndexExpr = LHSExp;
741 // FIXME: need to deal with const...
742 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000743 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
744 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000745 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000746
747 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000748 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
749 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000750 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000751 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000752 // FIXME: need to deal with const...
753 ResultType = VTy->getElementType();
754 } else {
755 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
756 RHSExp->getSourceRange());
757 }
758 // C99 6.5.2.1p1
759 if (!IndexExpr->getType()->isIntegerType())
760 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
761 IndexExpr->getSourceRange());
762
763 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
764 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000765 // void (*)(int)) and pointers to incomplete types. Functions are not
766 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000767 if (!ResultType->isObjectType())
768 return Diag(BaseExpr->getLocStart(),
769 diag::err_typecheck_subscript_not_object,
770 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
771
772 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
773}
774
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000775QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000776CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000777 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000778 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000779
780 // This flag determines whether or not the component is to be treated as a
781 // special name, or a regular GLSL-style component access.
782 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000783
784 // The vector accessor can't exceed the number of elements.
785 const char *compStr = CompName.getName();
786 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000787 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000788 baseType.getAsString(), SourceRange(CompLoc));
789 return QualType();
790 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000791
792 // Check that we've found one of the special components, or that the component
793 // names must come from the same set.
794 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
795 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
796 SpecialComponent = true;
797 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000798 do
799 compStr++;
800 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
801 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
802 do
803 compStr++;
804 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
805 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
806 do
807 compStr++;
808 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
809 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000810
Nate Begemanc8e51f82008-05-09 06:41:27 +0000811 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000812 // We didn't get to the end of the string. This means the component names
813 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000814 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000815 std::string(compStr,compStr+1), SourceRange(CompLoc));
816 return QualType();
817 }
818 // Each component accessor can't exceed the vector type.
819 compStr = CompName.getName();
820 while (*compStr) {
821 if (vecType->isAccessorWithinNumElements(*compStr))
822 compStr++;
823 else
824 break;
825 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000826 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000827 // We didn't get to the end of the string. This means a component accessor
828 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000829 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000830 baseType.getAsString(), SourceRange(CompLoc));
831 return QualType();
832 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000833
834 // If we have a special component name, verify that the current vector length
835 // is an even number, since all special component names return exactly half
836 // the elements.
837 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbar45a91802008-09-30 17:22:47 +0000838 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
839 baseType.getAsString(), SourceRange(CompLoc));
Nate Begemanc8e51f82008-05-09 06:41:27 +0000840 return QualType();
841 }
842
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000843 // The component accessor looks fine - now we need to compute the actual type.
844 // The vector type is implied by the component accessor. For example,
845 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000846 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
847 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
848 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000849 if (CompSize == 1)
850 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000851
Nate Begemanaf6ed502008-04-18 23:10:10 +0000852 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000853 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000854 // diagostics look bad. We want extended vector types to appear built-in.
855 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
856 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
857 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000858 }
859 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000860}
861
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000862/// constructSetterName - Return the setter name for the given
863/// identifier, i.e. "set" + Name where the initial character of Name
864/// has been capitalized.
865// FIXME: Merge with same routine in Parser. But where should this
866// live?
867static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
868 const IdentifierInfo *Name) {
869 unsigned N = Name->getLength();
870 char *SelectorName = new char[3 + N];
871 memcpy(SelectorName, "set", 3);
872 memcpy(&SelectorName[3], Name->getName(), N);
873 SelectorName[3] = toupper(SelectorName[3]);
874
875 IdentifierInfo *Setter =
876 &Idents.get(SelectorName, &SelectorName[3 + N]);
877 delete[] SelectorName;
878 return Setter;
879}
880
Chris Lattner4b009652007-07-25 00:24:17 +0000881Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000882ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000883 tok::TokenKind OpKind, SourceLocation MemberLoc,
884 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000885 Expr *BaseExpr = static_cast<Expr *>(Base);
886 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000887
888 // Perform default conversions.
889 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000890
Steve Naroff2cb66382007-07-26 03:11:44 +0000891 QualType BaseType = BaseExpr->getType();
892 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000893
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000894 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
895 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000896 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000897 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000898 BaseType = PT->getPointeeType();
899 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000900 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
901 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000902 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000903
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000904 // Handle field access to simple records. This also handles access to fields
905 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000906 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000907 RecordDecl *RDecl = RTy->getDecl();
908 if (RTy->isIncompleteType())
909 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
910 BaseExpr->getSourceRange());
911 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000912 FieldDecl *MemberDecl = RDecl->getMember(&Member);
913 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000914 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
915 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000916
917 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000918 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000919 QualType MemberType = MemberDecl->getType();
920 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000921 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000922 MemberType = MemberType.getQualifiedType(combinedQualifiers);
923
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000924 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000925 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000926 }
927
Chris Lattnere9d71612008-07-21 04:59:05 +0000928 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
929 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000930 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
931 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000932 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000933 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000934 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000935 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000936 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000937 }
938
Chris Lattnere9d71612008-07-21 04:59:05 +0000939 // Handle Objective-C property access, which is "Obj.property" where Obj is a
940 // pointer to a (potentially qualified) interface type.
941 const PointerType *PTy;
942 const ObjCInterfaceType *IFTy;
943 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
944 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
945 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000946
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000947 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000948 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
949 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
950
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000951 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000952 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
953 E = IFTy->qual_end(); I != E; ++I)
954 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
955 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000956
957 // If that failed, look for an "implicit" property by seeing if the nullary
958 // selector is implemented.
959
960 // FIXME: The logic for looking up nullary and unary selectors should be
961 // shared with the code in ActOnInstanceMessage.
962
963 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
964 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
965
966 // If this reference is in an @implementation, check for 'private' methods.
967 if (!Getter)
968 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
969 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
970 if (ObjCImplementationDecl *ImpDecl =
971 ObjCImplementations[ClassDecl->getIdentifier()])
972 Getter = ImpDecl->getInstanceMethod(Sel);
973
Steve Naroff04151f32008-10-22 19:16:27 +0000974 // Look through local category implementations associated with the class.
975 if (!Getter) {
976 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
977 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
978 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
979 }
980 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000981 if (Getter) {
982 // If we found a getter then this may be a valid dot-reference, we
983 // need to also look for the matching setter.
984 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
985 &Member);
986 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
987 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
988
989 if (!Setter) {
990 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
991 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
992 if (ObjCImplementationDecl *ImpDecl =
993 ObjCImplementations[ClassDecl->getIdentifier()])
994 Setter = ImpDecl->getInstanceMethod(SetterSel);
995 }
996
997 // FIXME: There are some issues here. First, we are not
998 // diagnosing accesses to read-only properties because we do not
999 // know if this is a getter or setter yet. Second, we are
1000 // checking that the type of the setter matches the type we
1001 // expect.
1002 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1003 MemberLoc, BaseExpr);
1004 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001005 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001006 // Handle properties on qualified "id" protocols.
1007 const ObjCQualifiedIdType *QIdTy;
1008 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1009 // Check protocols on qualified interfaces.
1010 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1011 E = QIdTy->qual_end(); I != E; ++I)
1012 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1013 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1014 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001015 // Handle 'field access' to vectors, such as 'V.xx'.
1016 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1017 // Component access limited to variables (reject vec4.rg.g).
1018 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1019 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +00001020 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1021 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001022 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1023 if (ret.isNull())
1024 return true;
1025 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1026 }
1027
Chris Lattner7d5a8762008-07-21 05:35:34 +00001028 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1029 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001030}
1031
Steve Naroff87d58b42007-09-16 03:34:24 +00001032/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001033/// This provides the location of the left/right parens and a list of comma
1034/// locations.
1035Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001036ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001037 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001038 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1039 Expr *Fn = static_cast<Expr *>(fn);
1040 Expr **Args = reinterpret_cast<Expr**>(args);
1041 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001042 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001043 OverloadedFunctionDecl *Ovl = NULL;
1044
1045 // If we're directly calling a function or a set of overloaded
1046 // functions, get the appropriate declaration.
1047 {
1048 DeclRefExpr *DRExpr = NULL;
1049 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1050 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1051 else
1052 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1053
1054 if (DRExpr) {
1055 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1056 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1057 }
1058 }
1059
1060 // If we have a set of overloaded functions, perform overload
1061 // resolution to pick the function.
1062 if (Ovl) {
1063 OverloadCandidateSet CandidateSet;
1064 OverloadCandidateSet::iterator Best;
1065 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1066 switch (BestViableFunction(CandidateSet, Best)) {
1067 case OR_Success:
1068 {
1069 // Success! Let the remainder of this function build a call to
1070 // the function selected by overload resolution.
1071 FDecl = Best->Function;
1072 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1073 Fn->getSourceRange().getBegin());
1074 delete Fn;
1075 Fn = NewFn;
1076 }
1077 break;
1078
1079 case OR_No_Viable_Function:
1080 if (CandidateSet.empty())
1081 Diag(Fn->getSourceRange().getBegin(),
1082 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1083 Fn->getSourceRange());
1084 else {
1085 Diag(Fn->getSourceRange().getBegin(),
1086 diag::err_ovl_no_viable_function_in_call_with_cands,
1087 Ovl->getName(), Fn->getSourceRange());
1088 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1089 }
1090 return true;
1091
1092 case OR_Ambiguous:
1093 Diag(Fn->getSourceRange().getBegin(),
1094 diag::err_ovl_ambiguous_call, Ovl->getName(),
1095 Fn->getSourceRange());
1096 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1097 return true;
1098 }
1099 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001100
1101 // Promote the function operand.
1102 UsualUnaryConversions(Fn);
1103
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001104 // Make the call expr early, before semantic checks. This guarantees cleanup
1105 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001106 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001107 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001108 const FunctionType *FuncT;
1109 if (!Fn->getType()->isBlockPointerType()) {
1110 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1111 // have type pointer to function".
1112 const PointerType *PT = Fn->getType()->getAsPointerType();
1113 if (PT == 0)
1114 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1115 Fn->getSourceRange());
1116 FuncT = PT->getPointeeType()->getAsFunctionType();
1117 } else { // This is a block call.
1118 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1119 getAsFunctionType();
1120 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001121 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001122 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1123 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001124
1125 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001126 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001127
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001128 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001129 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1130 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001131 unsigned NumArgsInProto = Proto->getNumArgs();
1132 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001133
Chris Lattner3e254fb2008-04-08 04:40:51 +00001134 // If too few arguments are available (and we don't have default
1135 // arguments for the remaining parameters), don't make the call.
1136 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001137 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001138 // Use default arguments for missing arguments
1139 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001140 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001141 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001142 return Diag(RParenLoc,
1143 !Fn->getType()->isBlockPointerType()
1144 ? diag::err_typecheck_call_too_few_args
1145 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001146 Fn->getSourceRange());
1147 }
1148
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001149 // If too many are passed and not variadic, error on the extras and drop
1150 // them.
1151 if (NumArgs > NumArgsInProto) {
1152 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001153 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001154 !Fn->getType()->isBlockPointerType()
1155 ? diag::err_typecheck_call_too_many_args
1156 : diag::err_typecheck_block_too_many_args,
1157 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001158 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001159 Args[NumArgs-1]->getLocEnd()));
1160 // This deletes the extra arguments.
1161 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001162 }
1163 NumArgsToCheck = NumArgsInProto;
1164 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001165
Chris Lattner4b009652007-07-25 00:24:17 +00001166 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001167 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001168 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001169
1170 Expr *Arg;
1171 if (i < NumArgs)
1172 Arg = Args[i];
1173 else
1174 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001175 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001176
Douglas Gregor81c29152008-10-29 00:13:59 +00001177 // Pass the argument.
1178 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001179 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001180
1181 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001182 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001183
1184 // If this is a variadic call, handle args passed through "...".
1185 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001186 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001187 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1188 Expr *Arg = Args[i];
1189 DefaultArgumentPromotion(Arg);
1190 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001191 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001192 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001193 } else {
1194 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1195
Steve Naroffdb65e052007-08-28 23:30:39 +00001196 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001197 for (unsigned i = 0; i != NumArgs; i++) {
1198 Expr *Arg = Args[i];
1199 DefaultArgumentPromotion(Arg);
1200 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001201 }
Chris Lattner4b009652007-07-25 00:24:17 +00001202 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001203
Chris Lattner2e64c072007-08-10 20:18:51 +00001204 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001205 if (FDecl)
1206 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001207
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001208 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001209}
1210
1211Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001212ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001213 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001214 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001215 QualType literalType = QualType::getFromOpaquePtr(Ty);
1216 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001217 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001218 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001219
Eli Friedman8c2173d2008-05-20 05:22:08 +00001220 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001221 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001222 return Diag(LParenLoc,
1223 diag::err_variable_object_no_init,
1224 SourceRange(LParenLoc,
1225 literalExpr->getSourceRange().getEnd()));
1226 } else if (literalType->isIncompleteType()) {
1227 return Diag(LParenLoc,
1228 diag::err_typecheck_decl_incomplete_type,
1229 literalType.getAsString(),
1230 SourceRange(LParenLoc,
1231 literalExpr->getSourceRange().getEnd()));
1232 }
1233
Douglas Gregor6428e762008-11-05 15:29:30 +00001234 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
1235 "temporary"))
Steve Naroff92590f92008-01-09 20:58:06 +00001236 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001237
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001238 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001239 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001240 if (CheckForConstantInitializer(literalExpr, literalType))
1241 return true;
1242 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001243 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1244 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001245}
1246
1247Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001248ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001249 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001250 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001251 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001252
Steve Naroff0acc9c92007-09-15 18:49:24 +00001253 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001254 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001255
Chris Lattner71ca8c82008-10-26 23:43:26 +00001256 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1257 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001258 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1259 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001260}
1261
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001262/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001263bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001264 UsualUnaryConversions(castExpr);
1265
1266 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1267 // type needs to be scalar.
1268 if (castType->isVoidType()) {
1269 // Cast to void allows any expr type.
1270 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1271 // GCC struct/union extension: allow cast to self.
1272 if (Context.getCanonicalType(castType) !=
1273 Context.getCanonicalType(castExpr->getType()) ||
1274 (!castType->isStructureType() && !castType->isUnionType())) {
1275 // Reject any other conversions to non-scalar types.
1276 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1277 castType.getAsString(), castExpr->getSourceRange());
1278 }
1279
1280 // accept this, but emit an ext-warn.
1281 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1282 castType.getAsString(), castExpr->getSourceRange());
1283 } else if (!castExpr->getType()->isScalarType() &&
1284 !castExpr->getType()->isVectorType()) {
1285 return Diag(castExpr->getLocStart(),
1286 diag::err_typecheck_expect_scalar_operand,
1287 castExpr->getType().getAsString(),castExpr->getSourceRange());
1288 } else if (castExpr->getType()->isVectorType()) {
1289 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1290 return true;
1291 } else if (castType->isVectorType()) {
1292 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1293 return true;
1294 }
1295 return false;
1296}
1297
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001298bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001299 assert(VectorTy->isVectorType() && "Not a vector type!");
1300
1301 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001302 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001303 return Diag(R.getBegin(),
1304 Ty->isVectorType() ?
1305 diag::err_invalid_conversion_between_vectors :
1306 diag::err_invalid_conversion_between_vector_and_integer,
1307 VectorTy.getAsString().c_str(),
1308 Ty.getAsString().c_str(), R);
1309 } else
1310 return Diag(R.getBegin(),
1311 diag::err_invalid_conversion_between_vector_and_scalar,
1312 VectorTy.getAsString().c_str(),
1313 Ty.getAsString().c_str(), R);
1314
1315 return false;
1316}
1317
Chris Lattner4b009652007-07-25 00:24:17 +00001318Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001319ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001320 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001321 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001322
1323 Expr *castExpr = static_cast<Expr*>(Op);
1324 QualType castType = QualType::getFromOpaquePtr(Ty);
1325
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001326 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1327 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001328 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001329}
1330
Chris Lattner98a425c2007-11-26 01:40:58 +00001331/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1332/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001333inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1334 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1335 UsualUnaryConversions(cond);
1336 UsualUnaryConversions(lex);
1337 UsualUnaryConversions(rex);
1338 QualType condT = cond->getType();
1339 QualType lexT = lex->getType();
1340 QualType rexT = rex->getType();
1341
1342 // first, check the condition.
1343 if (!condT->isScalarType()) { // C99 6.5.15p2
1344 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1345 condT.getAsString());
1346 return QualType();
1347 }
Chris Lattner992ae932008-01-06 22:42:25 +00001348
1349 // Now check the two expressions.
1350
1351 // If both operands have arithmetic type, do the usual arithmetic conversions
1352 // to find a common type: C99 6.5.15p3,5.
1353 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001354 UsualArithmeticConversions(lex, rex);
1355 return lex->getType();
1356 }
Chris Lattner992ae932008-01-06 22:42:25 +00001357
1358 // If both operands are the same structure or union type, the result is that
1359 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001360 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001361 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001362 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001363 // "If both the operands have structure or union type, the result has
1364 // that type." This implies that CV qualifiers are dropped.
1365 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001366 }
Chris Lattner992ae932008-01-06 22:42:25 +00001367
1368 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001369 // The following || allows only one side to be void (a GCC-ism).
1370 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001371 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001372 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1373 rex->getSourceRange());
1374 if (!rexT->isVoidType())
1375 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001376 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001377 ImpCastExprToType(lex, Context.VoidTy);
1378 ImpCastExprToType(rex, Context.VoidTy);
1379 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001380 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001381 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1382 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001383 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1384 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001385 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001386 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001387 return lexT;
1388 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001389 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1390 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001391 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001392 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001393 return rexT;
1394 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001395 // Handle the case where both operands are pointers before we handle null
1396 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001397 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1398 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1399 // get the "pointed to" types
1400 QualType lhptee = LHSPT->getPointeeType();
1401 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001402
Chris Lattner71225142007-07-31 21:27:01 +00001403 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1404 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001405 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001406 // Figure out necessary qualifiers (C99 6.5.15p6)
1407 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001408 QualType destType = Context.getPointerType(destPointee);
1409 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1410 ImpCastExprToType(rex, destType); // promote to void*
1411 return destType;
1412 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001413 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001414 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001415 QualType destType = Context.getPointerType(destPointee);
1416 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1417 ImpCastExprToType(rex, destType); // promote to void*
1418 return destType;
1419 }
Chris Lattner4b009652007-07-25 00:24:17 +00001420
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001421 QualType compositeType = lexT;
1422
1423 // If either type is an Objective-C object type then check
1424 // compatibility according to Objective-C.
1425 if (Context.isObjCObjectPointerType(lexT) ||
1426 Context.isObjCObjectPointerType(rexT)) {
1427 // If both operands are interfaces and either operand can be
1428 // assigned to the other, use that type as the composite
1429 // type. This allows
1430 // xxx ? (A*) a : (B*) b
1431 // where B is a subclass of A.
1432 //
1433 // Additionally, as for assignment, if either type is 'id'
1434 // allow silent coercion. Finally, if the types are
1435 // incompatible then make sure to use 'id' as the composite
1436 // type so the result is acceptable for sending messages to.
1437
1438 // FIXME: This code should not be localized to here. Also this
1439 // should use a compatible check instead of abusing the
1440 // canAssignObjCInterfaces code.
1441 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1442 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1443 if (LHSIface && RHSIface &&
1444 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1445 compositeType = lexT;
1446 } else if (LHSIface && RHSIface &&
1447 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1448 compositeType = rexT;
1449 } else if (Context.isObjCIdType(lhptee) ||
1450 Context.isObjCIdType(rhptee)) {
1451 // FIXME: This code looks wrong, because isObjCIdType checks
1452 // the struct but getObjCIdType returns the pointer to
1453 // struct. This is horrible and should be fixed.
1454 compositeType = Context.getObjCIdType();
1455 } else {
1456 QualType incompatTy = Context.getObjCIdType();
1457 ImpCastExprToType(lex, incompatTy);
1458 ImpCastExprToType(rex, incompatTy);
1459 return incompatTy;
1460 }
1461 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1462 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001463 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001464 lexT.getAsString(), rexT.getAsString(),
1465 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001466 // In this situation, we assume void* type. No especially good
1467 // reason, but this is what gcc does, and we do have to pick
1468 // to get a consistent AST.
1469 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001470 ImpCastExprToType(lex, incompatTy);
1471 ImpCastExprToType(rex, incompatTy);
1472 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001473 }
1474 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001475 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1476 // differently qualified versions of compatible types, the result type is
1477 // a pointer to an appropriately qualified version of the *composite*
1478 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001479 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001480 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001481 ImpCastExprToType(lex, compositeType);
1482 ImpCastExprToType(rex, compositeType);
1483 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001484 }
Chris Lattner4b009652007-07-25 00:24:17 +00001485 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001486 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1487 // evaluates to "struct objc_object *" (and is handled above when comparing
1488 // id with statically typed objects).
1489 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1490 // GCC allows qualified id and any Objective-C type to devolve to
1491 // id. Currently localizing to here until clear this should be
1492 // part of ObjCQualifiedIdTypesAreCompatible.
1493 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1494 (lexT->isObjCQualifiedIdType() &&
1495 Context.isObjCObjectPointerType(rexT)) ||
1496 (rexT->isObjCQualifiedIdType() &&
1497 Context.isObjCObjectPointerType(lexT))) {
1498 // FIXME: This is not the correct composite type. This only
1499 // happens to work because id can more or less be used anywhere,
1500 // however this may change the type of method sends.
1501 // FIXME: gcc adds some type-checking of the arguments and emits
1502 // (confusing) incompatible comparison warnings in some
1503 // cases. Investigate.
1504 QualType compositeType = Context.getObjCIdType();
1505 ImpCastExprToType(lex, compositeType);
1506 ImpCastExprToType(rex, compositeType);
1507 return compositeType;
1508 }
1509 }
1510
Steve Naroff3eac7692008-09-10 19:17:48 +00001511 // Selection between block pointer types is ok as long as they are the same.
1512 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1513 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1514 return lexT;
1515
Chris Lattner992ae932008-01-06 22:42:25 +00001516 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001517 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1518 lexT.getAsString(), rexT.getAsString(),
1519 lex->getSourceRange(), rex->getSourceRange());
1520 return QualType();
1521}
1522
Steve Naroff87d58b42007-09-16 03:34:24 +00001523/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001524/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001525Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001526 SourceLocation ColonLoc,
1527 ExprTy *Cond, ExprTy *LHS,
1528 ExprTy *RHS) {
1529 Expr *CondExpr = (Expr *) Cond;
1530 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001531
1532 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1533 // was the condition.
1534 bool isLHSNull = LHSExpr == 0;
1535 if (isLHSNull)
1536 LHSExpr = CondExpr;
1537
Chris Lattner4b009652007-07-25 00:24:17 +00001538 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1539 RHSExpr, QuestionLoc);
1540 if (result.isNull())
1541 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001542 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1543 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001544}
1545
Chris Lattner4b009652007-07-25 00:24:17 +00001546
1547// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1548// being closely modeled after the C99 spec:-). The odd characteristic of this
1549// routine is it effectively iqnores the qualifiers on the top level pointee.
1550// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1551// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001552Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001553Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1554 QualType lhptee, rhptee;
1555
1556 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001557 lhptee = lhsType->getAsPointerType()->getPointeeType();
1558 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001559
1560 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001561 lhptee = Context.getCanonicalType(lhptee);
1562 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001563
Chris Lattner005ed752008-01-04 18:04:52 +00001564 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001565
1566 // C99 6.5.16.1p1: This following citation is common to constraints
1567 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1568 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001569 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001570 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001571 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001572
1573 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1574 // incomplete type and the other is a pointer to a qualified or unqualified
1575 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001576 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001577 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001578 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001579
1580 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001581 assert(rhptee->isFunctionType());
1582 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001583 }
1584
1585 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001586 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001587 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001588
1589 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001590 assert(lhptee->isFunctionType());
1591 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001592 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001593
1594 // Check for ObjC interfaces
1595 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1596 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1597 if (LHSIface && RHSIface &&
1598 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1599 return ConvTy;
1600
1601 // ID acts sort of like void* for ObjC interfaces
1602 if (LHSIface && Context.isObjCIdType(rhptee))
1603 return ConvTy;
1604 if (RHSIface && Context.isObjCIdType(lhptee))
1605 return ConvTy;
1606
Chris Lattner4b009652007-07-25 00:24:17 +00001607 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1608 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001609 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1610 rhptee.getUnqualifiedType()))
1611 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001612 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001613}
1614
Steve Naroff3454b6c2008-09-04 15:10:53 +00001615/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1616/// block pointer types are compatible or whether a block and normal pointer
1617/// are compatible. It is more restrict than comparing two function pointer
1618// types.
1619Sema::AssignConvertType
1620Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1621 QualType rhsType) {
1622 QualType lhptee, rhptee;
1623
1624 // get the "pointed to" type (ignoring qualifiers at the top level)
1625 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1626 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1627
1628 // make sure we operate on the canonical type
1629 lhptee = Context.getCanonicalType(lhptee);
1630 rhptee = Context.getCanonicalType(rhptee);
1631
1632 AssignConvertType ConvTy = Compatible;
1633
1634 // For blocks we enforce that qualifiers are identical.
1635 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1636 ConvTy = CompatiblePointerDiscardsQualifiers;
1637
1638 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1639 return IncompatibleBlockPointer;
1640 return ConvTy;
1641}
1642
Chris Lattner4b009652007-07-25 00:24:17 +00001643/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1644/// has code to accommodate several GCC extensions when type checking
1645/// pointers. Here are some objectionable examples that GCC considers warnings:
1646///
1647/// int a, *pint;
1648/// short *pshort;
1649/// struct foo *pfoo;
1650///
1651/// pint = pshort; // warning: assignment from incompatible pointer type
1652/// a = pint; // warning: assignment makes integer from pointer without a cast
1653/// pint = a; // warning: assignment makes pointer from integer without a cast
1654/// pint = pfoo; // warning: assignment from incompatible pointer type
1655///
1656/// As a result, the code for dealing with pointers is more complex than the
1657/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001658///
Chris Lattner005ed752008-01-04 18:04:52 +00001659Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001660Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001661 // Get canonical types. We're not formatting these types, just comparing
1662 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001663 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1664 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001665
1666 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001667 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001668
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001669 // If the left-hand side is a reference type, then we are in a
1670 // (rare!) case where we've allowed the use of references in C,
1671 // e.g., as a parameter type in a built-in function. In this case,
1672 // just make sure that the type referenced is compatible with the
1673 // right-hand side type. The caller is responsible for adjusting
1674 // lhsType so that the resulting expression does not have reference
1675 // type.
1676 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1677 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001678 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001679 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001680 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001681
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001682 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1683 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001684 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001685 // Relax integer conversions like we do for pointers below.
1686 if (rhsType->isIntegerType())
1687 return IntToPointer;
1688 if (lhsType->isIntegerType())
1689 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001690 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001691 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001692
Nate Begemanc5f0f652008-07-14 18:02:46 +00001693 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001694 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001695 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1696 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001697 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001698
Nate Begemanc5f0f652008-07-14 18:02:46 +00001699 // If we are allowing lax vector conversions, and LHS and RHS are both
1700 // vectors, the total size only needs to be the same. This is a bitcast;
1701 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001702 if (getLangOptions().LaxVectorConversions &&
1703 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001704 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1705 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001706 }
1707 return Incompatible;
1708 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001709
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001710 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001711 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001712
Chris Lattner390564e2008-04-07 06:49:41 +00001713 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001714 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001715 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001716
Chris Lattner390564e2008-04-07 06:49:41 +00001717 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001718 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001719
Steve Naroffa982c712008-09-29 18:10:17 +00001720 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001721 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001722 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001723
1724 // Treat block pointers as objects.
1725 if (getLangOptions().ObjC1 &&
1726 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1727 return Compatible;
1728 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001729 return Incompatible;
1730 }
1731
1732 if (isa<BlockPointerType>(lhsType)) {
1733 if (rhsType->isIntegerType())
1734 return IntToPointer;
1735
Steve Naroffa982c712008-09-29 18:10:17 +00001736 // Treat block pointers as objects.
1737 if (getLangOptions().ObjC1 &&
1738 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1739 return Compatible;
1740
Steve Naroff3454b6c2008-09-04 15:10:53 +00001741 if (rhsType->isBlockPointerType())
1742 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1743
1744 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1745 if (RHSPT->getPointeeType()->isVoidType())
1746 return BlockVoidPointer;
1747 }
Chris Lattner1853da22008-01-04 23:18:45 +00001748 return Incompatible;
1749 }
1750
Chris Lattner390564e2008-04-07 06:49:41 +00001751 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001752 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001753 if (lhsType == Context.BoolTy)
1754 return Compatible;
1755
1756 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001757 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001758
Chris Lattner390564e2008-04-07 06:49:41 +00001759 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001760 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001761
1762 if (isa<BlockPointerType>(lhsType) &&
1763 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1764 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001765 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001766 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001767
Chris Lattner1853da22008-01-04 23:18:45 +00001768 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001769 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001770 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001771 }
1772 return Incompatible;
1773}
1774
Chris Lattner005ed752008-01-04 18:04:52 +00001775Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001776Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001777 if (getLangOptions().CPlusPlus) {
1778 if (!lhsType->isRecordType()) {
1779 // C++ 5.17p3: If the left operand is not of class type, the
1780 // expression is implicitly converted (C++ 4) to the
1781 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00001782 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001783 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00001784 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001785 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001786 }
1787
1788 // FIXME: Currently, we fall through and treat C++ classes like C
1789 // structures.
1790 }
1791
Steve Naroffcdee22d2007-11-27 17:58:44 +00001792 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1793 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001794 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1795 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001796 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001797 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001798 return Compatible;
1799 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001800
1801 // We don't allow conversion of non-null-pointer constants to integers.
1802 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1803 return IntToBlockPointer;
1804
Chris Lattner5f505bf2007-10-16 02:55:40 +00001805 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001806 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001807 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001808 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001809 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001810 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00001811 if (!lhsType->isReferenceType())
1812 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001813
Chris Lattner005ed752008-01-04 18:04:52 +00001814 Sema::AssignConvertType result =
1815 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001816
1817 // C99 6.5.16.1p2: The value of the right operand is converted to the
1818 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001819 // CheckAssignmentConstraints allows the left-hand side to be a reference,
1820 // so that we can use references in built-in functions even in C.
1821 // The getNonReferenceType() call makes sure that the resulting expression
1822 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00001823 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001824 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001825 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001826}
1827
Chris Lattner005ed752008-01-04 18:04:52 +00001828Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001829Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1830 return CheckAssignmentConstraints(lhsType, rhsType);
1831}
1832
Chris Lattner2c8bff72007-12-12 05:47:28 +00001833QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001834 Diag(loc, diag::err_typecheck_invalid_operands,
1835 lex->getType().getAsString(), rex->getType().getAsString(),
1836 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001837 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001838}
1839
1840inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1841 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001842 // For conversion purposes, we ignore any qualifiers.
1843 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001844 QualType lhsType =
1845 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1846 QualType rhsType =
1847 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001848
Nate Begemanc5f0f652008-07-14 18:02:46 +00001849 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001850 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001851 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001852
Nate Begemanc5f0f652008-07-14 18:02:46 +00001853 // Handle the case of a vector & extvector type of the same size and element
1854 // type. It would be nice if we only had one vector type someday.
1855 if (getLangOptions().LaxVectorConversions)
1856 if (const VectorType *LV = lhsType->getAsVectorType())
1857 if (const VectorType *RV = rhsType->getAsVectorType())
1858 if (LV->getElementType() == RV->getElementType() &&
1859 LV->getNumElements() == RV->getNumElements())
1860 return lhsType->isExtVectorType() ? lhsType : rhsType;
1861
1862 // If the lhs is an extended vector and the rhs is a scalar of the same type
1863 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001864 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001865 QualType eltType = V->getElementType();
1866
1867 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1868 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1869 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001870 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001871 return lhsType;
1872 }
1873 }
1874
Nate Begemanc5f0f652008-07-14 18:02:46 +00001875 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001876 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001877 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001878 QualType eltType = V->getElementType();
1879
1880 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1881 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1882 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001883 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001884 return rhsType;
1885 }
1886 }
1887
Chris Lattner4b009652007-07-25 00:24:17 +00001888 // You cannot convert between vector values of different size.
1889 Diag(loc, diag::err_typecheck_vector_not_convertable,
1890 lex->getType().getAsString(), rex->getType().getAsString(),
1891 lex->getSourceRange(), rex->getSourceRange());
1892 return QualType();
1893}
1894
1895inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001896 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001897{
1898 QualType lhsType = lex->getType(), rhsType = rex->getType();
1899
1900 if (lhsType->isVectorType() || rhsType->isVectorType())
1901 return CheckVectorOperands(loc, lex, rex);
1902
Steve Naroff8f708362007-08-24 19:07:16 +00001903 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001904
Chris Lattner4b009652007-07-25 00:24:17 +00001905 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001906 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001907 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001908}
1909
1910inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001911 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001912{
1913 QualType lhsType = lex->getType(), rhsType = rex->getType();
1914
Steve Naroff8f708362007-08-24 19:07:16 +00001915 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001916
Chris Lattner4b009652007-07-25 00:24:17 +00001917 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001918 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001919 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001920}
1921
1922inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001923 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001924{
1925 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1926 return CheckVectorOperands(loc, lex, rex);
1927
Steve Naroff8f708362007-08-24 19:07:16 +00001928 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001929
Chris Lattner4b009652007-07-25 00:24:17 +00001930 // handle the common case first (both operands are arithmetic).
1931 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001932 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001933
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001934 // Put any potential pointer into PExp
1935 Expr* PExp = lex, *IExp = rex;
1936 if (IExp->getType()->isPointerType())
1937 std::swap(PExp, IExp);
1938
1939 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1940 if (IExp->getType()->isIntegerType()) {
1941 // Check for arithmetic on pointers to incomplete types
1942 if (!PTy->getPointeeType()->isObjectType()) {
1943 if (PTy->getPointeeType()->isVoidType()) {
1944 Diag(loc, diag::ext_gnu_void_ptr,
1945 lex->getSourceRange(), rex->getSourceRange());
1946 } else {
1947 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1948 lex->getType().getAsString(), lex->getSourceRange());
1949 return QualType();
1950 }
1951 }
1952 return PExp->getType();
1953 }
1954 }
1955
Chris Lattner2c8bff72007-12-12 05:47:28 +00001956 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001957}
1958
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001959// C99 6.5.6
1960QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1961 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001962 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1963 return CheckVectorOperands(loc, lex, rex);
1964
Steve Naroff8f708362007-08-24 19:07:16 +00001965 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001966
Chris Lattnerf6da2912007-12-09 21:53:25 +00001967 // Enforce type constraints: C99 6.5.6p3.
1968
1969 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001970 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001971 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001972
1973 // Either ptr - int or ptr - ptr.
1974 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001975 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001976
Chris Lattnerf6da2912007-12-09 21:53:25 +00001977 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001978 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001979 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001980 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001981 Diag(loc, diag::ext_gnu_void_ptr,
1982 lex->getSourceRange(), rex->getSourceRange());
1983 } else {
1984 Diag(loc, diag::err_typecheck_sub_ptr_object,
1985 lex->getType().getAsString(), lex->getSourceRange());
1986 return QualType();
1987 }
1988 }
1989
1990 // The result type of a pointer-int computation is the pointer type.
1991 if (rex->getType()->isIntegerType())
1992 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001993
Chris Lattnerf6da2912007-12-09 21:53:25 +00001994 // Handle pointer-pointer subtractions.
1995 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001996 QualType rpointee = RHSPTy->getPointeeType();
1997
Chris Lattnerf6da2912007-12-09 21:53:25 +00001998 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001999 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002000 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002001 if (rpointee->isVoidType()) {
2002 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00002003 Diag(loc, diag::ext_gnu_void_ptr,
2004 lex->getSourceRange(), rex->getSourceRange());
2005 } else {
2006 Diag(loc, diag::err_typecheck_sub_ptr_object,
2007 rex->getType().getAsString(), rex->getSourceRange());
2008 return QualType();
2009 }
2010 }
2011
2012 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002013 if (!Context.typesAreCompatible(
2014 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2015 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002016 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2017 lex->getType().getAsString(), rex->getType().getAsString(),
2018 lex->getSourceRange(), rex->getSourceRange());
2019 return QualType();
2020 }
2021
2022 return Context.getPointerDiffType();
2023 }
2024 }
2025
Chris Lattner2c8bff72007-12-12 05:47:28 +00002026 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002027}
2028
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002029// C99 6.5.7
2030QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2031 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002032 // C99 6.5.7p2: Each of the operands shall have integer type.
2033 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2034 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002035
Chris Lattner2c8bff72007-12-12 05:47:28 +00002036 // Shifts don't perform usual arithmetic conversions, they just do integer
2037 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002038 if (!isCompAssign)
2039 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002040 UsualUnaryConversions(rex);
2041
2042 // "The type of the result is that of the promoted left operand."
2043 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002044}
2045
Eli Friedman0d9549b2008-08-22 00:56:42 +00002046static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2047 ASTContext& Context) {
2048 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2049 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2050 // ID acts sort of like void* for ObjC interfaces
2051 if (LHSIface && Context.isObjCIdType(RHS))
2052 return true;
2053 if (RHSIface && Context.isObjCIdType(LHS))
2054 return true;
2055 if (!LHSIface || !RHSIface)
2056 return false;
2057 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2058 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2059}
2060
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002061// C99 6.5.8
2062QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2063 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002064 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2065 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2066
Chris Lattner254f3bc2007-08-26 01:18:55 +00002067 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002068 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2069 UsualArithmeticConversions(lex, rex);
2070 else {
2071 UsualUnaryConversions(lex);
2072 UsualUnaryConversions(rex);
2073 }
Chris Lattner4b009652007-07-25 00:24:17 +00002074 QualType lType = lex->getType();
2075 QualType rType = rex->getType();
2076
Ted Kremenek486509e2007-10-29 17:13:39 +00002077 // For non-floating point types, check for self-comparisons of the form
2078 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2079 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002080 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002081 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2082 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002083 if (DRL->getDecl() == DRR->getDecl())
2084 Diag(loc, diag::warn_selfcomparison);
2085 }
2086
Chris Lattner254f3bc2007-08-26 01:18:55 +00002087 if (isRelational) {
2088 if (lType->isRealType() && rType->isRealType())
2089 return Context.IntTy;
2090 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002091 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002092 if (lType->isFloatingType()) {
2093 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00002094 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002095 }
2096
Chris Lattner254f3bc2007-08-26 01:18:55 +00002097 if (lType->isArithmeticType() && rType->isArithmeticType())
2098 return Context.IntTy;
2099 }
Chris Lattner4b009652007-07-25 00:24:17 +00002100
Chris Lattner22be8422007-08-26 01:10:14 +00002101 bool LHSIsNull = lex->isNullPointerConstant(Context);
2102 bool RHSIsNull = rex->isNullPointerConstant(Context);
2103
Chris Lattner254f3bc2007-08-26 01:18:55 +00002104 // All of the following pointer related warnings are GCC extensions, except
2105 // when handling null pointer constants. One day, we can consider making them
2106 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002107 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002108 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002109 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002110 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002111 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002112
Steve Naroff3b435622007-11-13 14:57:38 +00002113 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002114 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2115 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002116 RCanPointeeTy.getUnqualifiedType()) &&
2117 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002118 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2119 lType.getAsString(), rType.getAsString(),
2120 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002121 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002122 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002123 return Context.IntTy;
2124 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002125 // Handle block pointer types.
2126 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2127 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2128 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2129
2130 if (!LHSIsNull && !RHSIsNull &&
2131 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2132 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2133 lType.getAsString(), rType.getAsString(),
2134 lex->getSourceRange(), rex->getSourceRange());
2135 }
2136 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2137 return Context.IntTy;
2138 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002139 // Allow block pointers to be compared with null pointer constants.
2140 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2141 (lType->isPointerType() && rType->isBlockPointerType())) {
2142 if (!LHSIsNull && !RHSIsNull) {
2143 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2144 lType.getAsString(), rType.getAsString(),
2145 lex->getSourceRange(), rex->getSourceRange());
2146 }
2147 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2148 return Context.IntTy;
2149 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002150
Steve Naroff936c4362008-06-03 14:04:54 +00002151 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002152 if (lType->isPointerType() || rType->isPointerType()) {
2153 if (!Context.typesAreCompatible(lType, rType)) {
2154 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2155 lType.getAsString(), rType.getAsString(),
2156 lex->getSourceRange(), rex->getSourceRange());
2157 ImpCastExprToType(rex, lType);
2158 return Context.IntTy;
2159 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002160 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002161 return Context.IntTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002162 }
Steve Naroff936c4362008-06-03 14:04:54 +00002163 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2164 ImpCastExprToType(rex, lType);
2165 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002166 } else {
2167 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2168 Diag(loc, diag::warn_incompatible_qualified_id_operands,
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002169 lType.getAsString(), rType.getAsString(),
Steve Naroff19608432008-10-14 22:18:38 +00002170 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002171 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002172 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002173 }
Steve Naroff936c4362008-06-03 14:04:54 +00002174 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002175 }
Steve Naroff936c4362008-06-03 14:04:54 +00002176 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2177 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002178 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002179 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2180 lType.getAsString(), rType.getAsString(),
2181 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002182 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002183 return Context.IntTy;
2184 }
Steve Naroff936c4362008-06-03 14:04:54 +00002185 if (lType->isIntegerType() &&
2186 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002187 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002188 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2189 lType.getAsString(), rType.getAsString(),
2190 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002191 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002192 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002193 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002194 // Handle block pointers.
2195 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2196 if (!RHSIsNull)
2197 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2198 lType.getAsString(), rType.getAsString(),
2199 lex->getSourceRange(), rex->getSourceRange());
2200 ImpCastExprToType(rex, lType); // promote the integer to pointer
2201 return Context.IntTy;
2202 }
2203 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2204 if (!LHSIsNull)
2205 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2206 lType.getAsString(), rType.getAsString(),
2207 lex->getSourceRange(), rex->getSourceRange());
2208 ImpCastExprToType(lex, rType); // promote the integer to pointer
2209 return Context.IntTy;
2210 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002211 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002212}
2213
Nate Begemanc5f0f652008-07-14 18:02:46 +00002214/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2215/// operates on extended vector types. Instead of producing an IntTy result,
2216/// like a scalar comparison, a vector comparison produces a vector of integer
2217/// types.
2218QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2219 SourceLocation loc,
2220 bool isRelational) {
2221 // Check to make sure we're operating on vectors of the same type and width,
2222 // Allowing one side to be a scalar of element type.
2223 QualType vType = CheckVectorOperands(loc, lex, rex);
2224 if (vType.isNull())
2225 return vType;
2226
2227 QualType lType = lex->getType();
2228 QualType rType = rex->getType();
2229
2230 // For non-floating point types, check for self-comparisons of the form
2231 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2232 // often indicate logic errors in the program.
2233 if (!lType->isFloatingType()) {
2234 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2235 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2236 if (DRL->getDecl() == DRR->getDecl())
2237 Diag(loc, diag::warn_selfcomparison);
2238 }
2239
2240 // Check for comparisons of floating point operands using != and ==.
2241 if (!isRelational && lType->isFloatingType()) {
2242 assert (rType->isFloatingType());
2243 CheckFloatComparison(loc,lex,rex);
2244 }
2245
2246 // Return the type for the comparison, which is the same as vector type for
2247 // integer vectors, or an integer type of identical size and number of
2248 // elements for floating point vectors.
2249 if (lType->isIntegerType())
2250 return lType;
2251
2252 const VectorType *VTy = lType->getAsVectorType();
2253
2254 // FIXME: need to deal with non-32b int / non-64b long long
2255 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2256 if (TypeSize == 32) {
2257 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2258 }
2259 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2260 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2261}
2262
Chris Lattner4b009652007-07-25 00:24:17 +00002263inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002264 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002265{
2266 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2267 return CheckVectorOperands(loc, lex, rex);
2268
Steve Naroff8f708362007-08-24 19:07:16 +00002269 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002270
2271 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002272 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002273 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002274}
2275
2276inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2277 Expr *&lex, Expr *&rex, SourceLocation loc)
2278{
2279 UsualUnaryConversions(lex);
2280 UsualUnaryConversions(rex);
2281
Eli Friedmanbea3f842008-05-13 20:16:47 +00002282 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002283 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002284 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002285}
2286
2287inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002288 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002289{
2290 QualType lhsType = lex->getType();
2291 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002292 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002293
2294 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002295 case Expr::MLV_Valid:
2296 break;
2297 case Expr::MLV_ConstQualified:
2298 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2299 return QualType();
2300 case Expr::MLV_ArrayType:
2301 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2302 lhsType.getAsString(), lex->getSourceRange());
2303 return QualType();
2304 case Expr::MLV_NotObjectType:
2305 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2306 lhsType.getAsString(), lex->getSourceRange());
2307 return QualType();
2308 case Expr::MLV_InvalidExpression:
2309 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2310 lex->getSourceRange());
2311 return QualType();
2312 case Expr::MLV_IncompleteType:
2313 case Expr::MLV_IncompleteVoidType:
2314 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2315 lhsType.getAsString(), lex->getSourceRange());
2316 return QualType();
2317 case Expr::MLV_DuplicateVectorComponents:
2318 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2319 lex->getSourceRange());
2320 return QualType();
Steve Naroff076d6cb2008-09-26 14:41:28 +00002321 case Expr::MLV_NotBlockQualified:
2322 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2323 lex->getSourceRange());
2324 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002325 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002326
Chris Lattner005ed752008-01-04 18:04:52 +00002327 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002328 if (compoundType.isNull()) {
2329 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002330 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002331
2332 // If the RHS is a unary plus or minus, check to see if they = and + are
2333 // right next to each other. If so, the user may have typo'd "x =+ 4"
2334 // instead of "x += 4".
2335 Expr *RHSCheck = rex;
2336 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2337 RHSCheck = ICE->getSubExpr();
2338 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2339 if ((UO->getOpcode() == UnaryOperator::Plus ||
2340 UO->getOpcode() == UnaryOperator::Minus) &&
2341 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2342 // Only if the two operators are exactly adjacent.
2343 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2344 Diag(loc, diag::warn_not_compound_assign,
2345 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2346 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2347 }
2348 } else {
2349 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002350 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002351 }
Chris Lattner005ed752008-01-04 18:04:52 +00002352
2353 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2354 rex, "assigning"))
2355 return QualType();
2356
Chris Lattner4b009652007-07-25 00:24:17 +00002357 // C99 6.5.16p3: The type of an assignment expression is the type of the
2358 // left operand unless the left operand has qualified type, in which case
2359 // it is the unqualified version of the type of the left operand.
2360 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2361 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002362 // C++ 5.17p1: the type of the assignment expression is that of its left
2363 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002364 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002365}
2366
2367inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2368 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002369
2370 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2371 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002372 return rex->getType();
2373}
2374
2375/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2376/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2377QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2378 QualType resType = op->getType();
2379 assert(!resType.isNull() && "no type for increment/decrement expression");
2380
Steve Naroffd30e1932007-08-24 17:20:07 +00002381 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002382 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002383 if (pt->getPointeeType()->isVoidType()) {
2384 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2385 } else if (!pt->getPointeeType()->isObjectType()) {
2386 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002387 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2388 resType.getAsString(), op->getSourceRange());
2389 return QualType();
2390 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002391 } else if (!resType->isRealType()) {
2392 if (resType->isComplexType())
2393 // C99 does not support ++/-- on complex types.
2394 Diag(OpLoc, diag::ext_integer_increment_complex,
2395 resType.getAsString(), op->getSourceRange());
2396 else {
2397 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2398 resType.getAsString(), op->getSourceRange());
2399 return QualType();
2400 }
Chris Lattner4b009652007-07-25 00:24:17 +00002401 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002402 // At this point, we know we have a real, complex or pointer type.
2403 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002404 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002405 if (mlval != Expr::MLV_Valid) {
2406 // FIXME: emit a more precise diagnostic...
2407 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2408 op->getSourceRange());
2409 return QualType();
2410 }
2411 return resType;
2412}
2413
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002414/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002415/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002416/// where the declaration is needed for type checking. We only need to
2417/// handle cases when the expression references a function designator
2418/// or is an lvalue. Here are some examples:
2419/// - &(x) => x
2420/// - &*****f => f for f a function designator.
2421/// - &s.xx => s
2422/// - &s.zz[1].yy -> s, if zz is an array
2423/// - *(x + 1) -> x, if x is an array
2424/// - &"123"[2] -> 0
2425/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002426static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002427 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002428 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002429 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002430 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002431 // Fields cannot be declared with a 'register' storage class.
2432 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002433 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002434 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002435 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002436 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002437 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002438
Douglas Gregord2baafd2008-10-21 16:13:35 +00002439 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002440 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002441 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002442 return 0;
2443 else
2444 return VD;
2445 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002446 case Stmt::UnaryOperatorClass: {
2447 UnaryOperator *UO = cast<UnaryOperator>(E);
2448
2449 switch(UO->getOpcode()) {
2450 case UnaryOperator::Deref: {
2451 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002452 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2453 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2454 if (!VD || VD->getType()->isPointerType())
2455 return 0;
2456 return VD;
2457 }
2458 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002459 }
2460 case UnaryOperator::Real:
2461 case UnaryOperator::Imag:
2462 case UnaryOperator::Extension:
2463 return getPrimaryDecl(UO->getSubExpr());
2464 default:
2465 return 0;
2466 }
2467 }
2468 case Stmt::BinaryOperatorClass: {
2469 BinaryOperator *BO = cast<BinaryOperator>(E);
2470
2471 // Handle cases involving pointer arithmetic. The result of an
2472 // Assign or AddAssign is not an lvalue so they can be ignored.
2473
2474 // (x + n) or (n + x) => x
2475 if (BO->getOpcode() == BinaryOperator::Add) {
2476 if (BO->getLHS()->getType()->isPointerType()) {
2477 return getPrimaryDecl(BO->getLHS());
2478 } else if (BO->getRHS()->getType()->isPointerType()) {
2479 return getPrimaryDecl(BO->getRHS());
2480 }
2481 }
2482
2483 return 0;
2484 }
Chris Lattner4b009652007-07-25 00:24:17 +00002485 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002486 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002487 case Stmt::ImplicitCastExprClass:
2488 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002489 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002490 default:
2491 return 0;
2492 }
2493}
2494
2495/// CheckAddressOfOperand - The operand of & must be either a function
2496/// designator or an lvalue designating an object. If it is an lvalue, the
2497/// object cannot be declared with storage class register or be a bit field.
2498/// Note: The usual conversions are *not* applied to the operand of the &
2499/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2500QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002501 if (getLangOptions().C99) {
2502 // Implement C99-only parts of addressof rules.
2503 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2504 if (uOp->getOpcode() == UnaryOperator::Deref)
2505 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2506 // (assuming the deref expression is valid).
2507 return uOp->getSubExpr()->getType();
2508 }
2509 // Technically, there should be a check for array subscript
2510 // expressions here, but the result of one is always an lvalue anyway.
2511 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002512 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002513 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002514
2515 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002516 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2517 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002518 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2519 op->getSourceRange());
2520 return QualType();
2521 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002522 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2523 if (MemExpr->getMemberDecl()->isBitField()) {
2524 Diag(OpLoc, diag::err_typecheck_address_of,
2525 std::string("bit-field"), op->getSourceRange());
2526 return QualType();
2527 }
2528 // Check for Apple extension for accessing vector components.
2529 } else if (isa<ArraySubscriptExpr>(op) &&
2530 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2531 Diag(OpLoc, diag::err_typecheck_address_of,
2532 std::string("vector"), op->getSourceRange());
2533 return QualType();
2534 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002535 // We have an lvalue with a decl. Make sure the decl is not declared
2536 // with the register storage-class specifier.
2537 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2538 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002539 Diag(OpLoc, diag::err_typecheck_address_of,
2540 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002541 return QualType();
2542 }
2543 } else
2544 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002545 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002546
Chris Lattner4b009652007-07-25 00:24:17 +00002547 // If the operand has type "type", the result has type "pointer to type".
2548 return Context.getPointerType(op->getType());
2549}
2550
2551QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2552 UsualUnaryConversions(op);
2553 QualType qType = op->getType();
2554
Chris Lattner7931f4a2007-07-31 16:53:04 +00002555 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002556 // Note that per both C89 and C99, this is always legal, even
2557 // if ptype is an incomplete type or void.
2558 // It would be possible to warn about dereferencing a
2559 // void pointer, but it's completely well-defined,
2560 // and such a warning is unlikely to catch any mistakes.
2561 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002562 }
2563 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2564 qType.getAsString(), op->getSourceRange());
2565 return QualType();
2566}
2567
2568static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2569 tok::TokenKind Kind) {
2570 BinaryOperator::Opcode Opc;
2571 switch (Kind) {
2572 default: assert(0 && "Unknown binop!");
2573 case tok::star: Opc = BinaryOperator::Mul; break;
2574 case tok::slash: Opc = BinaryOperator::Div; break;
2575 case tok::percent: Opc = BinaryOperator::Rem; break;
2576 case tok::plus: Opc = BinaryOperator::Add; break;
2577 case tok::minus: Opc = BinaryOperator::Sub; break;
2578 case tok::lessless: Opc = BinaryOperator::Shl; break;
2579 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2580 case tok::lessequal: Opc = BinaryOperator::LE; break;
2581 case tok::less: Opc = BinaryOperator::LT; break;
2582 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2583 case tok::greater: Opc = BinaryOperator::GT; break;
2584 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2585 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2586 case tok::amp: Opc = BinaryOperator::And; break;
2587 case tok::caret: Opc = BinaryOperator::Xor; break;
2588 case tok::pipe: Opc = BinaryOperator::Or; break;
2589 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2590 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2591 case tok::equal: Opc = BinaryOperator::Assign; break;
2592 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2593 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2594 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2595 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2596 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2597 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2598 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2599 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2600 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2601 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2602 case tok::comma: Opc = BinaryOperator::Comma; break;
2603 }
2604 return Opc;
2605}
2606
2607static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2608 tok::TokenKind Kind) {
2609 UnaryOperator::Opcode Opc;
2610 switch (Kind) {
2611 default: assert(0 && "Unknown unary op!");
2612 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2613 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2614 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2615 case tok::star: Opc = UnaryOperator::Deref; break;
2616 case tok::plus: Opc = UnaryOperator::Plus; break;
2617 case tok::minus: Opc = UnaryOperator::Minus; break;
2618 case tok::tilde: Opc = UnaryOperator::Not; break;
2619 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2620 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2621 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2622 case tok::kw___real: Opc = UnaryOperator::Real; break;
2623 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2624 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2625 }
2626 return Opc;
2627}
2628
Douglas Gregord7f915e2008-11-06 23:29:22 +00002629/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2630/// operator @p Opc at location @c TokLoc. This routine only supports
2631/// built-in operations; ActOnBinOp handles overloaded operators.
2632Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2633 unsigned Op,
2634 Expr *lhs, Expr *rhs) {
2635 QualType ResultTy; // Result type of the binary operator.
2636 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2637 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2638
2639 switch (Opc) {
2640 default:
2641 assert(0 && "Unknown binary expr!");
2642 case BinaryOperator::Assign:
2643 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2644 break;
2645 case BinaryOperator::Mul:
2646 case BinaryOperator::Div:
2647 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2648 break;
2649 case BinaryOperator::Rem:
2650 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2651 break;
2652 case BinaryOperator::Add:
2653 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2654 break;
2655 case BinaryOperator::Sub:
2656 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2657 break;
2658 case BinaryOperator::Shl:
2659 case BinaryOperator::Shr:
2660 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2661 break;
2662 case BinaryOperator::LE:
2663 case BinaryOperator::LT:
2664 case BinaryOperator::GE:
2665 case BinaryOperator::GT:
2666 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2667 break;
2668 case BinaryOperator::EQ:
2669 case BinaryOperator::NE:
2670 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2671 break;
2672 case BinaryOperator::And:
2673 case BinaryOperator::Xor:
2674 case BinaryOperator::Or:
2675 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2676 break;
2677 case BinaryOperator::LAnd:
2678 case BinaryOperator::LOr:
2679 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2680 break;
2681 case BinaryOperator::MulAssign:
2682 case BinaryOperator::DivAssign:
2683 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2684 if (!CompTy.isNull())
2685 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2686 break;
2687 case BinaryOperator::RemAssign:
2688 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2689 if (!CompTy.isNull())
2690 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2691 break;
2692 case BinaryOperator::AddAssign:
2693 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2694 if (!CompTy.isNull())
2695 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2696 break;
2697 case BinaryOperator::SubAssign:
2698 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2699 if (!CompTy.isNull())
2700 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2701 break;
2702 case BinaryOperator::ShlAssign:
2703 case BinaryOperator::ShrAssign:
2704 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2705 if (!CompTy.isNull())
2706 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2707 break;
2708 case BinaryOperator::AndAssign:
2709 case BinaryOperator::XorAssign:
2710 case BinaryOperator::OrAssign:
2711 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2712 if (!CompTy.isNull())
2713 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2714 break;
2715 case BinaryOperator::Comma:
2716 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2717 break;
2718 }
2719 if (ResultTy.isNull())
2720 return true;
2721 if (CompTy.isNull())
2722 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2723 else
2724 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2725}
2726
Chris Lattner4b009652007-07-25 00:24:17 +00002727// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002728Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2729 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002730 ExprTy *LHS, ExprTy *RHS) {
2731 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2732 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2733
Steve Naroff87d58b42007-09-16 03:34:24 +00002734 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2735 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002736
Douglas Gregord7f915e2008-11-06 23:29:22 +00002737 if (getLangOptions().CPlusPlus &&
2738 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2739 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
2740 // C++ [over.binary]p1:
2741 // A binary operator shall be implemented either by a non-static
2742 // member function (9.3) with one parameter or by a non-member
2743 // function with two parameters. Thus, for any binary operator
2744 // @, x@y can be interpreted as either x.operator@(y) or
2745 // operator@(x,y). If both forms of the operator function have
2746 // been declared, the rules in 13.3.1.2 determines which, if
2747 // any, interpretation is used.
2748 OverloadCandidateSet CandidateSet;
2749
2750 // Determine which overloaded operator we're dealing with.
2751 static const OverloadedOperatorKind OverOps[] = {
2752 OO_Star, OO_Slash, OO_Percent,
2753 OO_Plus, OO_Minus,
2754 OO_LessLess, OO_GreaterGreater,
2755 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2756 OO_EqualEqual, OO_ExclaimEqual,
2757 OO_Amp,
2758 OO_Caret,
2759 OO_Pipe,
2760 OO_AmpAmp,
2761 OO_PipePipe,
2762 OO_Equal, OO_StarEqual,
2763 OO_SlashEqual, OO_PercentEqual,
2764 OO_PlusEqual, OO_MinusEqual,
2765 OO_LessLessEqual, OO_GreaterGreaterEqual,
2766 OO_AmpEqual, OO_CaretEqual,
2767 OO_PipeEqual,
2768 OO_Comma
2769 };
2770 OverloadedOperatorKind OverOp = OverOps[Opc];
2771
2772 // Lookup this operator.
2773 Decl *D = LookupDecl(&PP.getIdentifierTable().getOverloadedOperator(OverOp),
2774 Decl::IDNS_Ordinary, S);
2775
2776 // Add any overloaded operators we find to the overload set.
2777 Expr *Args[2] = { lhs, rhs };
2778 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2779 AddOverloadCandidate(FD, Args, 2, CandidateSet);
2780 else if (OverloadedFunctionDecl *Ovl
2781 = dyn_cast_or_null<OverloadedFunctionDecl>(D))
2782 AddOverloadCandidates(Ovl, Args, 2, CandidateSet);
2783
2784 // FIXME: Add builtin overload candidates (C++ [over.built]).
2785
2786 // Perform overload resolution.
2787 OverloadCandidateSet::iterator Best;
2788 switch (BestViableFunction(CandidateSet, Best)) {
2789 case OR_Success: {
2790 // FIXME: We might find a built-in candidate here.
2791 FunctionDecl *FnDecl = Best->Function;
2792
2793 // Convert the arguments.
2794 // FIXME: Conversion will be different for member operators.
2795 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
2796 "passing") ||
2797 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
2798 "passing"))
2799 return true;
2800
2801 // Determine the result type
2802 QualType ResultTy
2803 = FnDecl->getType()->getAsFunctionType()->getResultType();
2804 ResultTy = ResultTy.getNonReferenceType();
2805
2806 // Build the actual expression node.
2807 // FIXME: We lose the fact that we have a function here!
2808 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
2809 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, ResultTy,
2810 TokLoc);
2811 else
2812 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
2813 }
2814
2815 case OR_No_Viable_Function:
2816 // No viable function; fall through to handling this as a
2817 // built-in operator.
2818 break;
2819
2820 case OR_Ambiguous:
2821 Diag(TokLoc,
2822 diag::err_ovl_ambiguous_oper,
2823 BinaryOperator::getOpcodeStr(Opc),
2824 lhs->getSourceRange(), rhs->getSourceRange());
2825 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2826 return true;
2827 }
2828
2829 // There was no viable overloaded operator; fall through.
2830 }
2831
Chris Lattner4b009652007-07-25 00:24:17 +00002832
Douglas Gregord7f915e2008-11-06 23:29:22 +00002833 // Build a built-in binary operation.
2834 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00002835}
2836
2837// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002838Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002839 ExprTy *input) {
2840 Expr *Input = (Expr*)input;
2841 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2842 QualType resultType;
2843 switch (Opc) {
2844 default:
2845 assert(0 && "Unimplemented unary expr!");
2846 case UnaryOperator::PreInc:
2847 case UnaryOperator::PreDec:
2848 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2849 break;
2850 case UnaryOperator::AddrOf:
2851 resultType = CheckAddressOfOperand(Input, OpLoc);
2852 break;
2853 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002854 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002855 resultType = CheckIndirectionOperand(Input, OpLoc);
2856 break;
2857 case UnaryOperator::Plus:
2858 case UnaryOperator::Minus:
2859 UsualUnaryConversions(Input);
2860 resultType = Input->getType();
2861 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2862 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2863 resultType.getAsString());
2864 break;
2865 case UnaryOperator::Not: // bitwise complement
2866 UsualUnaryConversions(Input);
2867 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002868 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2869 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2870 // C99 does not support '~' for complex conjugation.
2871 Diag(OpLoc, diag::ext_integer_complement_complex,
2872 resultType.getAsString(), Input->getSourceRange());
2873 else if (!resultType->isIntegerType())
2874 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2875 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002876 break;
2877 case UnaryOperator::LNot: // logical negation
2878 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2879 DefaultFunctionArrayConversion(Input);
2880 resultType = Input->getType();
2881 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2882 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2883 resultType.getAsString());
2884 // LNot always has type int. C99 6.5.3.3p5.
2885 resultType = Context.IntTy;
2886 break;
2887 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002888 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2889 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002890 break;
2891 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002892 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2893 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002894 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002895 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002896 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002897 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002898 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002899 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002900 resultType = Input->getType();
2901 break;
2902 }
2903 if (resultType.isNull())
2904 return true;
2905 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2906}
2907
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002908/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2909Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002910 SourceLocation LabLoc,
2911 IdentifierInfo *LabelII) {
2912 // Look up the record for this label identifier.
2913 LabelStmt *&LabelDecl = LabelMap[LabelII];
2914
Daniel Dunbar879788d2008-08-04 16:51:22 +00002915 // If we haven't seen this label yet, create a forward reference. It
2916 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002917 if (LabelDecl == 0)
2918 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2919
2920 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002921 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2922 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002923}
2924
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002925Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002926 SourceLocation RPLoc) { // "({..})"
2927 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2928 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2929 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2930
2931 // FIXME: there are a variety of strange constraints to enforce here, for
2932 // example, it is not possible to goto into a stmt expression apparently.
2933 // More semantic analysis is needed.
2934
2935 // FIXME: the last statement in the compount stmt has its value used. We
2936 // should not warn about it being unused.
2937
2938 // If there are sub stmts in the compound stmt, take the type of the last one
2939 // as the type of the stmtexpr.
2940 QualType Ty = Context.VoidTy;
2941
Chris Lattner200964f2008-07-26 19:51:01 +00002942 if (!Compound->body_empty()) {
2943 Stmt *LastStmt = Compound->body_back();
2944 // If LastStmt is a label, skip down through into the body.
2945 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2946 LastStmt = Label->getSubStmt();
2947
2948 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002949 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002950 }
Chris Lattner4b009652007-07-25 00:24:17 +00002951
2952 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2953}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002954
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002955Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002956 SourceLocation TypeLoc,
2957 TypeTy *argty,
2958 OffsetOfComponent *CompPtr,
2959 unsigned NumComponents,
2960 SourceLocation RPLoc) {
2961 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2962 assert(!ArgTy.isNull() && "Missing type argument!");
2963
2964 // We must have at least one component that refers to the type, and the first
2965 // one is known to be a field designator. Verify that the ArgTy represents
2966 // a struct/union/class.
2967 if (!ArgTy->isRecordType())
2968 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2969
2970 // Otherwise, create a compound literal expression as the base, and
2971 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002972 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002973
Chris Lattnerb37522e2007-08-31 21:49:13 +00002974 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2975 // GCC extension, diagnose them.
2976 if (NumComponents != 1)
2977 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2978 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2979
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002980 for (unsigned i = 0; i != NumComponents; ++i) {
2981 const OffsetOfComponent &OC = CompPtr[i];
2982 if (OC.isBrackets) {
2983 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002984 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002985 if (!AT) {
2986 delete Res;
2987 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2988 Res->getType().getAsString());
2989 }
2990
Chris Lattner2af6a802007-08-30 17:59:59 +00002991 // FIXME: C++: Verify that operator[] isn't overloaded.
2992
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002993 // C99 6.5.2.1p1
2994 Expr *Idx = static_cast<Expr*>(OC.U.E);
2995 if (!Idx->getType()->isIntegerType())
2996 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2997 Idx->getSourceRange());
2998
2999 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3000 continue;
3001 }
3002
3003 const RecordType *RC = Res->getType()->getAsRecordType();
3004 if (!RC) {
3005 delete Res;
3006 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
3007 Res->getType().getAsString());
3008 }
3009
3010 // Get the decl corresponding to this.
3011 RecordDecl *RD = RC->getDecl();
3012 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3013 if (!MemberDecl)
3014 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
3015 OC.U.IdentInfo->getName(),
3016 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00003017
3018 // FIXME: C++: Verify that MemberDecl isn't a static field.
3019 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003020 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3021 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003022 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3023 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003024 }
3025
3026 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3027 BuiltinLoc);
3028}
3029
3030
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003031Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003032 TypeTy *arg1, TypeTy *arg2,
3033 SourceLocation RPLoc) {
3034 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3035 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3036
3037 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3038
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003039 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003040}
3041
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003042Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003043 ExprTy *expr1, ExprTy *expr2,
3044 SourceLocation RPLoc) {
3045 Expr *CondExpr = static_cast<Expr*>(cond);
3046 Expr *LHSExpr = static_cast<Expr*>(expr1);
3047 Expr *RHSExpr = static_cast<Expr*>(expr2);
3048
3049 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3050
3051 // The conditional expression is required to be a constant expression.
3052 llvm::APSInt condEval(32);
3053 SourceLocation ExpLoc;
3054 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
3055 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
3056 CondExpr->getSourceRange());
3057
3058 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3059 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3060 RHSExpr->getType();
3061 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3062}
3063
Steve Naroff52a81c02008-09-03 18:15:37 +00003064//===----------------------------------------------------------------------===//
3065// Clang Extensions.
3066//===----------------------------------------------------------------------===//
3067
3068/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003069void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003070 // Analyze block parameters.
3071 BlockSemaInfo *BSI = new BlockSemaInfo();
3072
3073 // Add BSI to CurBlock.
3074 BSI->PrevBlockInfo = CurBlock;
3075 CurBlock = BSI;
3076
3077 BSI->ReturnType = 0;
3078 BSI->TheScope = BlockScope;
3079
Steve Naroff52059382008-10-10 01:28:17 +00003080 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3081 PushDeclContext(BSI->TheDecl);
3082}
3083
3084void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003085 // Analyze arguments to block.
3086 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3087 "Not a function declarator!");
3088 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3089
Steve Naroff52059382008-10-10 01:28:17 +00003090 CurBlock->hasPrototype = FTI.hasPrototype;
3091 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003092
3093 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3094 // no arguments, not a function that takes a single void argument.
3095 if (FTI.hasPrototype &&
3096 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3097 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3098 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3099 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003100 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003101 } else if (FTI.hasPrototype) {
3102 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003103 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3104 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003105 }
Steve Naroff52059382008-10-10 01:28:17 +00003106 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3107
3108 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3109 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3110 // If this has an identifier, add it to the scope stack.
3111 if ((*AI)->getIdentifier())
3112 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003113}
3114
3115/// ActOnBlockError - If there is an error parsing a block, this callback
3116/// is invoked to pop the information about the block from the action impl.
3117void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3118 // Ensure that CurBlock is deleted.
3119 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3120
3121 // Pop off CurBlock, handle nested blocks.
3122 CurBlock = CurBlock->PrevBlockInfo;
3123
3124 // FIXME: Delete the ParmVarDecl objects as well???
3125
3126}
3127
3128/// ActOnBlockStmtExpr - This is called when the body of a block statement
3129/// literal was successfully completed. ^(int x){...}
3130Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3131 Scope *CurScope) {
3132 // Ensure that CurBlock is deleted.
3133 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3134 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3135
Steve Naroff52059382008-10-10 01:28:17 +00003136 PopDeclContext();
3137
Steve Naroff52a81c02008-09-03 18:15:37 +00003138 // Pop off CurBlock, handle nested blocks.
3139 CurBlock = CurBlock->PrevBlockInfo;
3140
3141 QualType RetTy = Context.VoidTy;
3142 if (BSI->ReturnType)
3143 RetTy = QualType(BSI->ReturnType, 0);
3144
3145 llvm::SmallVector<QualType, 8> ArgTypes;
3146 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3147 ArgTypes.push_back(BSI->Params[i]->getType());
3148
3149 QualType BlockTy;
3150 if (!BSI->hasPrototype)
3151 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3152 else
3153 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003154 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003155
3156 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003157
Steve Naroff95029d92008-10-08 18:44:00 +00003158 BSI->TheDecl->setBody(Body.take());
3159 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003160}
3161
Nate Begemanbd881ef2008-01-30 20:50:20 +00003162/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003163/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003164/// The number of arguments has already been validated to match the number of
3165/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003166static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3167 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003168 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003169 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003170 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3171 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003172
3173 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003174 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003175 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003176 return true;
3177}
3178
3179Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3180 SourceLocation *CommaLocs,
3181 SourceLocation BuiltinLoc,
3182 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003183 // __builtin_overload requires at least 2 arguments
3184 if (NumArgs < 2)
3185 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3186 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003187
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003188 // The first argument is required to be a constant expression. It tells us
3189 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003190 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003191 Expr *NParamsExpr = Args[0];
3192 llvm::APSInt constEval(32);
3193 SourceLocation ExpLoc;
3194 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3195 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3196 NParamsExpr->getSourceRange());
3197
3198 // Verify that the number of parameters is > 0
3199 unsigned NumParams = constEval.getZExtValue();
3200 if (NumParams == 0)
3201 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3202 NParamsExpr->getSourceRange());
3203 // Verify that we have at least 1 + NumParams arguments to the builtin.
3204 if ((NumParams + 1) > NumArgs)
3205 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3206 SourceRange(BuiltinLoc, RParenLoc));
3207
3208 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003209 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003210 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003211 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3212 // UsualUnaryConversions will convert the function DeclRefExpr into a
3213 // pointer to function.
3214 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003215 const FunctionTypeProto *FnType = 0;
3216 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3217 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003218
3219 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3220 // parameters, and the number of parameters must match the value passed to
3221 // the builtin.
3222 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00003223 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3224 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003225
3226 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003227 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003228 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003229 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003230 if (OE)
3231 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3232 OE->getFn()->getSourceRange());
3233 // Remember our match, and continue processing the remaining arguments
3234 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003235 OE = new OverloadExpr(Args, NumArgs, i,
3236 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003237 BuiltinLoc, RParenLoc);
3238 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003239 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003240 // Return the newly created OverloadExpr node, if we succeded in matching
3241 // exactly one of the candidate functions.
3242 if (OE)
3243 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003244
3245 // If we didn't find a matching function Expr in the __builtin_overload list
3246 // the return an error.
3247 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003248 for (unsigned i = 0; i != NumParams; ++i) {
3249 if (i != 0) typeNames += ", ";
3250 typeNames += Args[i+1]->getType().getAsString();
3251 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003252
3253 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3254 SourceRange(BuiltinLoc, RParenLoc));
3255}
3256
Anders Carlsson36760332007-10-15 20:28:48 +00003257Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3258 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003259 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003260 Expr *E = static_cast<Expr*>(expr);
3261 QualType T = QualType::getFromOpaquePtr(type);
3262
3263 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003264
3265 // Get the va_list type
3266 QualType VaListType = Context.getBuiltinVaListType();
3267 // Deal with implicit array decay; for example, on x86-64,
3268 // va_list is an array, but it's supposed to decay to
3269 // a pointer for va_arg.
3270 if (VaListType->isArrayType())
3271 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003272 // Make sure the input expression also decays appropriately.
3273 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003274
3275 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003276 return Diag(E->getLocStart(),
3277 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3278 E->getType().getAsString(),
3279 E->getSourceRange());
3280
3281 // FIXME: Warn if a non-POD type is passed in.
3282
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003283 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003284}
3285
Chris Lattner005ed752008-01-04 18:04:52 +00003286bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3287 SourceLocation Loc,
3288 QualType DstType, QualType SrcType,
3289 Expr *SrcExpr, const char *Flavor) {
3290 // Decode the result (notice that AST's are still created for extensions).
3291 bool isInvalid = false;
3292 unsigned DiagKind;
3293 switch (ConvTy) {
3294 default: assert(0 && "Unknown conversion type");
3295 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003296 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003297 DiagKind = diag::ext_typecheck_convert_pointer_int;
3298 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003299 case IntToPointer:
3300 DiagKind = diag::ext_typecheck_convert_int_pointer;
3301 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003302 case IncompatiblePointer:
3303 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3304 break;
3305 case FunctionVoidPointer:
3306 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3307 break;
3308 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003309 // If the qualifiers lost were because we were applying the
3310 // (deprecated) C++ conversion from a string literal to a char*
3311 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3312 // Ideally, this check would be performed in
3313 // CheckPointerTypesForAssignment. However, that would require a
3314 // bit of refactoring (so that the second argument is an
3315 // expression, rather than a type), which should be done as part
3316 // of a larger effort to fix CheckPointerTypesForAssignment for
3317 // C++ semantics.
3318 if (getLangOptions().CPlusPlus &&
3319 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3320 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003321 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3322 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003323 case IntToBlockPointer:
3324 DiagKind = diag::err_int_to_block_pointer;
3325 break;
3326 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003327 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003328 break;
3329 case BlockVoidPointer:
3330 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3331 break;
Steve Naroff19608432008-10-14 22:18:38 +00003332 case IncompatibleObjCQualifiedId:
3333 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3334 // it can give a more specific diagnostic.
3335 DiagKind = diag::warn_incompatible_qualified_id;
3336 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003337 case Incompatible:
3338 DiagKind = diag::err_typecheck_convert_incompatible;
3339 isInvalid = true;
3340 break;
3341 }
3342
3343 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3344 SrcExpr->getSourceRange());
3345 return isInvalid;
3346}