blob: 92efa68cc434ad74da2a35153a05b764a13b833c [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Chris Lattnere7a2e912008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattnere7a2e912008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattnere7a2e912008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattnere7a2e912008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattnere7a2e912008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner05faf172008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattnere7a2e912008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
102 // For conversion purposes, we ignore any qualifiers.
103 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000104 QualType lhs =
105 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
106 QualType rhs =
107 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattnere7a2e912008-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 Narofff69936d2007-09-16 03:34:24 +0000259/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000266Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnera7ad98f2008-02-11 00:02:17 +0000276
277 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-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()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000282
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000283 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000284 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000285 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-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 Lattnera7ad98f2008-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
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
299 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000300 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000301 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 StringToks[NumStringToks-1].getLocation());
303}
304
Chris Lattner639e2d32008-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 Naroff08d92e42007-09-15 18:49:24 +0000335/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000336/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000337/// identifier is used in a function call context.
Argyrios Kyrtzidisef6e6472008-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 Naroff08d92e42007-09-15 18:49:24 +0000340Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 IdentifierInfo &II,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000342 bool HasTrailingLParen,
343 const CXXScopeSpec *SS) {
Chris Lattner8a934232008-03-31 00:36:02 +0000344 // Could be enum-constant, value decl, instance variable, etc.
Argyrios Kyrtzidisef6e6472008-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 Lattner8a934232008-03-31 00:36:02 +0000353
354 // If this reference is in an Objective-C method, then ivar lookup happens as
355 // well.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000356 if (getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000357 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-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 Naroffe8043c32008-04-01 23:04:06 +0000363 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000364 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattner123a11f2008-07-21 04:44:44 +0000365 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattner8a934232008-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 Naroff76de9d72008-08-10 19:10:41 +0000374 // Needed to implement property "super.method" notation.
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000375 if (SD == 0 && &II == SuperID) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000376 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000377 getCurMethodDecl()->getClassInterface()));
Douglas Gregorcd9b46e2008-11-04 14:56:14 +0000378 return new ObjCSuperExpr(Loc, T);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000379 }
Chris Lattner8a934232008-03-31 00:36:02 +0000380 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner8a934232008-03-31 00:36:02 +0000385 !getLangOptions().CPlusPlus) // Not in C++.
Reid Spencer5f016e22007-07-11 17:01:13 +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.
Argyrios Kyrtzidisef6e6472008-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());
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 }
396 }
Chris Lattner8a934232008-03-31 00:36:02 +0000397
Argyrios Kyrtzidis07952322008-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
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +0000412 // FIXME: Handle 'mutable'.
413 return new DeclRefExpr(FD,
414 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000415 }
416
417 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
418 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 if (isa<TypedefDecl>(D))
420 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000421 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000422 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000423 if (isa<NamespaceDecl>(D))
424 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000425
Steve Naroffdd972f22008-09-05 22:11:13 +0000426 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000427 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
428 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
429
Steve Naroffdd972f22008-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 Lattner639e2d32008-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 Naroffdd972f22008-09-05 22:11:13 +0000444 //
Chris Lattner639e2d32008-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 Naroff090276f2008-10-10 01:28:17 +0000449 // The BlocksAttr indicates the variable is bound by-reference.
450 if (VD->getAttr<BlocksAttr>())
Douglas Gregor9d293df2008-10-28 00:22:11 +0000451 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
452 Loc, true);
Steve Naroff090276f2008-10-10 01:28:17 +0000453
454 // Variable will be bound by-copy, make it const within the closure.
455 VD->getType().addConst();
Douglas Gregor9d293df2008-10-28 00:22:11 +0000456 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
457 Loc, false);
Steve Naroff090276f2008-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 Gregore0a5d5f2008-10-22 04:14:44 +0000461 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000462}
463
Chris Lattnerd9f69102008-08-10 01:53:14 +0000464Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000465 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000466 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000467
Reid Spencer5f016e22007-07-11 17:01:13 +0000468 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000469 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000474
475 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000476 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000477 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000478
Chris Lattnerfa28b302008-01-12 08:14:25 +0000479 // Pre-defined identifiers are of type char[x], where x is the length of the
480 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000481 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000482 if (getCurFunctionDecl())
483 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000484 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000485 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000486
Chris Lattner8f978d52008-01-12 19:32:28 +0000487 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000488 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000489 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000490 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000491}
492
Steve Narofff69936d2007-09-16 03:34:24 +0000493Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerfc62bfd2008-03-01 08:32:21 +0000503
504 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
505
Chris Lattnerc250aae2008-06-07 22:35:38 +0000506 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
507 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000508}
509
Steve Narofff69936d2007-09-16 03:34:24 +0000510Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000514 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000515
Chris Lattner98be4942008-03-05 18:54:05 +0000516 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000517 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000518 Context.IntTy,
519 Tok.getLocation()));
520 }
521 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000522 // Add padding so that NumericLiteralParser can overread by one character.
523 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner28997ec2008-09-30 20:51:14 +0000528
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
530 Tok.getLocation(), PP);
531 if (Literal.hadError)
532 return ExprResult(true);
533
Chris Lattner5d661452007-08-26 03:42:43 +0000534 Expr *Res;
535
536 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000537 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000538 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000539 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000540 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000541 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000542 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000543 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000544
545 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
546
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000547 // isExact will be set by GetFloatValue().
548 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000549 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000550 Ty, Tok.getLocation());
551
Chris Lattner5d661452007-08-26 03:42:43 +0000552 } else if (!Literal.isIntegerLiteral()) {
553 return ExprResult(true);
554 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000555 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000556
Neil Boothb9449512007-08-29 22:00:19 +0000557 // long long is a C99 feature.
558 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000559 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000560 Diag(Tok.getLocation(), diag::ext_longlong);
561
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000563 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000568 Ty = Context.UnsignedLongLongTy;
569 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000570 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner8cbcb0e2008-05-09 05:59:00 +0000580 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000581 if (!Literal.isLong && !Literal.isLongLong) {
582 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000583 unsigned IntSize = Context.Target.getIntWidth();
584
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000589 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000590 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000591 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000592 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 }
595
596 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000597 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000598 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000604 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000606 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000607 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000609 }
610
611 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000612 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000613 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000619 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000621 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000622 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000628 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000629 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000630 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000631 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000633
634 if (ResultVal.getBitWidth() != Width)
635 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000636 }
637
Chris Lattnerf0467b32008-04-02 04:24:33 +0000638 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 }
Chris Lattner5d661452007-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000646}
647
Steve Narofff69936d2007-09-16 03:34:24 +0000648Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000649 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000650 Expr *E = (Expr *)Val;
651 assert((E != 0) && "ActOnParenExpr() missing expr");
652 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000653}
654
655/// The UsualUnaryConversions() function is *not* called by this routine.
656/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +0000657bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
658 SourceLocation OpLoc,
659 const SourceRange &ExprRange,
660 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000661 // C99 6.5.3.4p1:
662 if (isa<FunctionType>(exprType) && isSizeof)
663 // alignof(function) is allowed.
Chris Lattnerbb280a42008-07-25 21:45:37 +0000664 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000665 else if (exprType->isVoidType())
Chris Lattnerbb280a42008-07-25 21:45:37 +0000666 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
667 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 else if (exprType->isIncompleteType()) {
669 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
670 diag::err_alignof_incomplete_type,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000671 exprType.getAsString(), ExprRange);
Sebastian Redl05189992008-11-11 17:56:53 +0000672 return true; // error
Reid Spencer5f016e22007-07-11 17:01:13 +0000673 }
Sebastian Redl05189992008-11-11 17:56:53 +0000674
675 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000676}
677
Sebastian Redl05189992008-11-11 17:56:53 +0000678/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
679/// the same for @c alignof and @c __alignof
680/// Note that the ArgRange is invalid if isType is false.
681Action::ExprResult
682Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
683 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000684 // If error parsing type, ignore.
Sebastian Redl05189992008-11-11 17:56:53 +0000685 if (TyOrEx == 0) return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000686
Sebastian Redl05189992008-11-11 17:56:53 +0000687 QualType ArgTy;
688 SourceRange Range;
689 if (isType) {
690 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
691 Range = ArgRange;
692 } else {
693 // Get the end location.
694 Expr *ArgEx = (Expr *)TyOrEx;
695 Range = ArgEx->getSourceRange();
696 ArgTy = ArgEx->getType();
697 }
698
699 // Verify that the operand is valid.
700 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 return true;
Sebastian Redl05189992008-11-11 17:56:53 +0000702
703 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
704 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
705 OpLoc, Range.getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +0000706}
707
Chris Lattner5d794252007-08-24 21:41:10 +0000708QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000709 DefaultFunctionArrayConversion(V);
710
Chris Lattnercc26ed72007-08-26 05:39:26 +0000711 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000712 if (const ComplexType *CT = V->getType()->getAsComplexType())
713 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000714
715 // Otherwise they pass through real integer and floating point types here.
716 if (V->getType()->isArithmeticType())
717 return V->getType();
718
719 // Reject anything else.
720 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
721 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000722}
723
724
Reid Spencer5f016e22007-07-11 17:01:13 +0000725
Steve Narofff69936d2007-09-16 03:34:24 +0000726Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 tok::TokenKind Kind,
728 ExprTy *Input) {
729 UnaryOperator::Opcode Opc;
730 switch (Kind) {
731 default: assert(0 && "Unknown unary op!");
732 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
733 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
734 }
735 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
736 if (result.isNull())
737 return true;
738 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
739}
740
741Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000742ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000743 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000744 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000745
746 // Perform default conversions.
747 DefaultFunctionArrayConversion(LHSExp);
748 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000749
Chris Lattner12d9ff62007-07-16 00:14:47 +0000750 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000751
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000753 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 // in the subscript position. As a result, we need to derive the array base
755 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000756 Expr *BaseExpr, *IndexExpr;
757 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000758 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000759 BaseExpr = LHSExp;
760 IndexExpr = RHSExp;
761 // FIXME: need to deal with const...
762 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000763 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000764 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000765 BaseExpr = RHSExp;
766 IndexExpr = LHSExp;
767 // FIXME: need to deal with const...
768 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000769 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
770 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000771 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000772
773 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000774 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
775 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begeman213541a2008-04-18 23:10:10 +0000776 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff608e0ee2007-08-03 22:40:33 +0000777 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000778 // FIXME: need to deal with const...
779 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000781 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
782 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 }
784 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000785 if (!IndexExpr->getType()->isIntegerType())
786 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
787 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000788
Chris Lattner12d9ff62007-07-16 00:14:47 +0000789 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
790 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000791 // void (*)(int)) and pointers to incomplete types. Functions are not
792 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000793 if (!ResultType->isObjectType())
794 return Diag(BaseExpr->getLocStart(),
795 diag::err_typecheck_subscript_not_object,
796 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
797
798 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000799}
800
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000801QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000802CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000803 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000804 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +0000805
806 // This flag determines whether or not the component is to be treated as a
807 // special name, or a regular GLSL-style component access.
808 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000809
810 // The vector accessor can't exceed the number of elements.
811 const char *compStr = CompName.getName();
812 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begeman213541a2008-04-18 23:10:10 +0000813 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000814 baseType.getAsString(), SourceRange(CompLoc));
815 return QualType();
816 }
Nate Begeman8a997642008-05-09 06:41:27 +0000817
818 // Check that we've found one of the special components, or that the component
819 // names must come from the same set.
820 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
821 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
822 SpecialComponent = true;
823 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +0000824 do
825 compStr++;
826 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
827 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
828 do
829 compStr++;
830 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
831 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
832 do
833 compStr++;
834 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
835 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000836
Nate Begeman8a997642008-05-09 06:41:27 +0000837 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000838 // We didn't get to the end of the string. This means the component names
839 // didn't come from the same set *or* we encountered an illegal name.
Nate Begeman213541a2008-04-18 23:10:10 +0000840 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000841 std::string(compStr,compStr+1), SourceRange(CompLoc));
842 return QualType();
843 }
844 // Each component accessor can't exceed the vector type.
845 compStr = CompName.getName();
846 while (*compStr) {
847 if (vecType->isAccessorWithinNumElements(*compStr))
848 compStr++;
849 else
850 break;
851 }
Nate Begeman8a997642008-05-09 06:41:27 +0000852 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000853 // We didn't get to the end of the string. This means a component accessor
854 // exceeds the number of elements in the vector.
Nate Begeman213541a2008-04-18 23:10:10 +0000855 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000856 baseType.getAsString(), SourceRange(CompLoc));
857 return QualType();
858 }
Nate Begeman8a997642008-05-09 06:41:27 +0000859
860 // If we have a special component name, verify that the current vector length
861 // is an even number, since all special component names return exactly half
862 // the elements.
863 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbarabee2d72008-09-30 17:22:47 +0000864 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
865 baseType.getAsString(), SourceRange(CompLoc));
Nate Begeman8a997642008-05-09 06:41:27 +0000866 return QualType();
867 }
868
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000869 // The component accessor looks fine - now we need to compute the actual type.
870 // The vector type is implied by the component accessor. For example,
871 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +0000872 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
873 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
874 : strlen(CompName.getName());
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000875 if (CompSize == 1)
876 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000877
Nate Begeman213541a2008-04-18 23:10:10 +0000878 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000879 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +0000880 // diagostics look bad. We want extended vector types to appear built-in.
881 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
882 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
883 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +0000884 }
885 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000886}
887
Daniel Dunbar2307d312008-09-03 01:05:41 +0000888/// constructSetterName - Return the setter name for the given
889/// identifier, i.e. "set" + Name where the initial character of Name
890/// has been capitalized.
891// FIXME: Merge with same routine in Parser. But where should this
892// live?
893static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
894 const IdentifierInfo *Name) {
895 unsigned N = Name->getLength();
896 char *SelectorName = new char[3 + N];
897 memcpy(SelectorName, "set", 3);
898 memcpy(&SelectorName[3], Name->getName(), N);
899 SelectorName[3] = toupper(SelectorName[3]);
900
901 IdentifierInfo *Setter =
902 &Idents.get(SelectorName, &SelectorName[3 + N]);
903 delete[] SelectorName;
904 return Setter;
905}
906
Reid Spencer5f016e22007-07-11 17:01:13 +0000907Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000908ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 tok::TokenKind OpKind, SourceLocation MemberLoc,
910 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000911 Expr *BaseExpr = static_cast<Expr *>(Base);
912 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000913
914 // Perform default conversions.
915 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000916
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000917 QualType BaseType = BaseExpr->getType();
918 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000919
Chris Lattner68a057b2008-07-21 04:36:39 +0000920 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
921 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +0000922 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000923 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000924 BaseType = PT->getPointeeType();
925 else
Chris Lattner2a01b722008-07-21 05:35:34 +0000926 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
927 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000929
Chris Lattner68a057b2008-07-21 04:36:39 +0000930 // Handle field access to simple records. This also handles access to fields
931 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +0000932 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000933 RecordDecl *RDecl = RTy->getDecl();
934 if (RTy->isIncompleteType())
935 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
936 BaseExpr->getSourceRange());
937 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000938 FieldDecl *MemberDecl = RDecl->getMember(&Member);
939 if (!MemberDecl)
Chris Lattner2a01b722008-07-21 05:35:34 +0000940 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
941 BaseExpr->getSourceRange());
Eli Friedman51019072008-02-06 22:48:16 +0000942
943 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000944 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000945 QualType MemberType = MemberDecl->getType();
946 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000947 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman51019072008-02-06 22:48:16 +0000948 MemberType = MemberType.getQualifiedType(combinedQualifiers);
949
Chris Lattner68a057b2008-07-21 04:36:39 +0000950 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000951 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000952 }
953
Chris Lattnera38e6b12008-07-21 04:59:05 +0000954 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
955 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000956 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
957 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000958 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000959 OpKind == tok::arrow);
Chris Lattner2a01b722008-07-21 05:35:34 +0000960 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner1f719742008-07-21 04:42:08 +0000961 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner2a01b722008-07-21 05:35:34 +0000962 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000963 }
964
Chris Lattnera38e6b12008-07-21 04:59:05 +0000965 // Handle Objective-C property access, which is "Obj.property" where Obj is a
966 // pointer to a (potentially qualified) interface type.
967 const PointerType *PTy;
968 const ObjCInterfaceType *IFTy;
969 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
970 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
971 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000972
Daniel Dunbar2307d312008-09-03 01:05:41 +0000973 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +0000974 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
975 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
976
Daniel Dunbar2307d312008-09-03 01:05:41 +0000977 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +0000978 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
979 E = IFTy->qual_end(); I != E; ++I)
980 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
981 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +0000982
983 // If that failed, look for an "implicit" property by seeing if the nullary
984 // selector is implemented.
985
986 // FIXME: The logic for looking up nullary and unary selectors should be
987 // shared with the code in ActOnInstanceMessage.
988
989 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
990 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
991
992 // If this reference is in an @implementation, check for 'private' methods.
993 if (!Getter)
994 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
995 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
996 if (ObjCImplementationDecl *ImpDecl =
997 ObjCImplementations[ClassDecl->getIdentifier()])
998 Getter = ImpDecl->getInstanceMethod(Sel);
999
Steve Naroff7692ed62008-10-22 19:16:27 +00001000 // Look through local category implementations associated with the class.
1001 if (!Getter) {
1002 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1003 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1004 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1005 }
1006 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001007 if (Getter) {
1008 // If we found a getter then this may be a valid dot-reference, we
1009 // need to also look for the matching setter.
1010 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1011 &Member);
1012 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1013 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1014
1015 if (!Setter) {
1016 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1017 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1018 if (ObjCImplementationDecl *ImpDecl =
1019 ObjCImplementations[ClassDecl->getIdentifier()])
1020 Setter = ImpDecl->getInstanceMethod(SetterSel);
1021 }
1022
1023 // FIXME: There are some issues here. First, we are not
1024 // diagnosing accesses to read-only properties because we do not
1025 // know if this is a getter or setter yet. Second, we are
1026 // checking that the type of the setter matches the type we
1027 // expect.
1028 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1029 MemberLoc, BaseExpr);
1030 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001031 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001032 // Handle properties on qualified "id" protocols.
1033 const ObjCQualifiedIdType *QIdTy;
1034 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1035 // Check protocols on qualified interfaces.
1036 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1037 E = QIdTy->qual_end(); I != E; ++I)
1038 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1039 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1040 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001041 // Handle 'field access' to vectors, such as 'V.xx'.
1042 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1043 // Component access limited to variables (reject vec4.rg.g).
1044 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1045 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner2a01b722008-07-21 05:35:34 +00001046 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1047 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001048 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1049 if (ret.isNull())
1050 return true;
1051 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1052 }
1053
Chris Lattner2a01b722008-07-21 05:35:34 +00001054 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1055 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001056}
1057
Steve Narofff69936d2007-09-16 03:34:24 +00001058/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001059/// This provides the location of the left/right parens and a list of comma
1060/// locations.
1061Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001062ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001063 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001065 Expr *Fn = static_cast<Expr *>(fn);
1066 Expr **Args = reinterpret_cast<Expr**>(args);
1067 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001068 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001069 OverloadedFunctionDecl *Ovl = NULL;
1070
1071 // If we're directly calling a function or a set of overloaded
1072 // functions, get the appropriate declaration.
1073 {
1074 DeclRefExpr *DRExpr = NULL;
1075 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1076 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1077 else
1078 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1079
1080 if (DRExpr) {
1081 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1082 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1083 }
1084 }
1085
1086 // If we have a set of overloaded functions, perform overload
1087 // resolution to pick the function.
1088 if (Ovl) {
1089 OverloadCandidateSet CandidateSet;
1090 OverloadCandidateSet::iterator Best;
1091 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1092 switch (BestViableFunction(CandidateSet, Best)) {
1093 case OR_Success:
1094 {
1095 // Success! Let the remainder of this function build a call to
1096 // the function selected by overload resolution.
1097 FDecl = Best->Function;
1098 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1099 Fn->getSourceRange().getBegin());
1100 delete Fn;
1101 Fn = NewFn;
1102 }
1103 break;
1104
1105 case OR_No_Viable_Function:
1106 if (CandidateSet.empty())
1107 Diag(Fn->getSourceRange().getBegin(),
1108 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1109 Fn->getSourceRange());
1110 else {
1111 Diag(Fn->getSourceRange().getBegin(),
1112 diag::err_ovl_no_viable_function_in_call_with_cands,
1113 Ovl->getName(), Fn->getSourceRange());
1114 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1115 }
1116 return true;
1117
1118 case OR_Ambiguous:
1119 Diag(Fn->getSourceRange().getBegin(),
1120 diag::err_ovl_ambiguous_call, Ovl->getName(),
1121 Fn->getSourceRange());
1122 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1123 return true;
1124 }
1125 }
Chris Lattner04421082008-04-08 04:40:51 +00001126
1127 // Promote the function operand.
1128 UsualUnaryConversions(Fn);
1129
Chris Lattner925e60d2007-12-28 05:29:59 +00001130 // Make the call expr early, before semantic checks. This guarantees cleanup
1131 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001132 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001133 Context.BoolTy, RParenLoc));
Steve Naroffdd972f22008-09-05 22:11:13 +00001134 const FunctionType *FuncT;
1135 if (!Fn->getType()->isBlockPointerType()) {
1136 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1137 // have type pointer to function".
1138 const PointerType *PT = Fn->getType()->getAsPointerType();
1139 if (PT == 0)
1140 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1141 Fn->getSourceRange());
1142 FuncT = PT->getPointeeType()->getAsFunctionType();
1143 } else { // This is a block call.
1144 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1145 getAsFunctionType();
1146 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001147 if (FuncT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +00001148 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1149 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +00001150
1151 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001152 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001153
Chris Lattner925e60d2007-12-28 05:29:59 +00001154 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1156 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001157 unsigned NumArgsInProto = Proto->getNumArgs();
1158 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001159
Chris Lattner04421082008-04-08 04:40:51 +00001160 // If too few arguments are available (and we don't have default
1161 // arguments for the remaining parameters), don't make the call.
1162 if (NumArgs < NumArgsInProto) {
Chris Lattner8123a952008-04-10 02:22:51 +00001163 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +00001164 // Use default arguments for missing arguments
1165 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +00001166 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001167 } else
Steve Naroffdd972f22008-09-05 22:11:13 +00001168 return Diag(RParenLoc,
1169 !Fn->getType()->isBlockPointerType()
1170 ? diag::err_typecheck_call_too_few_args
1171 : diag::err_typecheck_block_too_few_args,
Chris Lattner04421082008-04-08 04:40:51 +00001172 Fn->getSourceRange());
1173 }
1174
Chris Lattner925e60d2007-12-28 05:29:59 +00001175 // If too many are passed and not variadic, error on the extras and drop
1176 // them.
1177 if (NumArgs > NumArgsInProto) {
1178 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +00001179 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffdd972f22008-09-05 22:11:13 +00001180 !Fn->getType()->isBlockPointerType()
1181 ? diag::err_typecheck_call_too_many_args
1182 : diag::err_typecheck_block_too_many_args,
1183 Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +00001184 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +00001185 Args[NumArgs-1]->getLocEnd()));
1186 // This deletes the extra arguments.
1187 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 }
1189 NumArgsToCheck = NumArgsInProto;
1190 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001191
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001193 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001194 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001195
1196 Expr *Arg;
1197 if (i < NumArgs)
1198 Arg = Args[i];
1199 else
1200 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001201 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001202
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001203 // Pass the argument.
1204 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001205 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001206
1207 TheCall->setArg(i, Arg);
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001209
1210 // If this is a variadic call, handle args passed through "...".
1211 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001212 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001213 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1214 Expr *Arg = Args[i];
1215 DefaultArgumentPromotion(Arg);
1216 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001217 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001218 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001219 } else {
1220 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1221
Steve Naroffb291ab62007-08-28 23:30:39 +00001222 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001223 for (unsigned i = 0; i != NumArgs; i++) {
1224 Expr *Arg = Args[i];
1225 DefaultArgumentPromotion(Arg);
1226 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001227 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001229
Chris Lattner59907c42007-08-10 20:18:51 +00001230 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001231 if (FDecl)
1232 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001233
Chris Lattner925e60d2007-12-28 05:29:59 +00001234 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001235}
1236
1237Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001238ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001239 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001240 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001241 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001242 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001243 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001244 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001245
Eli Friedman6223c222008-05-20 05:22:08 +00001246 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001247 if (literalType->isVariableArrayType())
Eli Friedman6223c222008-05-20 05:22:08 +00001248 return Diag(LParenLoc,
1249 diag::err_variable_object_no_init,
1250 SourceRange(LParenLoc,
1251 literalExpr->getSourceRange().getEnd()));
1252 } else if (literalType->isIncompleteType()) {
1253 return Diag(LParenLoc,
1254 diag::err_typecheck_decl_incomplete_type,
1255 literalType.getAsString(),
1256 SourceRange(LParenLoc,
1257 literalExpr->getSourceRange().getEnd()));
1258 }
1259
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001260 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
1261 "temporary"))
Steve Naroff58d18212008-01-09 20:58:06 +00001262 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001263
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001264 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001265 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001266 if (CheckForConstantInitializer(literalExpr, literalType))
1267 return true;
1268 }
Chris Lattner220ad7c2008-10-26 23:35:51 +00001269 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1270 isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001271}
1272
1273Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001274ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattner220ad7c2008-10-26 23:35:51 +00001275 InitListDesignations &Designators,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001276 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001277 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001278
Steve Naroff08d92e42007-09-15 18:49:24 +00001279 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001280 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001281
Chris Lattner418f6c72008-10-26 23:43:26 +00001282 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1283 Designators.hasAnyDesignators());
Chris Lattnerf0467b32008-04-02 04:24:33 +00001284 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1285 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001286}
1287
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001288/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001289bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001290 UsualUnaryConversions(castExpr);
1291
1292 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1293 // type needs to be scalar.
1294 if (castType->isVoidType()) {
1295 // Cast to void allows any expr type.
1296 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1297 // GCC struct/union extension: allow cast to self.
1298 if (Context.getCanonicalType(castType) !=
1299 Context.getCanonicalType(castExpr->getType()) ||
1300 (!castType->isStructureType() && !castType->isUnionType())) {
1301 // Reject any other conversions to non-scalar types.
1302 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1303 castType.getAsString(), castExpr->getSourceRange());
1304 }
1305
1306 // accept this, but emit an ext-warn.
1307 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1308 castType.getAsString(), castExpr->getSourceRange());
1309 } else if (!castExpr->getType()->isScalarType() &&
1310 !castExpr->getType()->isVectorType()) {
1311 return Diag(castExpr->getLocStart(),
1312 diag::err_typecheck_expect_scalar_operand,
1313 castExpr->getType().getAsString(),castExpr->getSourceRange());
1314 } else if (castExpr->getType()->isVectorType()) {
1315 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1316 return true;
1317 } else if (castType->isVectorType()) {
1318 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1319 return true;
1320 }
1321 return false;
1322}
1323
Chris Lattnerfe23e212007-12-20 00:44:32 +00001324bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001325 assert(VectorTy->isVectorType() && "Not a vector type!");
1326
1327 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001328 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001329 return Diag(R.getBegin(),
1330 Ty->isVectorType() ?
1331 diag::err_invalid_conversion_between_vectors :
1332 diag::err_invalid_conversion_between_vector_and_integer,
1333 VectorTy.getAsString().c_str(),
1334 Ty.getAsString().c_str(), R);
1335 } else
1336 return Diag(R.getBegin(),
1337 diag::err_invalid_conversion_between_vector_and_scalar,
1338 VectorTy.getAsString().c_str(),
1339 Ty.getAsString().c_str(), R);
1340
1341 return false;
1342}
1343
Steve Naroff4aa88f82007-07-19 01:06:55 +00001344Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001345ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001347 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001348
1349 Expr *castExpr = static_cast<Expr*>(Op);
1350 QualType castType = QualType::getFromOpaquePtr(Ty);
1351
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001352 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1353 return true;
Steve Naroffb2f9e512008-11-03 23:29:32 +00001354 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001355}
1356
Chris Lattnera21ddb32007-11-26 01:40:58 +00001357/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1358/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001359inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001360 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001361 UsualUnaryConversions(cond);
1362 UsualUnaryConversions(lex);
1363 UsualUnaryConversions(rex);
1364 QualType condT = cond->getType();
1365 QualType lexT = lex->getType();
1366 QualType rexT = rex->getType();
1367
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001369 if (!condT->isScalarType()) { // C99 6.5.15p2
1370 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1371 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 return QualType();
1373 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001374
1375 // Now check the two expressions.
1376
1377 // If both operands have arithmetic type, do the usual arithmetic conversions
1378 // to find a common type: C99 6.5.15p3,5.
1379 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001380 UsualArithmeticConversions(lex, rex);
1381 return lex->getType();
1382 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001383
1384 // If both operands are the same structure or union type, the result is that
1385 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001386 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001387 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001388 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001389 // "If both the operands have structure or union type, the result has
1390 // that type." This implies that CV qualifiers are dropped.
1391 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001393
1394 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001395 // The following || allows only one side to be void (a GCC-ism).
1396 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001397 if (!lexT->isVoidType())
Steve Naroffe701c0a2008-05-12 21:44:38 +00001398 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1399 rex->getSourceRange());
1400 if (!rexT->isVoidType())
1401 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopesd8de7252008-06-04 19:14:12 +00001402 lex->getSourceRange());
Eli Friedman0e724012008-06-04 19:47:51 +00001403 ImpCastExprToType(lex, Context.VoidTy);
1404 ImpCastExprToType(rex, Context.VoidTy);
1405 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001406 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001407 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1408 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001409 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1410 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001411 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001412 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001413 return lexT;
1414 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001415 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1416 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001417 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001418 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001419 return rexT;
1420 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001421 // Handle the case where both operands are pointers before we handle null
1422 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001423 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1424 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1425 // get the "pointed to" types
1426 QualType lhptee = LHSPT->getPointeeType();
1427 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001428
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001429 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1430 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001431 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001432 // Figure out necessary qualifiers (C99 6.5.15p6)
1433 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001434 QualType destType = Context.getPointerType(destPointee);
1435 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1436 ImpCastExprToType(rex, destType); // promote to void*
1437 return destType;
1438 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001439 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001440 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001441 QualType destType = Context.getPointerType(destPointee);
1442 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1443 ImpCastExprToType(rex, destType); // promote to void*
1444 return destType;
1445 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001446
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001447 QualType compositeType = lexT;
1448
1449 // If either type is an Objective-C object type then check
1450 // compatibility according to Objective-C.
1451 if (Context.isObjCObjectPointerType(lexT) ||
1452 Context.isObjCObjectPointerType(rexT)) {
1453 // If both operands are interfaces and either operand can be
1454 // assigned to the other, use that type as the composite
1455 // type. This allows
1456 // xxx ? (A*) a : (B*) b
1457 // where B is a subclass of A.
1458 //
1459 // Additionally, as for assignment, if either type is 'id'
1460 // allow silent coercion. Finally, if the types are
1461 // incompatible then make sure to use 'id' as the composite
1462 // type so the result is acceptable for sending messages to.
1463
1464 // FIXME: This code should not be localized to here. Also this
1465 // should use a compatible check instead of abusing the
1466 // canAssignObjCInterfaces code.
1467 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1468 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1469 if (LHSIface && RHSIface &&
1470 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1471 compositeType = lexT;
1472 } else if (LHSIface && RHSIface &&
1473 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1474 compositeType = rexT;
1475 } else if (Context.isObjCIdType(lhptee) ||
1476 Context.isObjCIdType(rhptee)) {
1477 // FIXME: This code looks wrong, because isObjCIdType checks
1478 // the struct but getObjCIdType returns the pointer to
1479 // struct. This is horrible and should be fixed.
1480 compositeType = Context.getObjCIdType();
1481 } else {
1482 QualType incompatTy = Context.getObjCIdType();
1483 ImpCastExprToType(lex, incompatTy);
1484 ImpCastExprToType(rex, incompatTy);
1485 return incompatTy;
1486 }
1487 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1488 rhptee.getUnqualifiedType())) {
Steve Naroffc0ff1ca2008-02-01 22:44:48 +00001489 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001490 lexT.getAsString(), rexT.getAsString(),
1491 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001492 // In this situation, we assume void* type. No especially good
1493 // reason, but this is what gcc does, and we do have to pick
1494 // to get a consistent AST.
1495 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00001496 ImpCastExprToType(lex, incompatTy);
1497 ImpCastExprToType(rex, incompatTy);
1498 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001499 }
1500 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001501 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1502 // differently qualified versions of compatible types, the result type is
1503 // a pointer to an appropriately qualified version of the *composite*
1504 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001505 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001506 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001507 ImpCastExprToType(lex, compositeType);
1508 ImpCastExprToType(rex, compositeType);
1509 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 }
1511 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001512 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1513 // evaluates to "struct objc_object *" (and is handled above when comparing
1514 // id with statically typed objects).
1515 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1516 // GCC allows qualified id and any Objective-C type to devolve to
1517 // id. Currently localizing to here until clear this should be
1518 // part of ObjCQualifiedIdTypesAreCompatible.
1519 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1520 (lexT->isObjCQualifiedIdType() &&
1521 Context.isObjCObjectPointerType(rexT)) ||
1522 (rexT->isObjCQualifiedIdType() &&
1523 Context.isObjCObjectPointerType(lexT))) {
1524 // FIXME: This is not the correct composite type. This only
1525 // happens to work because id can more or less be used anywhere,
1526 // however this may change the type of method sends.
1527 // FIXME: gcc adds some type-checking of the arguments and emits
1528 // (confusing) incompatible comparison warnings in some
1529 // cases. Investigate.
1530 QualType compositeType = Context.getObjCIdType();
1531 ImpCastExprToType(lex, compositeType);
1532 ImpCastExprToType(rex, compositeType);
1533 return compositeType;
1534 }
1535 }
1536
Steve Naroff61f40a22008-09-10 19:17:48 +00001537 // Selection between block pointer types is ok as long as they are the same.
1538 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1539 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1540 return lexT;
1541
Chris Lattner70d67a92008-01-06 22:42:25 +00001542 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +00001544 lexT.getAsString(), rexT.getAsString(),
1545 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 return QualType();
1547}
1548
Steve Narofff69936d2007-09-16 03:34:24 +00001549/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001550/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001551Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 SourceLocation ColonLoc,
1553 ExprTy *Cond, ExprTy *LHS,
1554 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001555 Expr *CondExpr = (Expr *) Cond;
1556 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001557
1558 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1559 // was the condition.
1560 bool isLHSNull = LHSExpr == 0;
1561 if (isLHSNull)
1562 LHSExpr = CondExpr;
1563
Chris Lattner26824902007-07-16 21:39:03 +00001564 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1565 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 if (result.isNull())
1567 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001568 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1569 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001570}
1571
Reid Spencer5f016e22007-07-11 17:01:13 +00001572
1573// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1574// being closely modeled after the C99 spec:-). The odd characteristic of this
1575// routine is it effectively iqnores the qualifiers on the top level pointee.
1576// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1577// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001578Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001579Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1580 QualType lhptee, rhptee;
1581
1582 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001583 lhptee = lhsType->getAsPointerType()->getPointeeType();
1584 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001585
1586 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001587 lhptee = Context.getCanonicalType(lhptee);
1588 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001589
Chris Lattner5cf216b2008-01-04 18:04:52 +00001590 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001591
1592 // C99 6.5.16.1p1: This following citation is common to constraints
1593 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1594 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001595 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00001596 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001597 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001598
1599 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1600 // incomplete type and the other is a pointer to a qualified or unqualified
1601 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001602 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001603 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001604 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001605
1606 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001607 assert(rhptee->isFunctionType());
1608 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001609 }
1610
1611 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001612 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001613 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001614
1615 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001616 assert(lhptee->isFunctionType());
1617 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001618 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001619
1620 // Check for ObjC interfaces
1621 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1622 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1623 if (LHSIface && RHSIface &&
1624 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1625 return ConvTy;
1626
1627 // ID acts sort of like void* for ObjC interfaces
1628 if (LHSIface && Context.isObjCIdType(rhptee))
1629 return ConvTy;
1630 if (RHSIface && Context.isObjCIdType(lhptee))
1631 return ConvTy;
1632
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1634 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001635 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1636 rhptee.getUnqualifiedType()))
1637 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001638 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001639}
1640
Steve Naroff1c7d0672008-09-04 15:10:53 +00001641/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1642/// block pointer types are compatible or whether a block and normal pointer
1643/// are compatible. It is more restrict than comparing two function pointer
1644// types.
1645Sema::AssignConvertType
1646Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1647 QualType rhsType) {
1648 QualType lhptee, rhptee;
1649
1650 // get the "pointed to" type (ignoring qualifiers at the top level)
1651 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1652 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1653
1654 // make sure we operate on the canonical type
1655 lhptee = Context.getCanonicalType(lhptee);
1656 rhptee = Context.getCanonicalType(rhptee);
1657
1658 AssignConvertType ConvTy = Compatible;
1659
1660 // For blocks we enforce that qualifiers are identical.
1661 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1662 ConvTy = CompatiblePointerDiscardsQualifiers;
1663
1664 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1665 return IncompatibleBlockPointer;
1666 return ConvTy;
1667}
1668
Reid Spencer5f016e22007-07-11 17:01:13 +00001669/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1670/// has code to accommodate several GCC extensions when type checking
1671/// pointers. Here are some objectionable examples that GCC considers warnings:
1672///
1673/// int a, *pint;
1674/// short *pshort;
1675/// struct foo *pfoo;
1676///
1677/// pint = pshort; // warning: assignment from incompatible pointer type
1678/// a = pint; // warning: assignment makes integer from pointer without a cast
1679/// pint = a; // warning: assignment makes pointer from integer without a cast
1680/// pint = pfoo; // warning: assignment from incompatible pointer type
1681///
1682/// As a result, the code for dealing with pointers is more complex than the
1683/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001684///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001685Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001686Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001687 // Get canonical types. We're not formatting these types, just comparing
1688 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001689 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1690 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001691
1692 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001693 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001694
Douglas Gregor9d293df2008-10-28 00:22:11 +00001695 // If the left-hand side is a reference type, then we are in a
1696 // (rare!) case where we've allowed the use of references in C,
1697 // e.g., as a parameter type in a built-in function. In this case,
1698 // just make sure that the type referenced is compatible with the
1699 // right-hand side type. The caller is responsible for adjusting
1700 // lhsType so that the resulting expression does not have reference
1701 // type.
1702 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1703 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001704 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001705 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001706 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001707
Chris Lattnereca7be62008-04-07 05:30:13 +00001708 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1709 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001710 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001711 // Relax integer conversions like we do for pointers below.
1712 if (rhsType->isIntegerType())
1713 return IntToPointer;
1714 if (lhsType->isIntegerType())
1715 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00001716 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001717 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001718
Nate Begemanbe2341d2008-07-14 18:02:46 +00001719 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001720 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001721 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1722 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001723 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001724
Nate Begemanbe2341d2008-07-14 18:02:46 +00001725 // If we are allowing lax vector conversions, and LHS and RHS are both
1726 // vectors, the total size only needs to be the same. This is a bitcast;
1727 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001728 if (getLangOptions().LaxVectorConversions &&
1729 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001730 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1731 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001732 }
1733 return Incompatible;
1734 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001735
Chris Lattnere8b3e962008-01-04 23:32:24 +00001736 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001738
Chris Lattner78eca282008-04-07 06:49:41 +00001739 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001740 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001741 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001742
Chris Lattner78eca282008-04-07 06:49:41 +00001743 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001745
Steve Naroffb4406862008-09-29 18:10:17 +00001746 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00001747 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff1c7d0672008-09-04 15:10:53 +00001748 return BlockVoidPointer;
Steve Naroffb4406862008-09-29 18:10:17 +00001749
1750 // Treat block pointers as objects.
1751 if (getLangOptions().ObjC1 &&
1752 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1753 return Compatible;
1754 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001755 return Incompatible;
1756 }
1757
1758 if (isa<BlockPointerType>(lhsType)) {
1759 if (rhsType->isIntegerType())
1760 return IntToPointer;
1761
Steve Naroffb4406862008-09-29 18:10:17 +00001762 // Treat block pointers as objects.
1763 if (getLangOptions().ObjC1 &&
1764 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1765 return Compatible;
1766
Steve Naroff1c7d0672008-09-04 15:10:53 +00001767 if (rhsType->isBlockPointerType())
1768 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1769
1770 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1771 if (RHSPT->getPointeeType()->isVoidType())
1772 return BlockVoidPointer;
1773 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001774 return Incompatible;
1775 }
1776
Chris Lattner78eca282008-04-07 06:49:41 +00001777 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001779 if (lhsType == Context.BoolTy)
1780 return Compatible;
1781
1782 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001783 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001784
Chris Lattner78eca282008-04-07 06:49:41 +00001785 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001787
1788 if (isa<BlockPointerType>(lhsType) &&
1789 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1790 return BlockVoidPointer;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001791 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001792 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001793
Chris Lattnerfc144e22008-01-04 23:18:45 +00001794 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001795 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 }
1798 return Incompatible;
1799}
1800
Chris Lattner5cf216b2008-01-04 18:04:52 +00001801Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001802Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001803 if (getLangOptions().CPlusPlus) {
1804 if (!lhsType->isRecordType()) {
1805 // C++ 5.17p3: If the left operand is not of class type, the
1806 // expression is implicitly converted (C++ 4) to the
1807 // cv-unqualified type of the left operand.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001808 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001809 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001810 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00001811 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001812 }
1813
1814 // FIXME: Currently, we fall through and treat C++ classes like C
1815 // structures.
1816 }
1817
Steve Naroff529a4ad2007-11-27 17:58:44 +00001818 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1819 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00001820 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1821 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001822 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001823 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001824 return Compatible;
1825 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001826
1827 // We don't allow conversion of non-null-pointer constants to integers.
1828 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1829 return IntToBlockPointer;
1830
Chris Lattner943140e2007-10-16 02:55:40 +00001831 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001832 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001833 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001834 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001835 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00001836 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00001837 if (!lhsType->isReferenceType())
1838 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001839
Chris Lattner5cf216b2008-01-04 18:04:52 +00001840 Sema::AssignConvertType result =
1841 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001842
1843 // C99 6.5.16.1p2: The value of the right operand is converted to the
1844 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00001845 // CheckAssignmentConstraints allows the left-hand side to be a reference,
1846 // so that we can use references in built-in functions even in C.
1847 // The getNonReferenceType() call makes sure that the resulting expression
1848 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00001849 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00001850 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00001851 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001852}
1853
Chris Lattner5cf216b2008-01-04 18:04:52 +00001854Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001855Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1856 return CheckAssignmentConstraints(lhsType, rhsType);
1857}
1858
Chris Lattnerca5eede2007-12-12 05:47:28 +00001859QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 Diag(loc, diag::err_typecheck_invalid_operands,
1861 lex->getType().getAsString(), rex->getType().getAsString(),
1862 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001863 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001864}
1865
Steve Naroff49b45262007-07-13 16:58:59 +00001866inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1867 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001868 // For conversion purposes, we ignore any qualifiers.
1869 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001870 QualType lhsType =
1871 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1872 QualType rhsType =
1873 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001874
Nate Begemanbe2341d2008-07-14 18:02:46 +00001875 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001876 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001878
Nate Begemanbe2341d2008-07-14 18:02:46 +00001879 // Handle the case of a vector & extvector type of the same size and element
1880 // type. It would be nice if we only had one vector type someday.
1881 if (getLangOptions().LaxVectorConversions)
1882 if (const VectorType *LV = lhsType->getAsVectorType())
1883 if (const VectorType *RV = rhsType->getAsVectorType())
1884 if (LV->getElementType() == RV->getElementType() &&
1885 LV->getNumElements() == RV->getNumElements())
1886 return lhsType->isExtVectorType() ? lhsType : rhsType;
1887
1888 // If the lhs is an extended vector and the rhs is a scalar of the same type
1889 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001890 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001891 QualType eltType = V->getElementType();
1892
1893 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1894 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1895 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001896 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001897 return lhsType;
1898 }
1899 }
1900
Nate Begemanbe2341d2008-07-14 18:02:46 +00001901 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001902 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001903 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001904 QualType eltType = V->getElementType();
1905
1906 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1907 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1908 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001909 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001910 return rhsType;
1911 }
1912 }
1913
Reid Spencer5f016e22007-07-11 17:01:13 +00001914 // You cannot convert between vector values of different size.
1915 Diag(loc, diag::err_typecheck_vector_not_convertable,
1916 lex->getType().getAsString(), rex->getType().getAsString(),
1917 lex->getSourceRange(), rex->getSourceRange());
1918 return QualType();
1919}
1920
1921inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001922 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001923{
Steve Naroff90045e82007-07-13 23:32:42 +00001924 QualType lhsType = lex->getType(), rhsType = rex->getType();
1925
1926 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001928
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001929 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001930
Steve Naroffa4332e22007-07-17 00:58:39 +00001931 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001932 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001933 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001934}
1935
1936inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001937 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001938{
Steve Naroff90045e82007-07-13 23:32:42 +00001939 QualType lhsType = lex->getType(), rhsType = rex->getType();
1940
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001941 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001942
Steve Naroffa4332e22007-07-17 00:58:39 +00001943 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001944 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001945 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001946}
1947
1948inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001949 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001950{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001951 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001952 return CheckVectorOperands(loc, lex, rex);
1953
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001954 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001955
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001957 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001958 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001959
Eli Friedmand72d16e2008-05-18 18:08:51 +00001960 // Put any potential pointer into PExp
1961 Expr* PExp = lex, *IExp = rex;
1962 if (IExp->getType()->isPointerType())
1963 std::swap(PExp, IExp);
1964
1965 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1966 if (IExp->getType()->isIntegerType()) {
1967 // Check for arithmetic on pointers to incomplete types
1968 if (!PTy->getPointeeType()->isObjectType()) {
1969 if (PTy->getPointeeType()->isVoidType()) {
1970 Diag(loc, diag::ext_gnu_void_ptr,
1971 lex->getSourceRange(), rex->getSourceRange());
1972 } else {
1973 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1974 lex->getType().getAsString(), lex->getSourceRange());
1975 return QualType();
1976 }
1977 }
1978 return PExp->getType();
1979 }
1980 }
1981
Chris Lattnerca5eede2007-12-12 05:47:28 +00001982 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001983}
1984
Chris Lattnereca7be62008-04-07 05:30:13 +00001985// C99 6.5.6
1986QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1987 SourceLocation loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00001988 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001989 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001990
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001991 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001992
Chris Lattner6e4ab612007-12-09 21:53:25 +00001993 // Enforce type constraints: C99 6.5.6p3.
1994
1995 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001996 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001997 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001998
1999 // Either ptr - int or ptr - ptr.
2000 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002001 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002002
Chris Lattner6e4ab612007-12-09 21:53:25 +00002003 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002004 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002005 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002006 if (lpointee->isVoidType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002007 Diag(loc, diag::ext_gnu_void_ptr,
2008 lex->getSourceRange(), rex->getSourceRange());
2009 } else {
2010 Diag(loc, diag::err_typecheck_sub_ptr_object,
2011 lex->getType().getAsString(), lex->getSourceRange());
2012 return QualType();
2013 }
2014 }
2015
2016 // The result type of a pointer-int computation is the pointer type.
2017 if (rex->getType()->isIntegerType())
2018 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002019
Chris Lattner6e4ab612007-12-09 21:53:25 +00002020 // Handle pointer-pointer subtractions.
2021 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002022 QualType rpointee = RHSPTy->getPointeeType();
2023
Chris Lattner6e4ab612007-12-09 21:53:25 +00002024 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002025 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002026 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002027 if (rpointee->isVoidType()) {
2028 if (!lpointee->isVoidType())
Chris Lattner6e4ab612007-12-09 21:53:25 +00002029 Diag(loc, diag::ext_gnu_void_ptr,
2030 lex->getSourceRange(), rex->getSourceRange());
2031 } else {
2032 Diag(loc, diag::err_typecheck_sub_ptr_object,
2033 rex->getType().getAsString(), rex->getSourceRange());
2034 return QualType();
2035 }
2036 }
2037
2038 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002039 if (!Context.typesAreCompatible(
2040 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2041 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002042 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2043 lex->getType().getAsString(), rex->getType().getAsString(),
2044 lex->getSourceRange(), rex->getSourceRange());
2045 return QualType();
2046 }
2047
2048 return Context.getPointerDiffType();
2049 }
2050 }
2051
Chris Lattnerca5eede2007-12-12 05:47:28 +00002052 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002053}
2054
Chris Lattnereca7be62008-04-07 05:30:13 +00002055// C99 6.5.7
2056QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2057 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002058 // C99 6.5.7p2: Each of the operands shall have integer type.
2059 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2060 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002061
Chris Lattnerca5eede2007-12-12 05:47:28 +00002062 // Shifts don't perform usual arithmetic conversions, they just do integer
2063 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002064 if (!isCompAssign)
2065 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002066 UsualUnaryConversions(rex);
2067
2068 // "The type of the result is that of the promoted left operand."
2069 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002070}
2071
Eli Friedman3d815e72008-08-22 00:56:42 +00002072static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2073 ASTContext& Context) {
2074 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2075 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2076 // ID acts sort of like void* for ObjC interfaces
2077 if (LHSIface && Context.isObjCIdType(RHS))
2078 return true;
2079 if (RHSIface && Context.isObjCIdType(LHS))
2080 return true;
2081 if (!LHSIface || !RHSIface)
2082 return false;
2083 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2084 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2085}
2086
Chris Lattnereca7be62008-04-07 05:30:13 +00002087// C99 6.5.8
2088QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2089 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002090 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2091 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2092
Chris Lattnera5937dd2007-08-26 01:18:55 +00002093 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002094 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2095 UsualArithmeticConversions(lex, rex);
2096 else {
2097 UsualUnaryConversions(lex);
2098 UsualUnaryConversions(rex);
2099 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002100 QualType lType = lex->getType();
2101 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002102
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002103 // For non-floating point types, check for self-comparisons of the form
2104 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2105 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002106 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002107 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2108 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002109 if (DRL->getDecl() == DRR->getDecl())
2110 Diag(loc, diag::warn_selfcomparison);
2111 }
2112
Chris Lattnera5937dd2007-08-26 01:18:55 +00002113 if (isRelational) {
2114 if (lType->isRealType() && rType->isRealType())
2115 return Context.IntTy;
2116 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002117 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002118 if (lType->isFloatingType()) {
2119 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002120 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002121 }
2122
Chris Lattnera5937dd2007-08-26 01:18:55 +00002123 if (lType->isArithmeticType() && rType->isArithmeticType())
2124 return Context.IntTy;
2125 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002126
Chris Lattnerd28f8152007-08-26 01:10:14 +00002127 bool LHSIsNull = lex->isNullPointerConstant(Context);
2128 bool RHSIsNull = rex->isNullPointerConstant(Context);
2129
Chris Lattnera5937dd2007-08-26 01:18:55 +00002130 // All of the following pointer related warnings are GCC extensions, except
2131 // when handling null pointer constants. One day, we can consider making them
2132 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002133 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002134 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002135 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002136 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002137 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002138
Steve Naroff66296cb2007-11-13 14:57:38 +00002139 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002140 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2141 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002142 RCanPointeeTy.getUnqualifiedType()) &&
2143 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002144 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2145 lType.getAsString(), rType.getAsString(),
2146 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002147 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002148 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002149 return Context.IntTy;
2150 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002151 // Handle block pointer types.
2152 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2153 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2154 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2155
2156 if (!LHSIsNull && !RHSIsNull &&
2157 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2158 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2159 lType.getAsString(), rType.getAsString(),
2160 lex->getSourceRange(), rex->getSourceRange());
2161 }
2162 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2163 return Context.IntTy;
2164 }
Steve Naroff59f53942008-09-28 01:11:11 +00002165 // Allow block pointers to be compared with null pointer constants.
2166 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2167 (lType->isPointerType() && rType->isBlockPointerType())) {
2168 if (!LHSIsNull && !RHSIsNull) {
2169 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2170 lType.getAsString(), rType.getAsString(),
2171 lex->getSourceRange(), rex->getSourceRange());
2172 }
2173 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2174 return Context.IntTy;
2175 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002176
Steve Naroff20373222008-06-03 14:04:54 +00002177 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002178 if (lType->isPointerType() || rType->isPointerType()) {
2179 if (!Context.typesAreCompatible(lType, rType)) {
2180 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2181 lType.getAsString(), rType.getAsString(),
2182 lex->getSourceRange(), rex->getSourceRange());
2183 ImpCastExprToType(rex, lType);
2184 return Context.IntTy;
2185 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002186 ImpCastExprToType(rex, lType);
Steve Naroff8970fea2008-10-22 22:40:28 +00002187 return Context.IntTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002188 }
Steve Naroff20373222008-06-03 14:04:54 +00002189 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2190 ImpCastExprToType(rex, lType);
2191 return Context.IntTy;
Steve Naroff39579072008-10-14 22:18:38 +00002192 } else {
2193 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2194 Diag(loc, diag::warn_incompatible_qualified_id_operands,
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002195 lType.getAsString(), rType.getAsString(),
Steve Naroff39579072008-10-14 22:18:38 +00002196 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002197 ImpCastExprToType(rex, lType);
Steve Naroff8970fea2008-10-22 22:40:28 +00002198 return Context.IntTy;
Steve Naroff39579072008-10-14 22:18:38 +00002199 }
Steve Naroff20373222008-06-03 14:04:54 +00002200 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002201 }
Steve Naroff20373222008-06-03 14:04:54 +00002202 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2203 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002204 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002205 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2206 lType.getAsString(), rType.getAsString(),
2207 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002208 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002209 return Context.IntTy;
2210 }
Steve Naroff20373222008-06-03 14:04:54 +00002211 if (lType->isIntegerType() &&
2212 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002213 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002214 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2215 lType.getAsString(), rType.getAsString(),
2216 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002217 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002218 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002219 }
Steve Naroff39218df2008-09-04 16:56:14 +00002220 // Handle block pointers.
2221 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2222 if (!RHSIsNull)
2223 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2224 lType.getAsString(), rType.getAsString(),
2225 lex->getSourceRange(), rex->getSourceRange());
2226 ImpCastExprToType(rex, lType); // promote the integer to pointer
2227 return Context.IntTy;
2228 }
2229 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2230 if (!LHSIsNull)
2231 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2232 lType.getAsString(), rType.getAsString(),
2233 lex->getSourceRange(), rex->getSourceRange());
2234 ImpCastExprToType(lex, rType); // promote the integer to pointer
2235 return Context.IntTy;
2236 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00002237 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002238}
2239
Nate Begemanbe2341d2008-07-14 18:02:46 +00002240/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2241/// operates on extended vector types. Instead of producing an IntTy result,
2242/// like a scalar comparison, a vector comparison produces a vector of integer
2243/// types.
2244QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2245 SourceLocation loc,
2246 bool isRelational) {
2247 // Check to make sure we're operating on vectors of the same type and width,
2248 // Allowing one side to be a scalar of element type.
2249 QualType vType = CheckVectorOperands(loc, lex, rex);
2250 if (vType.isNull())
2251 return vType;
2252
2253 QualType lType = lex->getType();
2254 QualType rType = rex->getType();
2255
2256 // For non-floating point types, check for self-comparisons of the form
2257 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2258 // often indicate logic errors in the program.
2259 if (!lType->isFloatingType()) {
2260 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2261 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2262 if (DRL->getDecl() == DRR->getDecl())
2263 Diag(loc, diag::warn_selfcomparison);
2264 }
2265
2266 // Check for comparisons of floating point operands using != and ==.
2267 if (!isRelational && lType->isFloatingType()) {
2268 assert (rType->isFloatingType());
2269 CheckFloatComparison(loc,lex,rex);
2270 }
2271
2272 // Return the type for the comparison, which is the same as vector type for
2273 // integer vectors, or an integer type of identical size and number of
2274 // elements for floating point vectors.
2275 if (lType->isIntegerType())
2276 return lType;
2277
2278 const VectorType *VTy = lType->getAsVectorType();
2279
2280 // FIXME: need to deal with non-32b int / non-64b long long
2281 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2282 if (TypeSize == 32) {
2283 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2284 }
2285 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2286 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2287}
2288
Reid Spencer5f016e22007-07-11 17:01:13 +00002289inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002290 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002291{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002292 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002294
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002295 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002296
Steve Naroffa4332e22007-07-17 00:58:39 +00002297 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002298 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002299 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002300}
2301
2302inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00002303 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002304{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002305 UsualUnaryConversions(lex);
2306 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002307
Eli Friedman5773a6c2008-05-13 20:16:47 +00002308 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002309 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002310 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002311}
2312
2313inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00002314 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002315{
2316 QualType lhsType = lex->getType();
2317 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner28be73f2008-07-26 21:30:36 +00002318 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002319
2320 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00002321 case Expr::MLV_Valid:
2322 break;
2323 case Expr::MLV_ConstQualified:
2324 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2325 return QualType();
2326 case Expr::MLV_ArrayType:
2327 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2328 lhsType.getAsString(), lex->getSourceRange());
2329 return QualType();
2330 case Expr::MLV_NotObjectType:
2331 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2332 lhsType.getAsString(), lex->getSourceRange());
2333 return QualType();
2334 case Expr::MLV_InvalidExpression:
2335 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2336 lex->getSourceRange());
2337 return QualType();
2338 case Expr::MLV_IncompleteType:
2339 case Expr::MLV_IncompleteVoidType:
2340 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2341 lhsType.getAsString(), lex->getSourceRange());
2342 return QualType();
2343 case Expr::MLV_DuplicateVectorComponents:
2344 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2345 lex->getSourceRange());
2346 return QualType();
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002347 case Expr::MLV_NotBlockQualified:
2348 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2349 lex->getSourceRange());
2350 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002351 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002352
Chris Lattner5cf216b2008-01-04 18:04:52 +00002353 AssignConvertType ConvTy;
Chris Lattner2c156472008-08-21 18:04:13 +00002354 if (compoundType.isNull()) {
2355 // Simple assignment "x = y".
Chris Lattner5cf216b2008-01-04 18:04:52 +00002356 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner2c156472008-08-21 18:04:13 +00002357
2358 // If the RHS is a unary plus or minus, check to see if they = and + are
2359 // right next to each other. If so, the user may have typo'd "x =+ 4"
2360 // instead of "x += 4".
2361 Expr *RHSCheck = rex;
2362 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2363 RHSCheck = ICE->getSubExpr();
2364 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2365 if ((UO->getOpcode() == UnaryOperator::Plus ||
2366 UO->getOpcode() == UnaryOperator::Minus) &&
2367 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2368 // Only if the two operators are exactly adjacent.
2369 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2370 Diag(loc, diag::warn_not_compound_assign,
2371 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2372 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2373 }
2374 } else {
2375 // Compound assignment "x += y"
Chris Lattner5cf216b2008-01-04 18:04:52 +00002376 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner2c156472008-08-21 18:04:13 +00002377 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002378
2379 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2380 rex, "assigning"))
2381 return QualType();
2382
Reid Spencer5f016e22007-07-11 17:01:13 +00002383 // C99 6.5.16p3: The type of an assignment expression is the type of the
2384 // left operand unless the left operand has qualified type, in which case
2385 // it is the unqualified version of the type of the left operand.
2386 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2387 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002388 // C++ 5.17p1: the type of the assignment expression is that of its left
2389 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002390 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002391}
2392
2393inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00002394 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00002395
2396 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2397 DefaultFunctionArrayConversion(rex);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002398 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002399}
2400
Steve Naroff49b45262007-07-13 16:58:59 +00002401/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2402/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00002403QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00002404 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002405 assert(!resType.isNull() && "no type for increment/decrement expression");
2406
Steve Naroff084f9ed2007-08-24 17:20:07 +00002407 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00002408 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00002409 if (pt->getPointeeType()->isVoidType()) {
2410 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2411 } else if (!pt->getPointeeType()->isObjectType()) {
2412 // C99 6.5.2.4p2, 6.5.6p2
Reid Spencer5f016e22007-07-11 17:01:13 +00002413 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2414 resType.getAsString(), op->getSourceRange());
2415 return QualType();
2416 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00002417 } else if (!resType->isRealType()) {
2418 if (resType->isComplexType())
2419 // C99 does not support ++/-- on complex types.
2420 Diag(OpLoc, diag::ext_integer_increment_complex,
2421 resType.getAsString(), op->getSourceRange());
2422 else {
2423 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2424 resType.getAsString(), op->getSourceRange());
2425 return QualType();
2426 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002427 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002428 // At this point, we know we have a real, complex or pointer type.
2429 // Now make sure the operand is a modifiable lvalue.
Chris Lattner28be73f2008-07-26 21:30:36 +00002430 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002431 if (mlval != Expr::MLV_Valid) {
2432 // FIXME: emit a more precise diagnostic...
2433 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2434 op->getSourceRange());
2435 return QualType();
2436 }
2437 return resType;
2438}
2439
Anders Carlsson369dee42008-02-01 07:15:58 +00002440/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002441/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002442/// where the declaration is needed for type checking. We only need to
2443/// handle cases when the expression references a function designator
2444/// or is an lvalue. Here are some examples:
2445/// - &(x) => x
2446/// - &*****f => f for f a function designator.
2447/// - &s.xx => s
2448/// - &s.zz[1].yy -> s, if zz is an array
2449/// - *(x + 1) -> x, if x is an array
2450/// - &"123"[2] -> 0
2451/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002452static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002453 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002454 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002455 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002456 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002457 // Fields cannot be declared with a 'register' storage class.
2458 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002459 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002460 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002461 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002462 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002463 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002464
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002465 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00002466 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002467 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002468 return 0;
2469 else
2470 return VD;
2471 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002472 case Stmt::UnaryOperatorClass: {
2473 UnaryOperator *UO = cast<UnaryOperator>(E);
2474
2475 switch(UO->getOpcode()) {
2476 case UnaryOperator::Deref: {
2477 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002478 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2479 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2480 if (!VD || VD->getType()->isPointerType())
2481 return 0;
2482 return VD;
2483 }
2484 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002485 }
2486 case UnaryOperator::Real:
2487 case UnaryOperator::Imag:
2488 case UnaryOperator::Extension:
2489 return getPrimaryDecl(UO->getSubExpr());
2490 default:
2491 return 0;
2492 }
2493 }
2494 case Stmt::BinaryOperatorClass: {
2495 BinaryOperator *BO = cast<BinaryOperator>(E);
2496
2497 // Handle cases involving pointer arithmetic. The result of an
2498 // Assign or AddAssign is not an lvalue so they can be ignored.
2499
2500 // (x + n) or (n + x) => x
2501 if (BO->getOpcode() == BinaryOperator::Add) {
2502 if (BO->getLHS()->getType()->isPointerType()) {
2503 return getPrimaryDecl(BO->getLHS());
2504 } else if (BO->getRHS()->getType()->isPointerType()) {
2505 return getPrimaryDecl(BO->getRHS());
2506 }
2507 }
2508
2509 return 0;
2510 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002511 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002512 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002513 case Stmt::ImplicitCastExprClass:
2514 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002515 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002516 default:
2517 return 0;
2518 }
2519}
2520
2521/// CheckAddressOfOperand - The operand of & must be either a function
2522/// designator or an lvalue designating an object. If it is an lvalue, the
2523/// object cannot be declared with storage class register or be a bit field.
2524/// Note: The usual conversions are *not* applied to the operand of the &
2525/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00002526/// In C++, the operand might be an overloaded function name, in which case
2527/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002528QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002529 if (getLangOptions().C99) {
2530 // Implement C99-only parts of addressof rules.
2531 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2532 if (uOp->getOpcode() == UnaryOperator::Deref)
2533 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2534 // (assuming the deref expression is valid).
2535 return uOp->getSubExpr()->getType();
2536 }
2537 // Technically, there should be a check for array subscript
2538 // expressions here, but the result of one is always an lvalue anyway.
2539 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002540 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002541 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002542
2543 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002544 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2545 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00002546 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2547 op->getSourceRange());
2548 return QualType();
2549 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002550 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2551 if (MemExpr->getMemberDecl()->isBitField()) {
2552 Diag(OpLoc, diag::err_typecheck_address_of,
2553 std::string("bit-field"), op->getSourceRange());
2554 return QualType();
2555 }
2556 // Check for Apple extension for accessing vector components.
2557 } else if (isa<ArraySubscriptExpr>(op) &&
2558 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2559 Diag(OpLoc, diag::err_typecheck_address_of,
2560 std::string("vector"), op->getSourceRange());
2561 return QualType();
2562 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002563 // We have an lvalue with a decl. Make sure the decl is not declared
2564 // with the register storage-class specifier.
2565 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2566 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002567 Diag(OpLoc, diag::err_typecheck_address_of,
2568 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 return QualType();
2570 }
Douglas Gregor904eed32008-11-10 20:40:00 +00002571 } else if (isa<OverloadedFunctionDecl>(dcl))
2572 return Context.OverloadTy;
2573 else
Reid Spencer5f016e22007-07-11 17:01:13 +00002574 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002576
Reid Spencer5f016e22007-07-11 17:01:13 +00002577 // If the operand has type "type", the result has type "pointer to type".
2578 return Context.getPointerType(op->getType());
2579}
2580
2581QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002582 UsualUnaryConversions(op);
2583 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002584
Chris Lattnerbefee482007-07-31 16:53:04 +00002585 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002586 // Note that per both C89 and C99, this is always legal, even
2587 // if ptype is an incomplete type or void.
2588 // It would be possible to warn about dereferencing a
2589 // void pointer, but it's completely well-defined,
2590 // and such a warning is unlikely to catch any mistakes.
2591 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002592 }
2593 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2594 qType.getAsString(), op->getSourceRange());
2595 return QualType();
2596}
2597
2598static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2599 tok::TokenKind Kind) {
2600 BinaryOperator::Opcode Opc;
2601 switch (Kind) {
2602 default: assert(0 && "Unknown binop!");
2603 case tok::star: Opc = BinaryOperator::Mul; break;
2604 case tok::slash: Opc = BinaryOperator::Div; break;
2605 case tok::percent: Opc = BinaryOperator::Rem; break;
2606 case tok::plus: Opc = BinaryOperator::Add; break;
2607 case tok::minus: Opc = BinaryOperator::Sub; break;
2608 case tok::lessless: Opc = BinaryOperator::Shl; break;
2609 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2610 case tok::lessequal: Opc = BinaryOperator::LE; break;
2611 case tok::less: Opc = BinaryOperator::LT; break;
2612 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2613 case tok::greater: Opc = BinaryOperator::GT; break;
2614 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2615 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2616 case tok::amp: Opc = BinaryOperator::And; break;
2617 case tok::caret: Opc = BinaryOperator::Xor; break;
2618 case tok::pipe: Opc = BinaryOperator::Or; break;
2619 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2620 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2621 case tok::equal: Opc = BinaryOperator::Assign; break;
2622 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2623 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2624 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2625 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2626 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2627 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2628 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2629 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2630 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2631 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2632 case tok::comma: Opc = BinaryOperator::Comma; break;
2633 }
2634 return Opc;
2635}
2636
2637static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2638 tok::TokenKind Kind) {
2639 UnaryOperator::Opcode Opc;
2640 switch (Kind) {
2641 default: assert(0 && "Unknown unary op!");
2642 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2643 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2644 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2645 case tok::star: Opc = UnaryOperator::Deref; break;
2646 case tok::plus: Opc = UnaryOperator::Plus; break;
2647 case tok::minus: Opc = UnaryOperator::Minus; break;
2648 case tok::tilde: Opc = UnaryOperator::Not; break;
2649 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 case tok::kw___real: Opc = UnaryOperator::Real; break;
2651 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2652 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2653 }
2654 return Opc;
2655}
2656
Douglas Gregoreaebc752008-11-06 23:29:22 +00002657/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2658/// operator @p Opc at location @c TokLoc. This routine only supports
2659/// built-in operations; ActOnBinOp handles overloaded operators.
2660Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2661 unsigned Op,
2662 Expr *lhs, Expr *rhs) {
2663 QualType ResultTy; // Result type of the binary operator.
2664 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2665 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2666
2667 switch (Opc) {
2668 default:
2669 assert(0 && "Unknown binary expr!");
2670 case BinaryOperator::Assign:
2671 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2672 break;
2673 case BinaryOperator::Mul:
2674 case BinaryOperator::Div:
2675 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2676 break;
2677 case BinaryOperator::Rem:
2678 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2679 break;
2680 case BinaryOperator::Add:
2681 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2682 break;
2683 case BinaryOperator::Sub:
2684 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2685 break;
2686 case BinaryOperator::Shl:
2687 case BinaryOperator::Shr:
2688 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2689 break;
2690 case BinaryOperator::LE:
2691 case BinaryOperator::LT:
2692 case BinaryOperator::GE:
2693 case BinaryOperator::GT:
2694 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2695 break;
2696 case BinaryOperator::EQ:
2697 case BinaryOperator::NE:
2698 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2699 break;
2700 case BinaryOperator::And:
2701 case BinaryOperator::Xor:
2702 case BinaryOperator::Or:
2703 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2704 break;
2705 case BinaryOperator::LAnd:
2706 case BinaryOperator::LOr:
2707 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2708 break;
2709 case BinaryOperator::MulAssign:
2710 case BinaryOperator::DivAssign:
2711 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2712 if (!CompTy.isNull())
2713 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2714 break;
2715 case BinaryOperator::RemAssign:
2716 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2717 if (!CompTy.isNull())
2718 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2719 break;
2720 case BinaryOperator::AddAssign:
2721 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2722 if (!CompTy.isNull())
2723 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2724 break;
2725 case BinaryOperator::SubAssign:
2726 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2727 if (!CompTy.isNull())
2728 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2729 break;
2730 case BinaryOperator::ShlAssign:
2731 case BinaryOperator::ShrAssign:
2732 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2733 if (!CompTy.isNull())
2734 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2735 break;
2736 case BinaryOperator::AndAssign:
2737 case BinaryOperator::XorAssign:
2738 case BinaryOperator::OrAssign:
2739 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2740 if (!CompTy.isNull())
2741 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2742 break;
2743 case BinaryOperator::Comma:
2744 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2745 break;
2746 }
2747 if (ResultTy.isNull())
2748 return true;
2749 if (CompTy.isNull())
2750 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2751 else
2752 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2753}
2754
Reid Spencer5f016e22007-07-11 17:01:13 +00002755// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00002756Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2757 tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002758 ExprTy *LHS, ExprTy *RHS) {
2759 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2760 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2761
Steve Narofff69936d2007-09-16 03:34:24 +00002762 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2763 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002764
Douglas Gregoreaebc752008-11-06 23:29:22 +00002765 if (getLangOptions().CPlusPlus &&
2766 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2767 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
2768 // C++ [over.binary]p1:
2769 // A binary operator shall be implemented either by a non-static
2770 // member function (9.3) with one parameter or by a non-member
2771 // function with two parameters. Thus, for any binary operator
2772 // @, x@y can be interpreted as either x.operator@(y) or
2773 // operator@(x,y). If both forms of the operator function have
2774 // been declared, the rules in 13.3.1.2 determines which, if
2775 // any, interpretation is used.
2776 OverloadCandidateSet CandidateSet;
2777
2778 // Determine which overloaded operator we're dealing with.
2779 static const OverloadedOperatorKind OverOps[] = {
2780 OO_Star, OO_Slash, OO_Percent,
2781 OO_Plus, OO_Minus,
2782 OO_LessLess, OO_GreaterGreater,
2783 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2784 OO_EqualEqual, OO_ExclaimEqual,
2785 OO_Amp,
2786 OO_Caret,
2787 OO_Pipe,
2788 OO_AmpAmp,
2789 OO_PipePipe,
2790 OO_Equal, OO_StarEqual,
2791 OO_SlashEqual, OO_PercentEqual,
2792 OO_PlusEqual, OO_MinusEqual,
2793 OO_LessLessEqual, OO_GreaterGreaterEqual,
2794 OO_AmpEqual, OO_CaretEqual,
2795 OO_PipeEqual,
2796 OO_Comma
2797 };
2798 OverloadedOperatorKind OverOp = OverOps[Opc];
2799
2800 // Lookup this operator.
2801 Decl *D = LookupDecl(&PP.getIdentifierTable().getOverloadedOperator(OverOp),
2802 Decl::IDNS_Ordinary, S);
2803
2804 // Add any overloaded operators we find to the overload set.
2805 Expr *Args[2] = { lhs, rhs };
2806 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2807 AddOverloadCandidate(FD, Args, 2, CandidateSet);
2808 else if (OverloadedFunctionDecl *Ovl
2809 = dyn_cast_or_null<OverloadedFunctionDecl>(D))
2810 AddOverloadCandidates(Ovl, Args, 2, CandidateSet);
2811
2812 // FIXME: Add builtin overload candidates (C++ [over.built]).
2813
2814 // Perform overload resolution.
2815 OverloadCandidateSet::iterator Best;
2816 switch (BestViableFunction(CandidateSet, Best)) {
2817 case OR_Success: {
2818 // FIXME: We might find a built-in candidate here.
2819 FunctionDecl *FnDecl = Best->Function;
2820
2821 // Convert the arguments.
2822 // FIXME: Conversion will be different for member operators.
2823 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
2824 "passing") ||
2825 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
2826 "passing"))
2827 return true;
2828
2829 // Determine the result type
2830 QualType ResultTy
2831 = FnDecl->getType()->getAsFunctionType()->getResultType();
2832 ResultTy = ResultTy.getNonReferenceType();
2833
2834 // Build the actual expression node.
2835 // FIXME: We lose the fact that we have a function here!
2836 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
2837 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, ResultTy,
2838 TokLoc);
2839 else
2840 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
2841 }
2842
2843 case OR_No_Viable_Function:
2844 // No viable function; fall through to handling this as a
2845 // built-in operator.
2846 break;
2847
2848 case OR_Ambiguous:
2849 Diag(TokLoc,
2850 diag::err_ovl_ambiguous_oper,
2851 BinaryOperator::getOpcodeStr(Opc),
2852 lhs->getSourceRange(), rhs->getSourceRange());
2853 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2854 return true;
2855 }
2856
2857 // There was no viable overloaded operator; fall through.
2858 }
2859
Reid Spencer5f016e22007-07-11 17:01:13 +00002860
Douglas Gregoreaebc752008-11-06 23:29:22 +00002861 // Build a built-in binary operation.
2862 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00002863}
2864
2865// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002866Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 ExprTy *input) {
2868 Expr *Input = (Expr*)input;
2869 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2870 QualType resultType;
2871 switch (Opc) {
2872 default:
2873 assert(0 && "Unimplemented unary expr!");
2874 case UnaryOperator::PreInc:
2875 case UnaryOperator::PreDec:
2876 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2877 break;
2878 case UnaryOperator::AddrOf:
2879 resultType = CheckAddressOfOperand(Input, OpLoc);
2880 break;
2881 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002882 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002883 resultType = CheckIndirectionOperand(Input, OpLoc);
2884 break;
2885 case UnaryOperator::Plus:
2886 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002887 UsualUnaryConversions(Input);
2888 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002889 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2890 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2891 resultType.getAsString());
2892 break;
2893 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002894 UsualUnaryConversions(Input);
2895 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00002896 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2897 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2898 // C99 does not support '~' for complex conjugation.
2899 Diag(OpLoc, diag::ext_integer_complement_complex,
2900 resultType.getAsString(), Input->getSourceRange());
2901 else if (!resultType->isIntegerType())
2902 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2903 resultType.getAsString(), Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002904 break;
2905 case UnaryOperator::LNot: // logical negation
2906 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002907 DefaultFunctionArrayConversion(Input);
2908 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002909 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2910 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2911 resultType.getAsString());
2912 // LNot always has type int. C99 6.5.3.3p5.
2913 resultType = Context.IntTy;
2914 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002915 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002916 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002917 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002918 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002920 resultType = Input->getType();
2921 break;
2922 }
2923 if (resultType.isNull())
2924 return true;
2925 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2926}
2927
Steve Naroff1b273c42007-09-16 14:56:35 +00002928/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2929Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002930 SourceLocation LabLoc,
2931 IdentifierInfo *LabelII) {
2932 // Look up the record for this label identifier.
2933 LabelStmt *&LabelDecl = LabelMap[LabelII];
2934
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00002935 // If we haven't seen this label yet, create a forward reference. It
2936 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 if (LabelDecl == 0)
2938 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2939
2940 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00002941 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2942 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00002943}
2944
Steve Naroff1b273c42007-09-16 14:56:35 +00002945Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002946 SourceLocation RPLoc) { // "({..})"
2947 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2948 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2949 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2950
2951 // FIXME: there are a variety of strange constraints to enforce here, for
2952 // example, it is not possible to goto into a stmt expression apparently.
2953 // More semantic analysis is needed.
2954
2955 // FIXME: the last statement in the compount stmt has its value used. We
2956 // should not warn about it being unused.
2957
2958 // If there are sub stmts in the compound stmt, take the type of the last one
2959 // as the type of the stmtexpr.
2960 QualType Ty = Context.VoidTy;
2961
Chris Lattner611b2ec2008-07-26 19:51:01 +00002962 if (!Compound->body_empty()) {
2963 Stmt *LastStmt = Compound->body_back();
2964 // If LastStmt is a label, skip down through into the body.
2965 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2966 LastStmt = Label->getSubStmt();
2967
2968 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002969 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00002970 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002971
2972 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2973}
Steve Naroffd34e9152007-08-01 22:05:33 +00002974
Steve Naroff1b273c42007-09-16 14:56:35 +00002975Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002976 SourceLocation TypeLoc,
2977 TypeTy *argty,
2978 OffsetOfComponent *CompPtr,
2979 unsigned NumComponents,
2980 SourceLocation RPLoc) {
2981 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2982 assert(!ArgTy.isNull() && "Missing type argument!");
2983
2984 // We must have at least one component that refers to the type, and the first
2985 // one is known to be a field designator. Verify that the ArgTy represents
2986 // a struct/union/class.
2987 if (!ArgTy->isRecordType())
2988 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2989
2990 // Otherwise, create a compound literal expression as the base, and
2991 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00002992 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002993
Chris Lattner9e2b75c2007-08-31 21:49:13 +00002994 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2995 // GCC extension, diagnose them.
2996 if (NumComponents != 1)
2997 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2998 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2999
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003000 for (unsigned i = 0; i != NumComponents; ++i) {
3001 const OffsetOfComponent &OC = CompPtr[i];
3002 if (OC.isBrackets) {
3003 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003004 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003005 if (!AT) {
3006 delete Res;
3007 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
3008 Res->getType().getAsString());
3009 }
3010
Chris Lattner704fe352007-08-30 17:59:59 +00003011 // FIXME: C++: Verify that operator[] isn't overloaded.
3012
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003013 // C99 6.5.2.1p1
3014 Expr *Idx = static_cast<Expr*>(OC.U.E);
3015 if (!Idx->getType()->isIntegerType())
3016 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
3017 Idx->getSourceRange());
3018
3019 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3020 continue;
3021 }
3022
3023 const RecordType *RC = Res->getType()->getAsRecordType();
3024 if (!RC) {
3025 delete Res;
3026 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
3027 Res->getType().getAsString());
3028 }
3029
3030 // Get the decl corresponding to this.
3031 RecordDecl *RD = RC->getDecl();
3032 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3033 if (!MemberDecl)
3034 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
3035 OC.U.IdentInfo->getName(),
3036 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00003037
3038 // FIXME: C++: Verify that MemberDecl isn't a static field.
3039 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00003040 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3041 // matter here.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003042 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3043 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003044 }
3045
3046 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3047 BuiltinLoc);
3048}
3049
3050
Steve Naroff1b273c42007-09-16 14:56:35 +00003051Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00003052 TypeTy *arg1, TypeTy *arg2,
3053 SourceLocation RPLoc) {
3054 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3055 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3056
3057 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3058
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003059 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00003060}
3061
Steve Naroff1b273c42007-09-16 14:56:35 +00003062Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00003063 ExprTy *expr1, ExprTy *expr2,
3064 SourceLocation RPLoc) {
3065 Expr *CondExpr = static_cast<Expr*>(cond);
3066 Expr *LHSExpr = static_cast<Expr*>(expr1);
3067 Expr *RHSExpr = static_cast<Expr*>(expr2);
3068
3069 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3070
3071 // The conditional expression is required to be a constant expression.
3072 llvm::APSInt condEval(32);
3073 SourceLocation ExpLoc;
3074 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
3075 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
3076 CondExpr->getSourceRange());
3077
3078 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3079 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3080 RHSExpr->getType();
3081 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3082}
3083
Steve Naroff4eb206b2008-09-03 18:15:37 +00003084//===----------------------------------------------------------------------===//
3085// Clang Extensions.
3086//===----------------------------------------------------------------------===//
3087
3088/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00003089void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003090 // Analyze block parameters.
3091 BlockSemaInfo *BSI = new BlockSemaInfo();
3092
3093 // Add BSI to CurBlock.
3094 BSI->PrevBlockInfo = CurBlock;
3095 CurBlock = BSI;
3096
3097 BSI->ReturnType = 0;
3098 BSI->TheScope = BlockScope;
3099
Steve Naroff090276f2008-10-10 01:28:17 +00003100 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3101 PushDeclContext(BSI->TheDecl);
3102}
3103
3104void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003105 // Analyze arguments to block.
3106 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3107 "Not a function declarator!");
3108 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3109
Steve Naroff090276f2008-10-10 01:28:17 +00003110 CurBlock->hasPrototype = FTI.hasPrototype;
3111 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003112
3113 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3114 // no arguments, not a function that takes a single void argument.
3115 if (FTI.hasPrototype &&
3116 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3117 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3118 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3119 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00003120 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003121 } else if (FTI.hasPrototype) {
3122 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00003123 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3124 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003125 }
Steve Naroff090276f2008-10-10 01:28:17 +00003126 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3127
3128 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3129 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3130 // If this has an identifier, add it to the scope stack.
3131 if ((*AI)->getIdentifier())
3132 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003133}
3134
3135/// ActOnBlockError - If there is an error parsing a block, this callback
3136/// is invoked to pop the information about the block from the action impl.
3137void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3138 // Ensure that CurBlock is deleted.
3139 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3140
3141 // Pop off CurBlock, handle nested blocks.
3142 CurBlock = CurBlock->PrevBlockInfo;
3143
3144 // FIXME: Delete the ParmVarDecl objects as well???
3145
3146}
3147
3148/// ActOnBlockStmtExpr - This is called when the body of a block statement
3149/// literal was successfully completed. ^(int x){...}
3150Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3151 Scope *CurScope) {
3152 // Ensure that CurBlock is deleted.
3153 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3154 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3155
Steve Naroff090276f2008-10-10 01:28:17 +00003156 PopDeclContext();
3157
Steve Naroff4eb206b2008-09-03 18:15:37 +00003158 // Pop off CurBlock, handle nested blocks.
3159 CurBlock = CurBlock->PrevBlockInfo;
3160
3161 QualType RetTy = Context.VoidTy;
3162 if (BSI->ReturnType)
3163 RetTy = QualType(BSI->ReturnType, 0);
3164
3165 llvm::SmallVector<QualType, 8> ArgTypes;
3166 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3167 ArgTypes.push_back(BSI->Params[i]->getType());
3168
3169 QualType BlockTy;
3170 if (!BSI->hasPrototype)
3171 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3172 else
3173 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003174 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003175
3176 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003177
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003178 BSI->TheDecl->setBody(Body.take());
3179 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003180}
3181
Nate Begeman67295d02008-01-30 20:50:20 +00003182/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003183/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003184/// The number of arguments has already been validated to match the number of
3185/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003186static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3187 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003188 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003189 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003190 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3191 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003192
3193 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00003194 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00003195 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003196 return true;
3197}
3198
3199Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3200 SourceLocation *CommaLocs,
3201 SourceLocation BuiltinLoc,
3202 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003203 // __builtin_overload requires at least 2 arguments
3204 if (NumArgs < 2)
3205 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3206 SourceRange(BuiltinLoc, RParenLoc));
Nate Begemane2ce1d92008-01-17 17:46:27 +00003207
Nate Begemane2ce1d92008-01-17 17:46:27 +00003208 // The first argument is required to be a constant expression. It tells us
3209 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003210 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003211 Expr *NParamsExpr = Args[0];
3212 llvm::APSInt constEval(32);
3213 SourceLocation ExpLoc;
3214 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3215 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3216 NParamsExpr->getSourceRange());
3217
3218 // Verify that the number of parameters is > 0
3219 unsigned NumParams = constEval.getZExtValue();
3220 if (NumParams == 0)
3221 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3222 NParamsExpr->getSourceRange());
3223 // Verify that we have at least 1 + NumParams arguments to the builtin.
3224 if ((NumParams + 1) > NumArgs)
3225 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3226 SourceRange(BuiltinLoc, RParenLoc));
3227
3228 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00003229 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003230 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003231 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3232 // UsualUnaryConversions will convert the function DeclRefExpr into a
3233 // pointer to function.
3234 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00003235 const FunctionTypeProto *FnType = 0;
3236 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3237 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003238
3239 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3240 // parameters, and the number of parameters must match the value passed to
3241 // the builtin.
3242 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begeman67295d02008-01-30 20:50:20 +00003243 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3244 Fn->getSourceRange());
Nate Begemane2ce1d92008-01-17 17:46:27 +00003245
3246 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00003247 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00003248 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003249 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003250 if (OE)
3251 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3252 OE->getFn()->getSourceRange());
3253 // Remember our match, and continue processing the remaining arguments
3254 // to catch any errors.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003255 OE = new OverloadExpr(Args, NumArgs, i,
3256 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00003257 BuiltinLoc, RParenLoc);
3258 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003259 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00003260 // Return the newly created OverloadExpr node, if we succeded in matching
3261 // exactly one of the candidate functions.
3262 if (OE)
3263 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003264
3265 // If we didn't find a matching function Expr in the __builtin_overload list
3266 // the return an error.
3267 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00003268 for (unsigned i = 0; i != NumParams; ++i) {
3269 if (i != 0) typeNames += ", ";
3270 typeNames += Args[i+1]->getType().getAsString();
3271 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003272
3273 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3274 SourceRange(BuiltinLoc, RParenLoc));
3275}
3276
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003277Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3278 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00003279 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003280 Expr *E = static_cast<Expr*>(expr);
3281 QualType T = QualType::getFromOpaquePtr(type);
3282
3283 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003284
3285 // Get the va_list type
3286 QualType VaListType = Context.getBuiltinVaListType();
3287 // Deal with implicit array decay; for example, on x86-64,
3288 // va_list is an array, but it's supposed to decay to
3289 // a pointer for va_arg.
3290 if (VaListType->isArrayType())
3291 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00003292 // Make sure the input expression also decays appropriately.
3293 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003294
3295 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003296 return Diag(E->getLocStart(),
3297 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3298 E->getType().getAsString(),
3299 E->getSourceRange());
3300
3301 // FIXME: Warn if a non-POD type is passed in.
3302
Douglas Gregor9d293df2008-10-28 00:22:11 +00003303 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003304}
3305
Chris Lattner5cf216b2008-01-04 18:04:52 +00003306bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3307 SourceLocation Loc,
3308 QualType DstType, QualType SrcType,
3309 Expr *SrcExpr, const char *Flavor) {
3310 // Decode the result (notice that AST's are still created for extensions).
3311 bool isInvalid = false;
3312 unsigned DiagKind;
3313 switch (ConvTy) {
3314 default: assert(0 && "Unknown conversion type");
3315 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003316 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00003317 DiagKind = diag::ext_typecheck_convert_pointer_int;
3318 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003319 case IntToPointer:
3320 DiagKind = diag::ext_typecheck_convert_int_pointer;
3321 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003322 case IncompatiblePointer:
3323 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3324 break;
3325 case FunctionVoidPointer:
3326 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3327 break;
3328 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00003329 // If the qualifiers lost were because we were applying the
3330 // (deprecated) C++ conversion from a string literal to a char*
3331 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3332 // Ideally, this check would be performed in
3333 // CheckPointerTypesForAssignment. However, that would require a
3334 // bit of refactoring (so that the second argument is an
3335 // expression, rather than a type), which should be done as part
3336 // of a larger effort to fix CheckPointerTypesForAssignment for
3337 // C++ semantics.
3338 if (getLangOptions().CPlusPlus &&
3339 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3340 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003341 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3342 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003343 case IntToBlockPointer:
3344 DiagKind = diag::err_int_to_block_pointer;
3345 break;
3346 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00003347 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003348 break;
3349 case BlockVoidPointer:
3350 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3351 break;
Steve Naroff39579072008-10-14 22:18:38 +00003352 case IncompatibleObjCQualifiedId:
3353 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3354 // it can give a more specific diagnostic.
3355 DiagKind = diag::warn_incompatible_qualified_id;
3356 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003357 case Incompatible:
3358 DiagKind = diag::err_typecheck_convert_incompatible;
3359 isInvalid = true;
3360 break;
3361 }
3362
3363 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3364 SrcExpr->getSourceRange());
3365 return isInvalid;
3366}