blob: a45d6717b797a0525ddcbef0eddfa2f156731739 [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.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000338/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
339/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000340Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000341 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000342 bool HasTrailingLParen,
343 const CXXScopeSpec *SS) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000344 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000345 Decl *D;
346 if (SS && !SS->isEmpty()) {
347 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
348 if (DC == 0)
349 return true;
350 D = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC);
351 } else
352 D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000353
354 // If this reference is in an Objective-C method, then ivar lookup happens as
355 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000356 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000357 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000358 // There are two cases to handle here. 1) scoped lookup could have failed,
359 // in which case we should look for an ivar. 2) scoped lookup could have
360 // found a decl, but that decl is outside the current method (i.e. a global
361 // variable). In these two cases, we do a lookup for an ivar with this
362 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000363 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000364 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000365 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000366 // FIXME: This should use a new expr for a direct reference, don't turn
367 // this into Self->ivar, just return a BareIVarExpr or something.
368 IdentifierInfo &II = Context.Idents.get("self");
369 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
370 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
371 static_cast<Expr*>(SelfExpr.Val), true, true);
372 }
373 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000374 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000375 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000376 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000377 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000378 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000379 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000380 }
Chris Lattner4b009652007-07-25 00:24:17 +0000381 if (D == 0) {
382 // Otherwise, this could be an implicitly declared function reference (legal
383 // in C90, extension in C99).
384 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000385 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000386 D = ImplicitlyDefineFunction(Loc, II, S);
387 else {
388 // If this name wasn't predeclared and if this is not a function call,
389 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000390 if (SS && !SS->isEmpty())
391 return Diag(Loc, diag::err_typecheck_no_member,
392 II.getName(), SS->getRange());
393 else
394 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000395 }
396 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000397
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000398 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
399 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
400 if (MD->isStatic())
401 // "invalid use of member 'x' in static member function"
402 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
403 FD->getName());
404 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
405 // "invalid use of nonstatic data member 'x'"
406 return Diag(Loc, diag::err_invalid_non_static_member_use,
407 FD->getName());
408
409 if (FD->isInvalidDecl())
410 return true;
411
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000412 // FIXME: Handle 'mutable'.
413 return new DeclRefExpr(FD,
414 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000415 }
416
417 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
418 }
Chris Lattner4b009652007-07-25 00:24:17 +0000419 if (isa<TypedefDecl>(D))
420 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000421 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000422 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000423 if (isa<NamespaceDecl>(D))
424 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000425
Steve Naroffd6163f32008-09-05 22:11:13 +0000426 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000427 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
428 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
429
Steve Naroffd6163f32008-09-05 22:11:13 +0000430 ValueDecl *VD = cast<ValueDecl>(D);
431
432 // check if referencing an identifier with __attribute__((deprecated)).
433 if (VD->getAttr<DeprecatedAttr>())
434 Diag(Loc, diag::warn_deprecated, VD->getName());
435
436 // Only create DeclRefExpr's for valid Decl's.
437 if (VD->isInvalidDecl())
438 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000439
440 // If the identifier reference is inside a block, and it refers to a value
441 // that is outside the block, create a BlockDeclRefExpr instead of a
442 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
443 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000444 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000445 // We do not do this for things like enum constants, global variables, etc,
446 // as they do not get snapshotted.
447 //
448 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000449 // The BlocksAttr indicates the variable is bound by-reference.
450 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000451 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
452 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000453
454 // Variable will be bound by-copy, make it const within the closure.
455 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000456 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
457 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000458 }
459 // If this reference is not in a block or if the referenced variable is
460 // within the block, create a normal DeclRefExpr.
Douglas Gregor3fb675a2008-10-22 04:14:44 +0000461 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000462}
463
Chris Lattner69909292008-08-10 01:53:14 +0000464Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000465 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000466 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000467
468 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000469 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000470 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
471 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
472 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000473 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000474
475 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000476 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000477 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000478
Chris Lattner7e637512008-01-12 08:14:25 +0000479 // Pre-defined identifiers are of type char[x], where x is the length of the
480 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000481 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000482 if (getCurFunctionDecl())
483 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000484 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000485 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000486
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000487 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000488 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000489 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000490 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000491}
492
Steve Naroff87d58b42007-09-16 03:34:24 +0000493Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000494 llvm::SmallString<16> CharBuffer;
495 CharBuffer.resize(Tok.getLength());
496 const char *ThisTokBegin = &CharBuffer[0];
497 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
498
499 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
500 Tok.getLocation(), PP);
501 if (Literal.hadError())
502 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000503
504 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
505
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000506 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
507 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000508}
509
Steve Naroff87d58b42007-09-16 03:34:24 +0000510Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000511 // fast path for a single digit (which is quite common). A single digit
512 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
513 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000514 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000515
Chris Lattner8cd0e932008-03-05 18:54:05 +0000516 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000517 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000518 Context.IntTy,
519 Tok.getLocation()));
520 }
521 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000522 // Add padding so that NumericLiteralParser can overread by one character.
523 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000524 const char *ThisTokBegin = &IntegerBuffer[0];
525
526 // Get the spelling of the token, which eliminates trigraphs, etc.
527 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000528
Chris Lattner4b009652007-07-25 00:24:17 +0000529 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
530 Tok.getLocation(), PP);
531 if (Literal.hadError)
532 return ExprResult(true);
533
Chris Lattner1de66eb2007-08-26 03:42:43 +0000534 Expr *Res;
535
536 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000537 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000538 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000539 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000540 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000541 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000542 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000543 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000544
545 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
546
Ted Kremenekddedbe22007-11-29 00:56:49 +0000547 // isExact will be set by GetFloatValue().
548 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000549 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000550 Ty, Tok.getLocation());
551
Chris Lattner1de66eb2007-08-26 03:42:43 +0000552 } else if (!Literal.isIntegerLiteral()) {
553 return ExprResult(true);
554 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000555 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000556
Neil Booth7421e9c2007-08-29 22:00:19 +0000557 // long long is a C99 feature.
558 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000559 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000560 Diag(Tok.getLocation(), diag::ext_longlong);
561
Chris Lattner4b009652007-07-25 00:24:17 +0000562 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000563 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000564
565 if (Literal.GetIntegerValue(ResultVal)) {
566 // If this value didn't fit into uintmax_t, warn and force to ull.
567 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000568 Ty = Context.UnsignedLongLongTy;
569 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000570 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000571 } else {
572 // If this value fits into a ULL, try to figure out what else it fits into
573 // according to the rules of C99 6.4.4.1p5.
574
575 // Octal, Hexadecimal, and integers with a U suffix are allowed to
576 // be an unsigned int.
577 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
578
579 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000580 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000581 if (!Literal.isLong && !Literal.isLongLong) {
582 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000583 unsigned IntSize = Context.Target.getIntWidth();
584
Chris Lattner4b009652007-07-25 00:24:17 +0000585 // Does it fit in a unsigned int?
586 if (ResultVal.isIntN(IntSize)) {
587 // Does it fit in a signed int?
588 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000589 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000590 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000591 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000592 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000593 }
Chris Lattner4b009652007-07-25 00:24:17 +0000594 }
595
596 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000597 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000598 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000599
600 // Does it fit in a unsigned long?
601 if (ResultVal.isIntN(LongSize)) {
602 // Does it fit in a signed long?
603 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000604 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000605 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000606 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000607 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000608 }
Chris Lattner4b009652007-07-25 00:24:17 +0000609 }
610
611 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000612 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000613 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000614
615 // Does it fit in a unsigned long long?
616 if (ResultVal.isIntN(LongLongSize)) {
617 // Does it fit in a signed long long?
618 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000619 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000620 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000621 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000622 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000623 }
624 }
625
626 // If we still couldn't decide a type, we probably have something that
627 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000628 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000629 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000630 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000631 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000632 }
Chris Lattnere4068872008-05-09 05:59:00 +0000633
634 if (ResultVal.getBitWidth() != Width)
635 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000636 }
637
Chris Lattner48d7f382008-04-02 04:24:33 +0000638 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000639 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000640
641 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
642 if (Literal.isImaginary)
643 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
644
645 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000646}
647
Steve Naroff87d58b42007-09-16 03:34:24 +0000648Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000649 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000650 Expr *E = (Expr *)Val;
651 assert((E != 0) && "ActOnParenExpr() missing expr");
652 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000653}
654
655/// The UsualUnaryConversions() function is *not* called by this routine.
656/// See C99 6.3.2.1p[2-4] for more details.
657QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000658 SourceLocation OpLoc,
659 const SourceRange &ExprRange,
660 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000661 // C99 6.5.3.4p1:
662 if (isa<FunctionType>(exprType) && isSizeof)
663 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000664 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000665 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000666 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
667 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000668 else if (exprType->isIncompleteType()) {
669 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
670 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000671 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000672 return QualType(); // error
673 }
674 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
675 return Context.getSizeType();
676}
677
678Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000679ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000680 SourceLocation LPLoc, TypeTy *Ty,
681 SourceLocation RPLoc) {
682 // If error parsing type, ignore.
683 if (Ty == 0) return true;
684
685 // Verify that this is a valid expression.
686 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
687
Chris Lattnerf814d882008-07-25 21:45:37 +0000688 QualType resultType =
689 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000690
691 if (resultType.isNull())
692 return true;
693 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
694}
695
Chris Lattner5110ad52007-08-24 21:41:10 +0000696QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000697 DefaultFunctionArrayConversion(V);
698
Chris Lattnera16e42d2007-08-26 05:39:26 +0000699 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000700 if (const ComplexType *CT = V->getType()->getAsComplexType())
701 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000702
703 // Otherwise they pass through real integer and floating point types here.
704 if (V->getType()->isArithmeticType())
705 return V->getType();
706
707 // Reject anything else.
708 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
709 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000710}
711
712
Chris Lattner4b009652007-07-25 00:24:17 +0000713
Steve Naroff87d58b42007-09-16 03:34:24 +0000714Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000715 tok::TokenKind Kind,
716 ExprTy *Input) {
717 UnaryOperator::Opcode Opc;
718 switch (Kind) {
719 default: assert(0 && "Unknown unary op!");
720 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
721 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
722 }
723 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
724 if (result.isNull())
725 return true;
726 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
727}
728
729Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000730ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000731 ExprTy *Idx, SourceLocation RLoc) {
732 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
733
734 // Perform default conversions.
735 DefaultFunctionArrayConversion(LHSExp);
736 DefaultFunctionArrayConversion(RHSExp);
737
738 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
739
740 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000741 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000742 // in the subscript position. As a result, we need to derive the array base
743 // and index from the expression types.
744 Expr *BaseExpr, *IndexExpr;
745 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000746 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000747 BaseExpr = LHSExp;
748 IndexExpr = RHSExp;
749 // FIXME: need to deal with const...
750 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000751 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000752 // Handle the uncommon case of "123[Ptr]".
753 BaseExpr = RHSExp;
754 IndexExpr = LHSExp;
755 // FIXME: need to deal with const...
756 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000757 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
758 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000759 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000760
761 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000762 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
763 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000764 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000765 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000766 // FIXME: need to deal with const...
767 ResultType = VTy->getElementType();
768 } else {
769 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
770 RHSExp->getSourceRange());
771 }
772 // C99 6.5.2.1p1
773 if (!IndexExpr->getType()->isIntegerType())
774 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
775 IndexExpr->getSourceRange());
776
777 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
778 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000779 // void (*)(int)) and pointers to incomplete types. Functions are not
780 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000781 if (!ResultType->isObjectType())
782 return Diag(BaseExpr->getLocStart(),
783 diag::err_typecheck_subscript_not_object,
784 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
785
786 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
787}
788
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000789QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000790CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000791 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000792 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000793
794 // This flag determines whether or not the component is to be treated as a
795 // special name, or a regular GLSL-style component access.
796 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000797
798 // The vector accessor can't exceed the number of elements.
799 const char *compStr = CompName.getName();
800 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000801 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000802 baseType.getAsString(), SourceRange(CompLoc));
803 return QualType();
804 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000805
806 // Check that we've found one of the special components, or that the component
807 // names must come from the same set.
808 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
809 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
810 SpecialComponent = true;
811 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000812 do
813 compStr++;
814 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
815 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
816 do
817 compStr++;
818 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
819 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
820 do
821 compStr++;
822 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
823 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000824
Nate Begemanc8e51f82008-05-09 06:41:27 +0000825 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000826 // We didn't get to the end of the string. This means the component names
827 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000828 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000829 std::string(compStr,compStr+1), SourceRange(CompLoc));
830 return QualType();
831 }
832 // Each component accessor can't exceed the vector type.
833 compStr = CompName.getName();
834 while (*compStr) {
835 if (vecType->isAccessorWithinNumElements(*compStr))
836 compStr++;
837 else
838 break;
839 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000840 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000841 // We didn't get to the end of the string. This means a component accessor
842 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000843 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000844 baseType.getAsString(), SourceRange(CompLoc));
845 return QualType();
846 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000847
848 // If we have a special component name, verify that the current vector length
849 // is an even number, since all special component names return exactly half
850 // the elements.
851 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbar45a91802008-09-30 17:22:47 +0000852 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
853 baseType.getAsString(), SourceRange(CompLoc));
Nate Begemanc8e51f82008-05-09 06:41:27 +0000854 return QualType();
855 }
856
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000857 // The component accessor looks fine - now we need to compute the actual type.
858 // The vector type is implied by the component accessor. For example,
859 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000860 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
861 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
862 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000863 if (CompSize == 1)
864 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000865
Nate Begemanaf6ed502008-04-18 23:10:10 +0000866 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000867 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000868 // diagostics look bad. We want extended vector types to appear built-in.
869 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
870 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
871 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000872 }
873 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000874}
875
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000876/// constructSetterName - Return the setter name for the given
877/// identifier, i.e. "set" + Name where the initial character of Name
878/// has been capitalized.
879// FIXME: Merge with same routine in Parser. But where should this
880// live?
881static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
882 const IdentifierInfo *Name) {
883 unsigned N = Name->getLength();
884 char *SelectorName = new char[3 + N];
885 memcpy(SelectorName, "set", 3);
886 memcpy(&SelectorName[3], Name->getName(), N);
887 SelectorName[3] = toupper(SelectorName[3]);
888
889 IdentifierInfo *Setter =
890 &Idents.get(SelectorName, &SelectorName[3 + N]);
891 delete[] SelectorName;
892 return Setter;
893}
894
Chris Lattner4b009652007-07-25 00:24:17 +0000895Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000896ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000897 tok::TokenKind OpKind, SourceLocation MemberLoc,
898 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000899 Expr *BaseExpr = static_cast<Expr *>(Base);
900 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000901
902 // Perform default conversions.
903 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000904
Steve Naroff2cb66382007-07-26 03:11:44 +0000905 QualType BaseType = BaseExpr->getType();
906 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000907
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000908 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
909 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000910 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000911 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000912 BaseType = PT->getPointeeType();
913 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000914 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
915 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000916 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000917
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000918 // Handle field access to simple records. This also handles access to fields
919 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000920 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000921 RecordDecl *RDecl = RTy->getDecl();
922 if (RTy->isIncompleteType())
923 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
924 BaseExpr->getSourceRange());
925 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000926 FieldDecl *MemberDecl = RDecl->getMember(&Member);
927 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000928 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
929 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000930
931 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000932 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000933 QualType MemberType = MemberDecl->getType();
934 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000935 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000936 MemberType = MemberType.getQualifiedType(combinedQualifiers);
937
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000938 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000939 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000940 }
941
Chris Lattnere9d71612008-07-21 04:59:05 +0000942 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
943 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000944 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
945 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000946 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000947 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000948 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000949 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000950 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000951 }
952
Chris Lattnere9d71612008-07-21 04:59:05 +0000953 // Handle Objective-C property access, which is "Obj.property" where Obj is a
954 // pointer to a (potentially qualified) interface type.
955 const PointerType *PTy;
956 const ObjCInterfaceType *IFTy;
957 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
958 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
959 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000960
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000961 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000962 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
963 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
964
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000965 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000966 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
967 E = IFTy->qual_end(); I != E; ++I)
968 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
969 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000970
971 // If that failed, look for an "implicit" property by seeing if the nullary
972 // selector is implemented.
973
974 // FIXME: The logic for looking up nullary and unary selectors should be
975 // shared with the code in ActOnInstanceMessage.
976
977 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
978 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
979
980 // If this reference is in an @implementation, check for 'private' methods.
981 if (!Getter)
982 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
983 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
984 if (ObjCImplementationDecl *ImpDecl =
985 ObjCImplementations[ClassDecl->getIdentifier()])
986 Getter = ImpDecl->getInstanceMethod(Sel);
987
Steve Naroff04151f32008-10-22 19:16:27 +0000988 // Look through local category implementations associated with the class.
989 if (!Getter) {
990 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
991 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
992 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
993 }
994 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000995 if (Getter) {
996 // If we found a getter then this may be a valid dot-reference, we
997 // need to also look for the matching setter.
998 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
999 &Member);
1000 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1001 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1002
1003 if (!Setter) {
1004 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1005 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1006 if (ObjCImplementationDecl *ImpDecl =
1007 ObjCImplementations[ClassDecl->getIdentifier()])
1008 Setter = ImpDecl->getInstanceMethod(SetterSel);
1009 }
1010
1011 // FIXME: There are some issues here. First, we are not
1012 // diagnosing accesses to read-only properties because we do not
1013 // know if this is a getter or setter yet. Second, we are
1014 // checking that the type of the setter matches the type we
1015 // expect.
1016 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1017 MemberLoc, BaseExpr);
1018 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001019 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001020 // Handle properties on qualified "id" protocols.
1021 const ObjCQualifiedIdType *QIdTy;
1022 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1023 // Check protocols on qualified interfaces.
1024 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1025 E = QIdTy->qual_end(); I != E; ++I)
1026 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1027 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1028 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001029 // Handle 'field access' to vectors, such as 'V.xx'.
1030 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1031 // Component access limited to variables (reject vec4.rg.g).
1032 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1033 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +00001034 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1035 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001036 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1037 if (ret.isNull())
1038 return true;
1039 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1040 }
1041
Chris Lattner7d5a8762008-07-21 05:35:34 +00001042 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1043 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001044}
1045
Steve Naroff87d58b42007-09-16 03:34:24 +00001046/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001047/// This provides the location of the left/right parens and a list of comma
1048/// locations.
1049Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001050ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001051 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001052 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1053 Expr *Fn = static_cast<Expr *>(fn);
1054 Expr **Args = reinterpret_cast<Expr**>(args);
1055 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001056 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001057 OverloadedFunctionDecl *Ovl = NULL;
1058
1059 // If we're directly calling a function or a set of overloaded
1060 // functions, get the appropriate declaration.
1061 {
1062 DeclRefExpr *DRExpr = NULL;
1063 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1064 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1065 else
1066 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1067
1068 if (DRExpr) {
1069 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1070 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1071 }
1072 }
1073
1074 // If we have a set of overloaded functions, perform overload
1075 // resolution to pick the function.
1076 if (Ovl) {
1077 OverloadCandidateSet CandidateSet;
1078 OverloadCandidateSet::iterator Best;
1079 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1080 switch (BestViableFunction(CandidateSet, Best)) {
1081 case OR_Success:
1082 {
1083 // Success! Let the remainder of this function build a call to
1084 // the function selected by overload resolution.
1085 FDecl = Best->Function;
1086 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1087 Fn->getSourceRange().getBegin());
1088 delete Fn;
1089 Fn = NewFn;
1090 }
1091 break;
1092
1093 case OR_No_Viable_Function:
1094 if (CandidateSet.empty())
1095 Diag(Fn->getSourceRange().getBegin(),
1096 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1097 Fn->getSourceRange());
1098 else {
1099 Diag(Fn->getSourceRange().getBegin(),
1100 diag::err_ovl_no_viable_function_in_call_with_cands,
1101 Ovl->getName(), Fn->getSourceRange());
1102 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1103 }
1104 return true;
1105
1106 case OR_Ambiguous:
1107 Diag(Fn->getSourceRange().getBegin(),
1108 diag::err_ovl_ambiguous_call, Ovl->getName(),
1109 Fn->getSourceRange());
1110 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1111 return true;
1112 }
1113 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001114
1115 // Promote the function operand.
1116 UsualUnaryConversions(Fn);
1117
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001118 // Make the call expr early, before semantic checks. This guarantees cleanup
1119 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001120 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001121 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001122 const FunctionType *FuncT;
1123 if (!Fn->getType()->isBlockPointerType()) {
1124 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1125 // have type pointer to function".
1126 const PointerType *PT = Fn->getType()->getAsPointerType();
1127 if (PT == 0)
1128 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1129 Fn->getSourceRange());
1130 FuncT = PT->getPointeeType()->getAsFunctionType();
1131 } else { // This is a block call.
1132 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1133 getAsFunctionType();
1134 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001135 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001136 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1137 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001138
1139 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001140 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001141
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001142 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001143 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1144 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001145 unsigned NumArgsInProto = Proto->getNumArgs();
1146 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001147
Chris Lattner3e254fb2008-04-08 04:40:51 +00001148 // If too few arguments are available (and we don't have default
1149 // arguments for the remaining parameters), don't make the call.
1150 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001151 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001152 // Use default arguments for missing arguments
1153 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001154 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001155 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001156 return Diag(RParenLoc,
1157 !Fn->getType()->isBlockPointerType()
1158 ? diag::err_typecheck_call_too_few_args
1159 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001160 Fn->getSourceRange());
1161 }
1162
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001163 // If too many are passed and not variadic, error on the extras and drop
1164 // them.
1165 if (NumArgs > NumArgsInProto) {
1166 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001167 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001168 !Fn->getType()->isBlockPointerType()
1169 ? diag::err_typecheck_call_too_many_args
1170 : diag::err_typecheck_block_too_many_args,
1171 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001172 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001173 Args[NumArgs-1]->getLocEnd()));
1174 // This deletes the extra arguments.
1175 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001176 }
1177 NumArgsToCheck = NumArgsInProto;
1178 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001179
Chris Lattner4b009652007-07-25 00:24:17 +00001180 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001181 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001182 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001183
1184 Expr *Arg;
1185 if (i < NumArgs)
1186 Arg = Args[i];
1187 else
1188 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001189 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001190
Douglas Gregor81c29152008-10-29 00:13:59 +00001191 // Pass the argument.
1192 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001193 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001194
1195 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001196 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001197
1198 // If this is a variadic call, handle args passed through "...".
1199 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001200 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001201 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1202 Expr *Arg = Args[i];
1203 DefaultArgumentPromotion(Arg);
1204 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001205 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001206 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001207 } else {
1208 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1209
Steve Naroffdb65e052007-08-28 23:30:39 +00001210 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001211 for (unsigned i = 0; i != NumArgs; i++) {
1212 Expr *Arg = Args[i];
1213 DefaultArgumentPromotion(Arg);
1214 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001215 }
Chris Lattner4b009652007-07-25 00:24:17 +00001216 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001217
Chris Lattner2e64c072007-08-10 20:18:51 +00001218 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001219 if (FDecl)
1220 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001221
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001222 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001223}
1224
1225Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001226ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001227 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001228 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001229 QualType literalType = QualType::getFromOpaquePtr(Ty);
1230 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001231 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001232 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001233
Eli Friedman8c2173d2008-05-20 05:22:08 +00001234 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001235 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001236 return Diag(LParenLoc,
1237 diag::err_variable_object_no_init,
1238 SourceRange(LParenLoc,
1239 literalExpr->getSourceRange().getEnd()));
1240 } else if (literalType->isIncompleteType()) {
1241 return Diag(LParenLoc,
1242 diag::err_typecheck_decl_incomplete_type,
1243 literalType.getAsString(),
1244 SourceRange(LParenLoc,
1245 literalExpr->getSourceRange().getEnd()));
1246 }
1247
Douglas Gregor6428e762008-11-05 15:29:30 +00001248 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
1249 "temporary"))
Steve Naroff92590f92008-01-09 20:58:06 +00001250 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001251
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001252 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001253 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001254 if (CheckForConstantInitializer(literalExpr, literalType))
1255 return true;
1256 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001257 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1258 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001259}
1260
1261Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001262ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001263 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001264 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001265 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001266
Steve Naroff0acc9c92007-09-15 18:49:24 +00001267 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001268 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001269
Chris Lattner71ca8c82008-10-26 23:43:26 +00001270 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1271 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001272 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1273 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001274}
1275
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001276/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001277bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001278 UsualUnaryConversions(castExpr);
1279
1280 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1281 // type needs to be scalar.
1282 if (castType->isVoidType()) {
1283 // Cast to void allows any expr type.
1284 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1285 // GCC struct/union extension: allow cast to self.
1286 if (Context.getCanonicalType(castType) !=
1287 Context.getCanonicalType(castExpr->getType()) ||
1288 (!castType->isStructureType() && !castType->isUnionType())) {
1289 // Reject any other conversions to non-scalar types.
1290 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1291 castType.getAsString(), castExpr->getSourceRange());
1292 }
1293
1294 // accept this, but emit an ext-warn.
1295 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1296 castType.getAsString(), castExpr->getSourceRange());
1297 } else if (!castExpr->getType()->isScalarType() &&
1298 !castExpr->getType()->isVectorType()) {
1299 return Diag(castExpr->getLocStart(),
1300 diag::err_typecheck_expect_scalar_operand,
1301 castExpr->getType().getAsString(),castExpr->getSourceRange());
1302 } else if (castExpr->getType()->isVectorType()) {
1303 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1304 return true;
1305 } else if (castType->isVectorType()) {
1306 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1307 return true;
1308 }
1309 return false;
1310}
1311
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001312bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001313 assert(VectorTy->isVectorType() && "Not a vector type!");
1314
1315 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001316 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001317 return Diag(R.getBegin(),
1318 Ty->isVectorType() ?
1319 diag::err_invalid_conversion_between_vectors :
1320 diag::err_invalid_conversion_between_vector_and_integer,
1321 VectorTy.getAsString().c_str(),
1322 Ty.getAsString().c_str(), R);
1323 } else
1324 return Diag(R.getBegin(),
1325 diag::err_invalid_conversion_between_vector_and_scalar,
1326 VectorTy.getAsString().c_str(),
1327 Ty.getAsString().c_str(), R);
1328
1329 return false;
1330}
1331
Chris Lattner4b009652007-07-25 00:24:17 +00001332Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001333ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001334 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001335 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001336
1337 Expr *castExpr = static_cast<Expr*>(Op);
1338 QualType castType = QualType::getFromOpaquePtr(Ty);
1339
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001340 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1341 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001342 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001343}
1344
Chris Lattner98a425c2007-11-26 01:40:58 +00001345/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1346/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001347inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1348 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1349 UsualUnaryConversions(cond);
1350 UsualUnaryConversions(lex);
1351 UsualUnaryConversions(rex);
1352 QualType condT = cond->getType();
1353 QualType lexT = lex->getType();
1354 QualType rexT = rex->getType();
1355
1356 // first, check the condition.
1357 if (!condT->isScalarType()) { // C99 6.5.15p2
1358 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1359 condT.getAsString());
1360 return QualType();
1361 }
Chris Lattner992ae932008-01-06 22:42:25 +00001362
1363 // Now check the two expressions.
1364
1365 // If both operands have arithmetic type, do the usual arithmetic conversions
1366 // to find a common type: C99 6.5.15p3,5.
1367 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001368 UsualArithmeticConversions(lex, rex);
1369 return lex->getType();
1370 }
Chris Lattner992ae932008-01-06 22:42:25 +00001371
1372 // If both operands are the same structure or union type, the result is that
1373 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001374 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001375 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001376 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001377 // "If both the operands have structure or union type, the result has
1378 // that type." This implies that CV qualifiers are dropped.
1379 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001380 }
Chris Lattner992ae932008-01-06 22:42:25 +00001381
1382 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001383 // The following || allows only one side to be void (a GCC-ism).
1384 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001385 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001386 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1387 rex->getSourceRange());
1388 if (!rexT->isVoidType())
1389 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001390 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001391 ImpCastExprToType(lex, Context.VoidTy);
1392 ImpCastExprToType(rex, Context.VoidTy);
1393 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001394 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001395 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1396 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001397 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1398 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001399 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001400 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001401 return lexT;
1402 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001403 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1404 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001405 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001406 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001407 return rexT;
1408 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001409 // Handle the case where both operands are pointers before we handle null
1410 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001411 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1412 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1413 // get the "pointed to" types
1414 QualType lhptee = LHSPT->getPointeeType();
1415 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001416
Chris Lattner71225142007-07-31 21:27:01 +00001417 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1418 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001419 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001420 // Figure out necessary qualifiers (C99 6.5.15p6)
1421 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001422 QualType destType = Context.getPointerType(destPointee);
1423 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1424 ImpCastExprToType(rex, destType); // promote to void*
1425 return destType;
1426 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001427 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001428 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001429 QualType destType = Context.getPointerType(destPointee);
1430 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1431 ImpCastExprToType(rex, destType); // promote to void*
1432 return destType;
1433 }
Chris Lattner4b009652007-07-25 00:24:17 +00001434
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001435 QualType compositeType = lexT;
1436
1437 // If either type is an Objective-C object type then check
1438 // compatibility according to Objective-C.
1439 if (Context.isObjCObjectPointerType(lexT) ||
1440 Context.isObjCObjectPointerType(rexT)) {
1441 // If both operands are interfaces and either operand can be
1442 // assigned to the other, use that type as the composite
1443 // type. This allows
1444 // xxx ? (A*) a : (B*) b
1445 // where B is a subclass of A.
1446 //
1447 // Additionally, as for assignment, if either type is 'id'
1448 // allow silent coercion. Finally, if the types are
1449 // incompatible then make sure to use 'id' as the composite
1450 // type so the result is acceptable for sending messages to.
1451
1452 // FIXME: This code should not be localized to here. Also this
1453 // should use a compatible check instead of abusing the
1454 // canAssignObjCInterfaces code.
1455 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1456 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1457 if (LHSIface && RHSIface &&
1458 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1459 compositeType = lexT;
1460 } else if (LHSIface && RHSIface &&
1461 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1462 compositeType = rexT;
1463 } else if (Context.isObjCIdType(lhptee) ||
1464 Context.isObjCIdType(rhptee)) {
1465 // FIXME: This code looks wrong, because isObjCIdType checks
1466 // the struct but getObjCIdType returns the pointer to
1467 // struct. This is horrible and should be fixed.
1468 compositeType = Context.getObjCIdType();
1469 } else {
1470 QualType incompatTy = Context.getObjCIdType();
1471 ImpCastExprToType(lex, incompatTy);
1472 ImpCastExprToType(rex, incompatTy);
1473 return incompatTy;
1474 }
1475 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1476 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001477 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001478 lexT.getAsString(), rexT.getAsString(),
1479 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001480 // In this situation, we assume void* type. No especially good
1481 // reason, but this is what gcc does, and we do have to pick
1482 // to get a consistent AST.
1483 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001484 ImpCastExprToType(lex, incompatTy);
1485 ImpCastExprToType(rex, incompatTy);
1486 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001487 }
1488 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001489 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1490 // differently qualified versions of compatible types, the result type is
1491 // a pointer to an appropriately qualified version of the *composite*
1492 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001493 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001494 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001495 ImpCastExprToType(lex, compositeType);
1496 ImpCastExprToType(rex, compositeType);
1497 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001498 }
Chris Lattner4b009652007-07-25 00:24:17 +00001499 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001500 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1501 // evaluates to "struct objc_object *" (and is handled above when comparing
1502 // id with statically typed objects).
1503 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1504 // GCC allows qualified id and any Objective-C type to devolve to
1505 // id. Currently localizing to here until clear this should be
1506 // part of ObjCQualifiedIdTypesAreCompatible.
1507 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1508 (lexT->isObjCQualifiedIdType() &&
1509 Context.isObjCObjectPointerType(rexT)) ||
1510 (rexT->isObjCQualifiedIdType() &&
1511 Context.isObjCObjectPointerType(lexT))) {
1512 // FIXME: This is not the correct composite type. This only
1513 // happens to work because id can more or less be used anywhere,
1514 // however this may change the type of method sends.
1515 // FIXME: gcc adds some type-checking of the arguments and emits
1516 // (confusing) incompatible comparison warnings in some
1517 // cases. Investigate.
1518 QualType compositeType = Context.getObjCIdType();
1519 ImpCastExprToType(lex, compositeType);
1520 ImpCastExprToType(rex, compositeType);
1521 return compositeType;
1522 }
1523 }
1524
Steve Naroff3eac7692008-09-10 19:17:48 +00001525 // Selection between block pointer types is ok as long as they are the same.
1526 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1527 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1528 return lexT;
1529
Chris Lattner992ae932008-01-06 22:42:25 +00001530 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001531 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1532 lexT.getAsString(), rexT.getAsString(),
1533 lex->getSourceRange(), rex->getSourceRange());
1534 return QualType();
1535}
1536
Steve Naroff87d58b42007-09-16 03:34:24 +00001537/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001538/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001539Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001540 SourceLocation ColonLoc,
1541 ExprTy *Cond, ExprTy *LHS,
1542 ExprTy *RHS) {
1543 Expr *CondExpr = (Expr *) Cond;
1544 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001545
1546 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1547 // was the condition.
1548 bool isLHSNull = LHSExpr == 0;
1549 if (isLHSNull)
1550 LHSExpr = CondExpr;
1551
Chris Lattner4b009652007-07-25 00:24:17 +00001552 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1553 RHSExpr, QuestionLoc);
1554 if (result.isNull())
1555 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001556 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1557 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001558}
1559
Chris Lattner4b009652007-07-25 00:24:17 +00001560
1561// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1562// being closely modeled after the C99 spec:-). The odd characteristic of this
1563// routine is it effectively iqnores the qualifiers on the top level pointee.
1564// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1565// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001566Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001567Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1568 QualType lhptee, rhptee;
1569
1570 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001571 lhptee = lhsType->getAsPointerType()->getPointeeType();
1572 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001573
1574 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001575 lhptee = Context.getCanonicalType(lhptee);
1576 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001577
Chris Lattner005ed752008-01-04 18:04:52 +00001578 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001579
1580 // C99 6.5.16.1p1: This following citation is common to constraints
1581 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1582 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001583 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001584 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001585 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001586
1587 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1588 // incomplete type and the other is a pointer to a qualified or unqualified
1589 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001590 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001591 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001592 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001593
1594 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001595 assert(rhptee->isFunctionType());
1596 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001597 }
1598
1599 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001600 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001601 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001602
1603 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001604 assert(lhptee->isFunctionType());
1605 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001606 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001607
1608 // Check for ObjC interfaces
1609 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1610 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1611 if (LHSIface && RHSIface &&
1612 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1613 return ConvTy;
1614
1615 // ID acts sort of like void* for ObjC interfaces
1616 if (LHSIface && Context.isObjCIdType(rhptee))
1617 return ConvTy;
1618 if (RHSIface && Context.isObjCIdType(lhptee))
1619 return ConvTy;
1620
Chris Lattner4b009652007-07-25 00:24:17 +00001621 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1622 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001623 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1624 rhptee.getUnqualifiedType()))
1625 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001626 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001627}
1628
Steve Naroff3454b6c2008-09-04 15:10:53 +00001629/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1630/// block pointer types are compatible or whether a block and normal pointer
1631/// are compatible. It is more restrict than comparing two function pointer
1632// types.
1633Sema::AssignConvertType
1634Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1635 QualType rhsType) {
1636 QualType lhptee, rhptee;
1637
1638 // get the "pointed to" type (ignoring qualifiers at the top level)
1639 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1640 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1641
1642 // make sure we operate on the canonical type
1643 lhptee = Context.getCanonicalType(lhptee);
1644 rhptee = Context.getCanonicalType(rhptee);
1645
1646 AssignConvertType ConvTy = Compatible;
1647
1648 // For blocks we enforce that qualifiers are identical.
1649 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1650 ConvTy = CompatiblePointerDiscardsQualifiers;
1651
1652 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1653 return IncompatibleBlockPointer;
1654 return ConvTy;
1655}
1656
Chris Lattner4b009652007-07-25 00:24:17 +00001657/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1658/// has code to accommodate several GCC extensions when type checking
1659/// pointers. Here are some objectionable examples that GCC considers warnings:
1660///
1661/// int a, *pint;
1662/// short *pshort;
1663/// struct foo *pfoo;
1664///
1665/// pint = pshort; // warning: assignment from incompatible pointer type
1666/// a = pint; // warning: assignment makes integer from pointer without a cast
1667/// pint = a; // warning: assignment makes pointer from integer without a cast
1668/// pint = pfoo; // warning: assignment from incompatible pointer type
1669///
1670/// As a result, the code for dealing with pointers is more complex than the
1671/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001672///
Chris Lattner005ed752008-01-04 18:04:52 +00001673Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001674Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001675 // Get canonical types. We're not formatting these types, just comparing
1676 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001677 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1678 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001679
1680 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001681 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001682
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001683 // If the left-hand side is a reference type, then we are in a
1684 // (rare!) case where we've allowed the use of references in C,
1685 // e.g., as a parameter type in a built-in function. In this case,
1686 // just make sure that the type referenced is compatible with the
1687 // right-hand side type. The caller is responsible for adjusting
1688 // lhsType so that the resulting expression does not have reference
1689 // type.
1690 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1691 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001692 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001693 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001694 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001695
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001696 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1697 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001698 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001699 // Relax integer conversions like we do for pointers below.
1700 if (rhsType->isIntegerType())
1701 return IntToPointer;
1702 if (lhsType->isIntegerType())
1703 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001704 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001705 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001706
Nate Begemanc5f0f652008-07-14 18:02:46 +00001707 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001708 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001709 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1710 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001711 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001712
Nate Begemanc5f0f652008-07-14 18:02:46 +00001713 // If we are allowing lax vector conversions, and LHS and RHS are both
1714 // vectors, the total size only needs to be the same. This is a bitcast;
1715 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001716 if (getLangOptions().LaxVectorConversions &&
1717 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001718 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1719 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001720 }
1721 return Incompatible;
1722 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001723
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001724 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001725 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001726
Chris Lattner390564e2008-04-07 06:49:41 +00001727 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001728 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001729 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001730
Chris Lattner390564e2008-04-07 06:49:41 +00001731 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001732 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001733
Steve Naroffa982c712008-09-29 18:10:17 +00001734 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001735 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001736 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001737
1738 // Treat block pointers as objects.
1739 if (getLangOptions().ObjC1 &&
1740 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1741 return Compatible;
1742 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001743 return Incompatible;
1744 }
1745
1746 if (isa<BlockPointerType>(lhsType)) {
1747 if (rhsType->isIntegerType())
1748 return IntToPointer;
1749
Steve Naroffa982c712008-09-29 18:10:17 +00001750 // Treat block pointers as objects.
1751 if (getLangOptions().ObjC1 &&
1752 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1753 return Compatible;
1754
Steve Naroff3454b6c2008-09-04 15:10:53 +00001755 if (rhsType->isBlockPointerType())
1756 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1757
1758 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1759 if (RHSPT->getPointeeType()->isVoidType())
1760 return BlockVoidPointer;
1761 }
Chris Lattner1853da22008-01-04 23:18:45 +00001762 return Incompatible;
1763 }
1764
Chris Lattner390564e2008-04-07 06:49:41 +00001765 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001766 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001767 if (lhsType == Context.BoolTy)
1768 return Compatible;
1769
1770 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001771 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001772
Chris Lattner390564e2008-04-07 06:49:41 +00001773 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001774 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001775
1776 if (isa<BlockPointerType>(lhsType) &&
1777 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1778 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001779 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001780 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001781
Chris Lattner1853da22008-01-04 23:18:45 +00001782 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001783 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001784 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001785 }
1786 return Incompatible;
1787}
1788
Chris Lattner005ed752008-01-04 18:04:52 +00001789Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001790Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001791 if (getLangOptions().CPlusPlus) {
1792 if (!lhsType->isRecordType()) {
1793 // C++ 5.17p3: If the left operand is not of class type, the
1794 // expression is implicitly converted (C++ 4) to the
1795 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00001796 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001797 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00001798 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001799 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001800 }
1801
1802 // FIXME: Currently, we fall through and treat C++ classes like C
1803 // structures.
1804 }
1805
Steve Naroffcdee22d2007-11-27 17:58:44 +00001806 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1807 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001808 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1809 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001810 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001811 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001812 return Compatible;
1813 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001814
1815 // We don't allow conversion of non-null-pointer constants to integers.
1816 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1817 return IntToBlockPointer;
1818
Chris Lattner5f505bf2007-10-16 02:55:40 +00001819 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001820 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001821 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001822 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001823 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001824 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00001825 if (!lhsType->isReferenceType())
1826 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001827
Chris Lattner005ed752008-01-04 18:04:52 +00001828 Sema::AssignConvertType result =
1829 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001830
1831 // C99 6.5.16.1p2: The value of the right operand is converted to the
1832 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001833 // CheckAssignmentConstraints allows the left-hand side to be a reference,
1834 // so that we can use references in built-in functions even in C.
1835 // The getNonReferenceType() call makes sure that the resulting expression
1836 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00001837 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001838 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001839 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001840}
1841
Chris Lattner005ed752008-01-04 18:04:52 +00001842Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001843Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1844 return CheckAssignmentConstraints(lhsType, rhsType);
1845}
1846
Chris Lattner2c8bff72007-12-12 05:47:28 +00001847QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001848 Diag(loc, diag::err_typecheck_invalid_operands,
1849 lex->getType().getAsString(), rex->getType().getAsString(),
1850 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001851 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001852}
1853
1854inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1855 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001856 // For conversion purposes, we ignore any qualifiers.
1857 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001858 QualType lhsType =
1859 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1860 QualType rhsType =
1861 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001862
Nate Begemanc5f0f652008-07-14 18:02:46 +00001863 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001864 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001865 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001866
Nate Begemanc5f0f652008-07-14 18:02:46 +00001867 // Handle the case of a vector & extvector type of the same size and element
1868 // type. It would be nice if we only had one vector type someday.
1869 if (getLangOptions().LaxVectorConversions)
1870 if (const VectorType *LV = lhsType->getAsVectorType())
1871 if (const VectorType *RV = rhsType->getAsVectorType())
1872 if (LV->getElementType() == RV->getElementType() &&
1873 LV->getNumElements() == RV->getNumElements())
1874 return lhsType->isExtVectorType() ? lhsType : rhsType;
1875
1876 // If the lhs is an extended vector and the rhs is a scalar of the same type
1877 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001878 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001879 QualType eltType = V->getElementType();
1880
1881 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1882 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1883 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001884 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001885 return lhsType;
1886 }
1887 }
1888
Nate Begemanc5f0f652008-07-14 18:02:46 +00001889 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001890 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001891 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001892 QualType eltType = V->getElementType();
1893
1894 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1895 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1896 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001897 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001898 return rhsType;
1899 }
1900 }
1901
Chris Lattner4b009652007-07-25 00:24:17 +00001902 // You cannot convert between vector values of different size.
1903 Diag(loc, diag::err_typecheck_vector_not_convertable,
1904 lex->getType().getAsString(), rex->getType().getAsString(),
1905 lex->getSourceRange(), rex->getSourceRange());
1906 return QualType();
1907}
1908
1909inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001910 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001911{
1912 QualType lhsType = lex->getType(), rhsType = rex->getType();
1913
1914 if (lhsType->isVectorType() || rhsType->isVectorType())
1915 return CheckVectorOperands(loc, lex, rex);
1916
Steve Naroff8f708362007-08-24 19:07:16 +00001917 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001918
Chris Lattner4b009652007-07-25 00:24:17 +00001919 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001920 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001921 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001922}
1923
1924inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001925 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001926{
1927 QualType lhsType = lex->getType(), rhsType = rex->getType();
1928
Steve Naroff8f708362007-08-24 19:07:16 +00001929 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001930
Chris Lattner4b009652007-07-25 00:24:17 +00001931 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001932 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001933 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001934}
1935
1936inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001937 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001938{
1939 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1940 return CheckVectorOperands(loc, lex, rex);
1941
Steve Naroff8f708362007-08-24 19:07:16 +00001942 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001943
Chris Lattner4b009652007-07-25 00:24:17 +00001944 // handle the common case first (both operands are arithmetic).
1945 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001946 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001947
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001948 // Put any potential pointer into PExp
1949 Expr* PExp = lex, *IExp = rex;
1950 if (IExp->getType()->isPointerType())
1951 std::swap(PExp, IExp);
1952
1953 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1954 if (IExp->getType()->isIntegerType()) {
1955 // Check for arithmetic on pointers to incomplete types
1956 if (!PTy->getPointeeType()->isObjectType()) {
1957 if (PTy->getPointeeType()->isVoidType()) {
1958 Diag(loc, diag::ext_gnu_void_ptr,
1959 lex->getSourceRange(), rex->getSourceRange());
1960 } else {
1961 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1962 lex->getType().getAsString(), lex->getSourceRange());
1963 return QualType();
1964 }
1965 }
1966 return PExp->getType();
1967 }
1968 }
1969
Chris Lattner2c8bff72007-12-12 05:47:28 +00001970 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001971}
1972
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001973// C99 6.5.6
1974QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1975 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001976 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1977 return CheckVectorOperands(loc, lex, rex);
1978
Steve Naroff8f708362007-08-24 19:07:16 +00001979 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001980
Chris Lattnerf6da2912007-12-09 21:53:25 +00001981 // Enforce type constraints: C99 6.5.6p3.
1982
1983 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001984 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001985 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001986
1987 // Either ptr - int or ptr - ptr.
1988 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001989 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001990
Chris Lattnerf6da2912007-12-09 21:53:25 +00001991 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001992 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001993 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001994 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001995 Diag(loc, diag::ext_gnu_void_ptr,
1996 lex->getSourceRange(), rex->getSourceRange());
1997 } else {
1998 Diag(loc, diag::err_typecheck_sub_ptr_object,
1999 lex->getType().getAsString(), lex->getSourceRange());
2000 return QualType();
2001 }
2002 }
2003
2004 // The result type of a pointer-int computation is the pointer type.
2005 if (rex->getType()->isIntegerType())
2006 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002007
Chris Lattnerf6da2912007-12-09 21:53:25 +00002008 // Handle pointer-pointer subtractions.
2009 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002010 QualType rpointee = RHSPTy->getPointeeType();
2011
Chris Lattnerf6da2912007-12-09 21:53:25 +00002012 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002013 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002014 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002015 if (rpointee->isVoidType()) {
2016 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00002017 Diag(loc, diag::ext_gnu_void_ptr,
2018 lex->getSourceRange(), rex->getSourceRange());
2019 } else {
2020 Diag(loc, diag::err_typecheck_sub_ptr_object,
2021 rex->getType().getAsString(), rex->getSourceRange());
2022 return QualType();
2023 }
2024 }
2025
2026 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002027 if (!Context.typesAreCompatible(
2028 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2029 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002030 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2031 lex->getType().getAsString(), rex->getType().getAsString(),
2032 lex->getSourceRange(), rex->getSourceRange());
2033 return QualType();
2034 }
2035
2036 return Context.getPointerDiffType();
2037 }
2038 }
2039
Chris Lattner2c8bff72007-12-12 05:47:28 +00002040 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002041}
2042
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002043// C99 6.5.7
2044QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2045 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002046 // C99 6.5.7p2: Each of the operands shall have integer type.
2047 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2048 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002049
Chris Lattner2c8bff72007-12-12 05:47:28 +00002050 // Shifts don't perform usual arithmetic conversions, they just do integer
2051 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002052 if (!isCompAssign)
2053 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002054 UsualUnaryConversions(rex);
2055
2056 // "The type of the result is that of the promoted left operand."
2057 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002058}
2059
Eli Friedman0d9549b2008-08-22 00:56:42 +00002060static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2061 ASTContext& Context) {
2062 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2063 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2064 // ID acts sort of like void* for ObjC interfaces
2065 if (LHSIface && Context.isObjCIdType(RHS))
2066 return true;
2067 if (RHSIface && Context.isObjCIdType(LHS))
2068 return true;
2069 if (!LHSIface || !RHSIface)
2070 return false;
2071 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2072 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2073}
2074
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002075// C99 6.5.8
2076QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2077 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002078 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2079 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2080
Chris Lattner254f3bc2007-08-26 01:18:55 +00002081 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002082 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2083 UsualArithmeticConversions(lex, rex);
2084 else {
2085 UsualUnaryConversions(lex);
2086 UsualUnaryConversions(rex);
2087 }
Chris Lattner4b009652007-07-25 00:24:17 +00002088 QualType lType = lex->getType();
2089 QualType rType = rex->getType();
2090
Ted Kremenek486509e2007-10-29 17:13:39 +00002091 // For non-floating point types, check for self-comparisons of the form
2092 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2093 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002094 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002095 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2096 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002097 if (DRL->getDecl() == DRR->getDecl())
2098 Diag(loc, diag::warn_selfcomparison);
2099 }
2100
Chris Lattner254f3bc2007-08-26 01:18:55 +00002101 if (isRelational) {
2102 if (lType->isRealType() && rType->isRealType())
2103 return Context.IntTy;
2104 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002105 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002106 if (lType->isFloatingType()) {
2107 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00002108 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002109 }
2110
Chris Lattner254f3bc2007-08-26 01:18:55 +00002111 if (lType->isArithmeticType() && rType->isArithmeticType())
2112 return Context.IntTy;
2113 }
Chris Lattner4b009652007-07-25 00:24:17 +00002114
Chris Lattner22be8422007-08-26 01:10:14 +00002115 bool LHSIsNull = lex->isNullPointerConstant(Context);
2116 bool RHSIsNull = rex->isNullPointerConstant(Context);
2117
Chris Lattner254f3bc2007-08-26 01:18:55 +00002118 // All of the following pointer related warnings are GCC extensions, except
2119 // when handling null pointer constants. One day, we can consider making them
2120 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002121 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002122 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002123 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002124 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002125 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002126
Steve Naroff3b435622007-11-13 14:57:38 +00002127 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002128 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2129 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002130 RCanPointeeTy.getUnqualifiedType()) &&
2131 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002132 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2133 lType.getAsString(), rType.getAsString(),
2134 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002135 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002136 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002137 return Context.IntTy;
2138 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002139 // Handle block pointer types.
2140 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2141 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2142 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2143
2144 if (!LHSIsNull && !RHSIsNull &&
2145 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2146 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2147 lType.getAsString(), rType.getAsString(),
2148 lex->getSourceRange(), rex->getSourceRange());
2149 }
2150 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2151 return Context.IntTy;
2152 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002153 // Allow block pointers to be compared with null pointer constants.
2154 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2155 (lType->isPointerType() && rType->isBlockPointerType())) {
2156 if (!LHSIsNull && !RHSIsNull) {
2157 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2158 lType.getAsString(), rType.getAsString(),
2159 lex->getSourceRange(), rex->getSourceRange());
2160 }
2161 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2162 return Context.IntTy;
2163 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002164
Steve Naroff936c4362008-06-03 14:04:54 +00002165 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002166 if (lType->isPointerType() || rType->isPointerType()) {
2167 if (!Context.typesAreCompatible(lType, rType)) {
2168 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2169 lType.getAsString(), rType.getAsString(),
2170 lex->getSourceRange(), rex->getSourceRange());
2171 ImpCastExprToType(rex, lType);
2172 return Context.IntTy;
2173 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002174 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002175 return Context.IntTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002176 }
Steve Naroff936c4362008-06-03 14:04:54 +00002177 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2178 ImpCastExprToType(rex, lType);
2179 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002180 } else {
2181 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2182 Diag(loc, diag::warn_incompatible_qualified_id_operands,
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002183 lType.getAsString(), rType.getAsString(),
Steve Naroff19608432008-10-14 22:18:38 +00002184 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002185 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002186 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002187 }
Steve Naroff936c4362008-06-03 14:04:54 +00002188 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002189 }
Steve Naroff936c4362008-06-03 14:04:54 +00002190 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2191 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002192 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002193 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2194 lType.getAsString(), rType.getAsString(),
2195 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002196 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002197 return Context.IntTy;
2198 }
Steve Naroff936c4362008-06-03 14:04:54 +00002199 if (lType->isIntegerType() &&
2200 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002201 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002202 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2203 lType.getAsString(), rType.getAsString(),
2204 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002205 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002206 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002207 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002208 // Handle block pointers.
2209 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2210 if (!RHSIsNull)
2211 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2212 lType.getAsString(), rType.getAsString(),
2213 lex->getSourceRange(), rex->getSourceRange());
2214 ImpCastExprToType(rex, lType); // promote the integer to pointer
2215 return Context.IntTy;
2216 }
2217 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2218 if (!LHSIsNull)
2219 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2220 lType.getAsString(), rType.getAsString(),
2221 lex->getSourceRange(), rex->getSourceRange());
2222 ImpCastExprToType(lex, rType); // promote the integer to pointer
2223 return Context.IntTy;
2224 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002225 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002226}
2227
Nate Begemanc5f0f652008-07-14 18:02:46 +00002228/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2229/// operates on extended vector types. Instead of producing an IntTy result,
2230/// like a scalar comparison, a vector comparison produces a vector of integer
2231/// types.
2232QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2233 SourceLocation loc,
2234 bool isRelational) {
2235 // Check to make sure we're operating on vectors of the same type and width,
2236 // Allowing one side to be a scalar of element type.
2237 QualType vType = CheckVectorOperands(loc, lex, rex);
2238 if (vType.isNull())
2239 return vType;
2240
2241 QualType lType = lex->getType();
2242 QualType rType = rex->getType();
2243
2244 // For non-floating point types, check for self-comparisons of the form
2245 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2246 // often indicate logic errors in the program.
2247 if (!lType->isFloatingType()) {
2248 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2249 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2250 if (DRL->getDecl() == DRR->getDecl())
2251 Diag(loc, diag::warn_selfcomparison);
2252 }
2253
2254 // Check for comparisons of floating point operands using != and ==.
2255 if (!isRelational && lType->isFloatingType()) {
2256 assert (rType->isFloatingType());
2257 CheckFloatComparison(loc,lex,rex);
2258 }
2259
2260 // Return the type for the comparison, which is the same as vector type for
2261 // integer vectors, or an integer type of identical size and number of
2262 // elements for floating point vectors.
2263 if (lType->isIntegerType())
2264 return lType;
2265
2266 const VectorType *VTy = lType->getAsVectorType();
2267
2268 // FIXME: need to deal with non-32b int / non-64b long long
2269 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2270 if (TypeSize == 32) {
2271 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2272 }
2273 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2274 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2275}
2276
Chris Lattner4b009652007-07-25 00:24:17 +00002277inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002278 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002279{
2280 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2281 return CheckVectorOperands(loc, lex, rex);
2282
Steve Naroff8f708362007-08-24 19:07:16 +00002283 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002284
2285 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002286 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002287 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002288}
2289
2290inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2291 Expr *&lex, Expr *&rex, SourceLocation loc)
2292{
2293 UsualUnaryConversions(lex);
2294 UsualUnaryConversions(rex);
2295
Eli Friedmanbea3f842008-05-13 20:16:47 +00002296 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002297 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002298 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002299}
2300
2301inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002302 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002303{
2304 QualType lhsType = lex->getType();
2305 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002306 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002307
2308 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002309 case Expr::MLV_Valid:
2310 break;
2311 case Expr::MLV_ConstQualified:
2312 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2313 return QualType();
2314 case Expr::MLV_ArrayType:
2315 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2316 lhsType.getAsString(), lex->getSourceRange());
2317 return QualType();
2318 case Expr::MLV_NotObjectType:
2319 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2320 lhsType.getAsString(), lex->getSourceRange());
2321 return QualType();
2322 case Expr::MLV_InvalidExpression:
2323 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2324 lex->getSourceRange());
2325 return QualType();
2326 case Expr::MLV_IncompleteType:
2327 case Expr::MLV_IncompleteVoidType:
2328 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2329 lhsType.getAsString(), lex->getSourceRange());
2330 return QualType();
2331 case Expr::MLV_DuplicateVectorComponents:
2332 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2333 lex->getSourceRange());
2334 return QualType();
Steve Naroff076d6cb2008-09-26 14:41:28 +00002335 case Expr::MLV_NotBlockQualified:
2336 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2337 lex->getSourceRange());
2338 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002339 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002340
Chris Lattner005ed752008-01-04 18:04:52 +00002341 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002342 if (compoundType.isNull()) {
2343 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002344 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002345
2346 // If the RHS is a unary plus or minus, check to see if they = and + are
2347 // right next to each other. If so, the user may have typo'd "x =+ 4"
2348 // instead of "x += 4".
2349 Expr *RHSCheck = rex;
2350 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2351 RHSCheck = ICE->getSubExpr();
2352 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2353 if ((UO->getOpcode() == UnaryOperator::Plus ||
2354 UO->getOpcode() == UnaryOperator::Minus) &&
2355 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2356 // Only if the two operators are exactly adjacent.
2357 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2358 Diag(loc, diag::warn_not_compound_assign,
2359 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2360 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2361 }
2362 } else {
2363 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002364 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002365 }
Chris Lattner005ed752008-01-04 18:04:52 +00002366
2367 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2368 rex, "assigning"))
2369 return QualType();
2370
Chris Lattner4b009652007-07-25 00:24:17 +00002371 // C99 6.5.16p3: The type of an assignment expression is the type of the
2372 // left operand unless the left operand has qualified type, in which case
2373 // it is the unqualified version of the type of the left operand.
2374 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2375 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002376 // C++ 5.17p1: the type of the assignment expression is that of its left
2377 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002378 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002379}
2380
2381inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2382 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002383
2384 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2385 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002386 return rex->getType();
2387}
2388
2389/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2390/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2391QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2392 QualType resType = op->getType();
2393 assert(!resType.isNull() && "no type for increment/decrement expression");
2394
Steve Naroffd30e1932007-08-24 17:20:07 +00002395 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002396 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002397 if (pt->getPointeeType()->isVoidType()) {
2398 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2399 } else if (!pt->getPointeeType()->isObjectType()) {
2400 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002401 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2402 resType.getAsString(), op->getSourceRange());
2403 return QualType();
2404 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002405 } else if (!resType->isRealType()) {
2406 if (resType->isComplexType())
2407 // C99 does not support ++/-- on complex types.
2408 Diag(OpLoc, diag::ext_integer_increment_complex,
2409 resType.getAsString(), op->getSourceRange());
2410 else {
2411 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2412 resType.getAsString(), op->getSourceRange());
2413 return QualType();
2414 }
Chris Lattner4b009652007-07-25 00:24:17 +00002415 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002416 // At this point, we know we have a real, complex or pointer type.
2417 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002418 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002419 if (mlval != Expr::MLV_Valid) {
2420 // FIXME: emit a more precise diagnostic...
2421 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2422 op->getSourceRange());
2423 return QualType();
2424 }
2425 return resType;
2426}
2427
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002428/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002429/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002430/// where the declaration is needed for type checking. We only need to
2431/// handle cases when the expression references a function designator
2432/// or is an lvalue. Here are some examples:
2433/// - &(x) => x
2434/// - &*****f => f for f a function designator.
2435/// - &s.xx => s
2436/// - &s.zz[1].yy -> s, if zz is an array
2437/// - *(x + 1) -> x, if x is an array
2438/// - &"123"[2] -> 0
2439/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002440static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002441 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002442 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002443 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002444 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002445 // Fields cannot be declared with a 'register' storage class.
2446 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002447 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002448 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002449 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002450 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002451 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002452
Douglas Gregord2baafd2008-10-21 16:13:35 +00002453 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002454 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002455 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002456 return 0;
2457 else
2458 return VD;
2459 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002460 case Stmt::UnaryOperatorClass: {
2461 UnaryOperator *UO = cast<UnaryOperator>(E);
2462
2463 switch(UO->getOpcode()) {
2464 case UnaryOperator::Deref: {
2465 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002466 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2467 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2468 if (!VD || VD->getType()->isPointerType())
2469 return 0;
2470 return VD;
2471 }
2472 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002473 }
2474 case UnaryOperator::Real:
2475 case UnaryOperator::Imag:
2476 case UnaryOperator::Extension:
2477 return getPrimaryDecl(UO->getSubExpr());
2478 default:
2479 return 0;
2480 }
2481 }
2482 case Stmt::BinaryOperatorClass: {
2483 BinaryOperator *BO = cast<BinaryOperator>(E);
2484
2485 // Handle cases involving pointer arithmetic. The result of an
2486 // Assign or AddAssign is not an lvalue so they can be ignored.
2487
2488 // (x + n) or (n + x) => x
2489 if (BO->getOpcode() == BinaryOperator::Add) {
2490 if (BO->getLHS()->getType()->isPointerType()) {
2491 return getPrimaryDecl(BO->getLHS());
2492 } else if (BO->getRHS()->getType()->isPointerType()) {
2493 return getPrimaryDecl(BO->getRHS());
2494 }
2495 }
2496
2497 return 0;
2498 }
Chris Lattner4b009652007-07-25 00:24:17 +00002499 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002500 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002501 case Stmt::ImplicitCastExprClass:
2502 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002503 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002504 default:
2505 return 0;
2506 }
2507}
2508
2509/// CheckAddressOfOperand - The operand of & must be either a function
2510/// designator or an lvalue designating an object. If it is an lvalue, the
2511/// object cannot be declared with storage class register or be a bit field.
2512/// Note: The usual conversions are *not* applied to the operand of the &
2513/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002514/// In C++, the operand might be an overloaded function name, in which case
2515/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002516QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002517 if (getLangOptions().C99) {
2518 // Implement C99-only parts of addressof rules.
2519 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2520 if (uOp->getOpcode() == UnaryOperator::Deref)
2521 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2522 // (assuming the deref expression is valid).
2523 return uOp->getSubExpr()->getType();
2524 }
2525 // Technically, there should be a check for array subscript
2526 // expressions here, but the result of one is always an lvalue anyway.
2527 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002528 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002529 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002530
2531 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002532 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2533 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002534 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2535 op->getSourceRange());
2536 return QualType();
2537 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002538 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2539 if (MemExpr->getMemberDecl()->isBitField()) {
2540 Diag(OpLoc, diag::err_typecheck_address_of,
2541 std::string("bit-field"), op->getSourceRange());
2542 return QualType();
2543 }
2544 // Check for Apple extension for accessing vector components.
2545 } else if (isa<ArraySubscriptExpr>(op) &&
2546 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2547 Diag(OpLoc, diag::err_typecheck_address_of,
2548 std::string("vector"), op->getSourceRange());
2549 return QualType();
2550 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002551 // We have an lvalue with a decl. Make sure the decl is not declared
2552 // with the register storage-class specifier.
2553 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2554 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002555 Diag(OpLoc, diag::err_typecheck_address_of,
2556 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002557 return QualType();
2558 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002559 } else if (isa<OverloadedFunctionDecl>(dcl))
2560 return Context.OverloadTy;
2561 else
Chris Lattner4b009652007-07-25 00:24:17 +00002562 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002563 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002564
Chris Lattner4b009652007-07-25 00:24:17 +00002565 // If the operand has type "type", the result has type "pointer to type".
2566 return Context.getPointerType(op->getType());
2567}
2568
2569QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2570 UsualUnaryConversions(op);
2571 QualType qType = op->getType();
2572
Chris Lattner7931f4a2007-07-31 16:53:04 +00002573 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002574 // Note that per both C89 and C99, this is always legal, even
2575 // if ptype is an incomplete type or void.
2576 // It would be possible to warn about dereferencing a
2577 // void pointer, but it's completely well-defined,
2578 // and such a warning is unlikely to catch any mistakes.
2579 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002580 }
2581 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2582 qType.getAsString(), op->getSourceRange());
2583 return QualType();
2584}
2585
2586static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2587 tok::TokenKind Kind) {
2588 BinaryOperator::Opcode Opc;
2589 switch (Kind) {
2590 default: assert(0 && "Unknown binop!");
2591 case tok::star: Opc = BinaryOperator::Mul; break;
2592 case tok::slash: Opc = BinaryOperator::Div; break;
2593 case tok::percent: Opc = BinaryOperator::Rem; break;
2594 case tok::plus: Opc = BinaryOperator::Add; break;
2595 case tok::minus: Opc = BinaryOperator::Sub; break;
2596 case tok::lessless: Opc = BinaryOperator::Shl; break;
2597 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2598 case tok::lessequal: Opc = BinaryOperator::LE; break;
2599 case tok::less: Opc = BinaryOperator::LT; break;
2600 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2601 case tok::greater: Opc = BinaryOperator::GT; break;
2602 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2603 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2604 case tok::amp: Opc = BinaryOperator::And; break;
2605 case tok::caret: Opc = BinaryOperator::Xor; break;
2606 case tok::pipe: Opc = BinaryOperator::Or; break;
2607 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2608 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2609 case tok::equal: Opc = BinaryOperator::Assign; break;
2610 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2611 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2612 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2613 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2614 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2615 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2616 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2617 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2618 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2619 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2620 case tok::comma: Opc = BinaryOperator::Comma; break;
2621 }
2622 return Opc;
2623}
2624
2625static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2626 tok::TokenKind Kind) {
2627 UnaryOperator::Opcode Opc;
2628 switch (Kind) {
2629 default: assert(0 && "Unknown unary op!");
2630 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2631 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2632 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2633 case tok::star: Opc = UnaryOperator::Deref; break;
2634 case tok::plus: Opc = UnaryOperator::Plus; break;
2635 case tok::minus: Opc = UnaryOperator::Minus; break;
2636 case tok::tilde: Opc = UnaryOperator::Not; break;
2637 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2638 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2639 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2640 case tok::kw___real: Opc = UnaryOperator::Real; break;
2641 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2642 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2643 }
2644 return Opc;
2645}
2646
Douglas Gregord7f915e2008-11-06 23:29:22 +00002647/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2648/// operator @p Opc at location @c TokLoc. This routine only supports
2649/// built-in operations; ActOnBinOp handles overloaded operators.
2650Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2651 unsigned Op,
2652 Expr *lhs, Expr *rhs) {
2653 QualType ResultTy; // Result type of the binary operator.
2654 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2655 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2656
2657 switch (Opc) {
2658 default:
2659 assert(0 && "Unknown binary expr!");
2660 case BinaryOperator::Assign:
2661 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2662 break;
2663 case BinaryOperator::Mul:
2664 case BinaryOperator::Div:
2665 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2666 break;
2667 case BinaryOperator::Rem:
2668 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2669 break;
2670 case BinaryOperator::Add:
2671 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2672 break;
2673 case BinaryOperator::Sub:
2674 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2675 break;
2676 case BinaryOperator::Shl:
2677 case BinaryOperator::Shr:
2678 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2679 break;
2680 case BinaryOperator::LE:
2681 case BinaryOperator::LT:
2682 case BinaryOperator::GE:
2683 case BinaryOperator::GT:
2684 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2685 break;
2686 case BinaryOperator::EQ:
2687 case BinaryOperator::NE:
2688 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2689 break;
2690 case BinaryOperator::And:
2691 case BinaryOperator::Xor:
2692 case BinaryOperator::Or:
2693 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2694 break;
2695 case BinaryOperator::LAnd:
2696 case BinaryOperator::LOr:
2697 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2698 break;
2699 case BinaryOperator::MulAssign:
2700 case BinaryOperator::DivAssign:
2701 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2702 if (!CompTy.isNull())
2703 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2704 break;
2705 case BinaryOperator::RemAssign:
2706 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2707 if (!CompTy.isNull())
2708 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2709 break;
2710 case BinaryOperator::AddAssign:
2711 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2712 if (!CompTy.isNull())
2713 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2714 break;
2715 case BinaryOperator::SubAssign:
2716 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2717 if (!CompTy.isNull())
2718 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2719 break;
2720 case BinaryOperator::ShlAssign:
2721 case BinaryOperator::ShrAssign:
2722 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2723 if (!CompTy.isNull())
2724 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2725 break;
2726 case BinaryOperator::AndAssign:
2727 case BinaryOperator::XorAssign:
2728 case BinaryOperator::OrAssign:
2729 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2730 if (!CompTy.isNull())
2731 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2732 break;
2733 case BinaryOperator::Comma:
2734 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2735 break;
2736 }
2737 if (ResultTy.isNull())
2738 return true;
2739 if (CompTy.isNull())
2740 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2741 else
2742 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2743}
2744
Chris Lattner4b009652007-07-25 00:24:17 +00002745// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002746Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2747 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002748 ExprTy *LHS, ExprTy *RHS) {
2749 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2750 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2751
Steve Naroff87d58b42007-09-16 03:34:24 +00002752 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2753 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002754
Douglas Gregord7f915e2008-11-06 23:29:22 +00002755 if (getLangOptions().CPlusPlus &&
2756 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2757 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
2758 // C++ [over.binary]p1:
2759 // A binary operator shall be implemented either by a non-static
2760 // member function (9.3) with one parameter or by a non-member
2761 // function with two parameters. Thus, for any binary operator
2762 // @, x@y can be interpreted as either x.operator@(y) or
2763 // operator@(x,y). If both forms of the operator function have
2764 // been declared, the rules in 13.3.1.2 determines which, if
2765 // any, interpretation is used.
2766 OverloadCandidateSet CandidateSet;
2767
2768 // Determine which overloaded operator we're dealing with.
2769 static const OverloadedOperatorKind OverOps[] = {
2770 OO_Star, OO_Slash, OO_Percent,
2771 OO_Plus, OO_Minus,
2772 OO_LessLess, OO_GreaterGreater,
2773 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2774 OO_EqualEqual, OO_ExclaimEqual,
2775 OO_Amp,
2776 OO_Caret,
2777 OO_Pipe,
2778 OO_AmpAmp,
2779 OO_PipePipe,
2780 OO_Equal, OO_StarEqual,
2781 OO_SlashEqual, OO_PercentEqual,
2782 OO_PlusEqual, OO_MinusEqual,
2783 OO_LessLessEqual, OO_GreaterGreaterEqual,
2784 OO_AmpEqual, OO_CaretEqual,
2785 OO_PipeEqual,
2786 OO_Comma
2787 };
2788 OverloadedOperatorKind OverOp = OverOps[Opc];
2789
2790 // Lookup this operator.
2791 Decl *D = LookupDecl(&PP.getIdentifierTable().getOverloadedOperator(OverOp),
2792 Decl::IDNS_Ordinary, S);
2793
2794 // Add any overloaded operators we find to the overload set.
2795 Expr *Args[2] = { lhs, rhs };
2796 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2797 AddOverloadCandidate(FD, Args, 2, CandidateSet);
2798 else if (OverloadedFunctionDecl *Ovl
2799 = dyn_cast_or_null<OverloadedFunctionDecl>(D))
2800 AddOverloadCandidates(Ovl, Args, 2, CandidateSet);
2801
2802 // FIXME: Add builtin overload candidates (C++ [over.built]).
2803
2804 // Perform overload resolution.
2805 OverloadCandidateSet::iterator Best;
2806 switch (BestViableFunction(CandidateSet, Best)) {
2807 case OR_Success: {
2808 // FIXME: We might find a built-in candidate here.
2809 FunctionDecl *FnDecl = Best->Function;
2810
2811 // Convert the arguments.
2812 // FIXME: Conversion will be different for member operators.
2813 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
2814 "passing") ||
2815 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
2816 "passing"))
2817 return true;
2818
2819 // Determine the result type
2820 QualType ResultTy
2821 = FnDecl->getType()->getAsFunctionType()->getResultType();
2822 ResultTy = ResultTy.getNonReferenceType();
2823
2824 // Build the actual expression node.
2825 // FIXME: We lose the fact that we have a function here!
2826 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
2827 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, ResultTy,
2828 TokLoc);
2829 else
2830 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
2831 }
2832
2833 case OR_No_Viable_Function:
2834 // No viable function; fall through to handling this as a
2835 // built-in operator.
2836 break;
2837
2838 case OR_Ambiguous:
2839 Diag(TokLoc,
2840 diag::err_ovl_ambiguous_oper,
2841 BinaryOperator::getOpcodeStr(Opc),
2842 lhs->getSourceRange(), rhs->getSourceRange());
2843 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2844 return true;
2845 }
2846
2847 // There was no viable overloaded operator; fall through.
2848 }
2849
Chris Lattner4b009652007-07-25 00:24:17 +00002850
Douglas Gregord7f915e2008-11-06 23:29:22 +00002851 // Build a built-in binary operation.
2852 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00002853}
2854
2855// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002856Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002857 ExprTy *input) {
2858 Expr *Input = (Expr*)input;
2859 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2860 QualType resultType;
2861 switch (Opc) {
2862 default:
2863 assert(0 && "Unimplemented unary expr!");
2864 case UnaryOperator::PreInc:
2865 case UnaryOperator::PreDec:
2866 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2867 break;
2868 case UnaryOperator::AddrOf:
2869 resultType = CheckAddressOfOperand(Input, OpLoc);
2870 break;
2871 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002872 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002873 resultType = CheckIndirectionOperand(Input, OpLoc);
2874 break;
2875 case UnaryOperator::Plus:
2876 case UnaryOperator::Minus:
2877 UsualUnaryConversions(Input);
2878 resultType = Input->getType();
2879 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2880 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2881 resultType.getAsString());
2882 break;
2883 case UnaryOperator::Not: // bitwise complement
2884 UsualUnaryConversions(Input);
2885 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002886 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2887 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2888 // C99 does not support '~' for complex conjugation.
2889 Diag(OpLoc, diag::ext_integer_complement_complex,
2890 resultType.getAsString(), Input->getSourceRange());
2891 else if (!resultType->isIntegerType())
2892 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2893 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002894 break;
2895 case UnaryOperator::LNot: // logical negation
2896 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2897 DefaultFunctionArrayConversion(Input);
2898 resultType = Input->getType();
2899 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2900 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2901 resultType.getAsString());
2902 // LNot always has type int. C99 6.5.3.3p5.
2903 resultType = Context.IntTy;
2904 break;
2905 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002906 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2907 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002908 break;
2909 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002910 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2911 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002912 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002913 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002914 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002915 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002916 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002917 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002918 resultType = Input->getType();
2919 break;
2920 }
2921 if (resultType.isNull())
2922 return true;
2923 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2924}
2925
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002926/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2927Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002928 SourceLocation LabLoc,
2929 IdentifierInfo *LabelII) {
2930 // Look up the record for this label identifier.
2931 LabelStmt *&LabelDecl = LabelMap[LabelII];
2932
Daniel Dunbar879788d2008-08-04 16:51:22 +00002933 // If we haven't seen this label yet, create a forward reference. It
2934 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002935 if (LabelDecl == 0)
2936 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2937
2938 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002939 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2940 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002941}
2942
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002943Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002944 SourceLocation RPLoc) { // "({..})"
2945 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2946 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2947 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2948
2949 // FIXME: there are a variety of strange constraints to enforce here, for
2950 // example, it is not possible to goto into a stmt expression apparently.
2951 // More semantic analysis is needed.
2952
2953 // FIXME: the last statement in the compount stmt has its value used. We
2954 // should not warn about it being unused.
2955
2956 // If there are sub stmts in the compound stmt, take the type of the last one
2957 // as the type of the stmtexpr.
2958 QualType Ty = Context.VoidTy;
2959
Chris Lattner200964f2008-07-26 19:51:01 +00002960 if (!Compound->body_empty()) {
2961 Stmt *LastStmt = Compound->body_back();
2962 // If LastStmt is a label, skip down through into the body.
2963 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2964 LastStmt = Label->getSubStmt();
2965
2966 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002967 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002968 }
Chris Lattner4b009652007-07-25 00:24:17 +00002969
2970 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2971}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002972
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002973Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002974 SourceLocation TypeLoc,
2975 TypeTy *argty,
2976 OffsetOfComponent *CompPtr,
2977 unsigned NumComponents,
2978 SourceLocation RPLoc) {
2979 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2980 assert(!ArgTy.isNull() && "Missing type argument!");
2981
2982 // We must have at least one component that refers to the type, and the first
2983 // one is known to be a field designator. Verify that the ArgTy represents
2984 // a struct/union/class.
2985 if (!ArgTy->isRecordType())
2986 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2987
2988 // Otherwise, create a compound literal expression as the base, and
2989 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002990 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002991
Chris Lattnerb37522e2007-08-31 21:49:13 +00002992 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2993 // GCC extension, diagnose them.
2994 if (NumComponents != 1)
2995 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2996 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2997
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002998 for (unsigned i = 0; i != NumComponents; ++i) {
2999 const OffsetOfComponent &OC = CompPtr[i];
3000 if (OC.isBrackets) {
3001 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003002 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003003 if (!AT) {
3004 delete Res;
3005 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
3006 Res->getType().getAsString());
3007 }
3008
Chris Lattner2af6a802007-08-30 17:59:59 +00003009 // FIXME: C++: Verify that operator[] isn't overloaded.
3010
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003011 // C99 6.5.2.1p1
3012 Expr *Idx = static_cast<Expr*>(OC.U.E);
3013 if (!Idx->getType()->isIntegerType())
3014 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
3015 Idx->getSourceRange());
3016
3017 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3018 continue;
3019 }
3020
3021 const RecordType *RC = Res->getType()->getAsRecordType();
3022 if (!RC) {
3023 delete Res;
3024 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
3025 Res->getType().getAsString());
3026 }
3027
3028 // Get the decl corresponding to this.
3029 RecordDecl *RD = RC->getDecl();
3030 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3031 if (!MemberDecl)
3032 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
3033 OC.U.IdentInfo->getName(),
3034 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00003035
3036 // FIXME: C++: Verify that MemberDecl isn't a static field.
3037 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003038 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3039 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003040 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3041 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003042 }
3043
3044 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3045 BuiltinLoc);
3046}
3047
3048
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003049Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003050 TypeTy *arg1, TypeTy *arg2,
3051 SourceLocation RPLoc) {
3052 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3053 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3054
3055 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3056
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003057 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003058}
3059
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003060Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003061 ExprTy *expr1, ExprTy *expr2,
3062 SourceLocation RPLoc) {
3063 Expr *CondExpr = static_cast<Expr*>(cond);
3064 Expr *LHSExpr = static_cast<Expr*>(expr1);
3065 Expr *RHSExpr = static_cast<Expr*>(expr2);
3066
3067 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3068
3069 // The conditional expression is required to be a constant expression.
3070 llvm::APSInt condEval(32);
3071 SourceLocation ExpLoc;
3072 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
3073 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
3074 CondExpr->getSourceRange());
3075
3076 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3077 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3078 RHSExpr->getType();
3079 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3080}
3081
Steve Naroff52a81c02008-09-03 18:15:37 +00003082//===----------------------------------------------------------------------===//
3083// Clang Extensions.
3084//===----------------------------------------------------------------------===//
3085
3086/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003087void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003088 // Analyze block parameters.
3089 BlockSemaInfo *BSI = new BlockSemaInfo();
3090
3091 // Add BSI to CurBlock.
3092 BSI->PrevBlockInfo = CurBlock;
3093 CurBlock = BSI;
3094
3095 BSI->ReturnType = 0;
3096 BSI->TheScope = BlockScope;
3097
Steve Naroff52059382008-10-10 01:28:17 +00003098 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3099 PushDeclContext(BSI->TheDecl);
3100}
3101
3102void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003103 // Analyze arguments to block.
3104 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3105 "Not a function declarator!");
3106 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3107
Steve Naroff52059382008-10-10 01:28:17 +00003108 CurBlock->hasPrototype = FTI.hasPrototype;
3109 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003110
3111 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3112 // no arguments, not a function that takes a single void argument.
3113 if (FTI.hasPrototype &&
3114 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3115 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3116 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3117 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003118 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003119 } else if (FTI.hasPrototype) {
3120 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003121 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3122 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003123 }
Steve Naroff52059382008-10-10 01:28:17 +00003124 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3125
3126 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3127 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3128 // If this has an identifier, add it to the scope stack.
3129 if ((*AI)->getIdentifier())
3130 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003131}
3132
3133/// ActOnBlockError - If there is an error parsing a block, this callback
3134/// is invoked to pop the information about the block from the action impl.
3135void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3136 // Ensure that CurBlock is deleted.
3137 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3138
3139 // Pop off CurBlock, handle nested blocks.
3140 CurBlock = CurBlock->PrevBlockInfo;
3141
3142 // FIXME: Delete the ParmVarDecl objects as well???
3143
3144}
3145
3146/// ActOnBlockStmtExpr - This is called when the body of a block statement
3147/// literal was successfully completed. ^(int x){...}
3148Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3149 Scope *CurScope) {
3150 // Ensure that CurBlock is deleted.
3151 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3152 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3153
Steve Naroff52059382008-10-10 01:28:17 +00003154 PopDeclContext();
3155
Steve Naroff52a81c02008-09-03 18:15:37 +00003156 // Pop off CurBlock, handle nested blocks.
3157 CurBlock = CurBlock->PrevBlockInfo;
3158
3159 QualType RetTy = Context.VoidTy;
3160 if (BSI->ReturnType)
3161 RetTy = QualType(BSI->ReturnType, 0);
3162
3163 llvm::SmallVector<QualType, 8> ArgTypes;
3164 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3165 ArgTypes.push_back(BSI->Params[i]->getType());
3166
3167 QualType BlockTy;
3168 if (!BSI->hasPrototype)
3169 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3170 else
3171 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003172 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003173
3174 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003175
Steve Naroff95029d92008-10-08 18:44:00 +00003176 BSI->TheDecl->setBody(Body.take());
3177 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003178}
3179
Nate Begemanbd881ef2008-01-30 20:50:20 +00003180/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003181/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003182/// The number of arguments has already been validated to match the number of
3183/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003184static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3185 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003186 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003187 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003188 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3189 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003190
3191 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003192 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003193 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003194 return true;
3195}
3196
3197Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3198 SourceLocation *CommaLocs,
3199 SourceLocation BuiltinLoc,
3200 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003201 // __builtin_overload requires at least 2 arguments
3202 if (NumArgs < 2)
3203 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3204 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003205
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003206 // The first argument is required to be a constant expression. It tells us
3207 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003208 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003209 Expr *NParamsExpr = Args[0];
3210 llvm::APSInt constEval(32);
3211 SourceLocation ExpLoc;
3212 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3213 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3214 NParamsExpr->getSourceRange());
3215
3216 // Verify that the number of parameters is > 0
3217 unsigned NumParams = constEval.getZExtValue();
3218 if (NumParams == 0)
3219 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3220 NParamsExpr->getSourceRange());
3221 // Verify that we have at least 1 + NumParams arguments to the builtin.
3222 if ((NumParams + 1) > NumArgs)
3223 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3224 SourceRange(BuiltinLoc, RParenLoc));
3225
3226 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003227 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003228 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003229 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3230 // UsualUnaryConversions will convert the function DeclRefExpr into a
3231 // pointer to function.
3232 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003233 const FunctionTypeProto *FnType = 0;
3234 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3235 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003236
3237 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3238 // parameters, and the number of parameters must match the value passed to
3239 // the builtin.
3240 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00003241 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3242 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003243
3244 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003245 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003246 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003247 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003248 if (OE)
3249 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3250 OE->getFn()->getSourceRange());
3251 // Remember our match, and continue processing the remaining arguments
3252 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003253 OE = new OverloadExpr(Args, NumArgs, i,
3254 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003255 BuiltinLoc, RParenLoc);
3256 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003257 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003258 // Return the newly created OverloadExpr node, if we succeded in matching
3259 // exactly one of the candidate functions.
3260 if (OE)
3261 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003262
3263 // If we didn't find a matching function Expr in the __builtin_overload list
3264 // the return an error.
3265 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003266 for (unsigned i = 0; i != NumParams; ++i) {
3267 if (i != 0) typeNames += ", ";
3268 typeNames += Args[i+1]->getType().getAsString();
3269 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003270
3271 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3272 SourceRange(BuiltinLoc, RParenLoc));
3273}
3274
Anders Carlsson36760332007-10-15 20:28:48 +00003275Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3276 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003277 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003278 Expr *E = static_cast<Expr*>(expr);
3279 QualType T = QualType::getFromOpaquePtr(type);
3280
3281 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003282
3283 // Get the va_list type
3284 QualType VaListType = Context.getBuiltinVaListType();
3285 // Deal with implicit array decay; for example, on x86-64,
3286 // va_list is an array, but it's supposed to decay to
3287 // a pointer for va_arg.
3288 if (VaListType->isArrayType())
3289 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003290 // Make sure the input expression also decays appropriately.
3291 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003292
3293 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003294 return Diag(E->getLocStart(),
3295 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3296 E->getType().getAsString(),
3297 E->getSourceRange());
3298
3299 // FIXME: Warn if a non-POD type is passed in.
3300
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003301 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003302}
3303
Chris Lattner005ed752008-01-04 18:04:52 +00003304bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3305 SourceLocation Loc,
3306 QualType DstType, QualType SrcType,
3307 Expr *SrcExpr, const char *Flavor) {
3308 // Decode the result (notice that AST's are still created for extensions).
3309 bool isInvalid = false;
3310 unsigned DiagKind;
3311 switch (ConvTy) {
3312 default: assert(0 && "Unknown conversion type");
3313 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003314 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003315 DiagKind = diag::ext_typecheck_convert_pointer_int;
3316 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003317 case IntToPointer:
3318 DiagKind = diag::ext_typecheck_convert_int_pointer;
3319 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003320 case IncompatiblePointer:
3321 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3322 break;
3323 case FunctionVoidPointer:
3324 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3325 break;
3326 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003327 // If the qualifiers lost were because we were applying the
3328 // (deprecated) C++ conversion from a string literal to a char*
3329 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3330 // Ideally, this check would be performed in
3331 // CheckPointerTypesForAssignment. However, that would require a
3332 // bit of refactoring (so that the second argument is an
3333 // expression, rather than a type), which should be done as part
3334 // of a larger effort to fix CheckPointerTypesForAssignment for
3335 // C++ semantics.
3336 if (getLangOptions().CPlusPlus &&
3337 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3338 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003339 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3340 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003341 case IntToBlockPointer:
3342 DiagKind = diag::err_int_to_block_pointer;
3343 break;
3344 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003345 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003346 break;
3347 case BlockVoidPointer:
3348 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3349 break;
Steve Naroff19608432008-10-14 22:18:38 +00003350 case IncompatibleObjCQualifiedId:
3351 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3352 // it can give a more specific diagnostic.
3353 DiagKind = diag::warn_incompatible_qualified_id;
3354 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003355 case Incompatible:
3356 DiagKind = diag::err_typecheck_convert_incompatible;
3357 isInvalid = true;
3358 break;
3359 }
3360
3361 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3362 SrcExpr->getSourceRange());
3363 return isInvalid;
3364}