blob: f4ef2839855b803af6b164ec4f3d470449f4de88 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000015#include "SemaUtil.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000018#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000023#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Steve Naroff87d58b42007-09-16 03:34:24 +000028/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000029/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000035Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000036 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +000045
46 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000047 if (Literal.Pascal && Literal.GetStringLength() > 256)
48 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
49 SourceRange(StringToks[0].getLocation(),
50 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000051
Chris Lattnera6dcce32008-02-11 00:02:17 +000052 QualType StrTy = Context.CharTy;
53 // FIXME: handle wchar_t
54 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
55
56 // Get an array type for the string, according to C99 6.4.5. This includes
57 // the nul terminator character as well as the string length for pascal
58 // strings.
59 StrTy = Context.getConstantArrayType(StrTy,
60 llvm::APInt(32, Literal.GetStringLength()+1),
61 ArrayType::Normal, 0);
62
Chris Lattner4b009652007-07-25 00:24:17 +000063 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
64 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +000065 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000066 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000067 StringToks[NumStringToks-1].getLocation());
68}
69
70
Steve Naroff0acc9c92007-09-15 18:49:24 +000071/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000072/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +000073/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000074Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000075 IdentifierInfo &II,
76 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000077 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +000078 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000079
80 // If this reference is in an Objective-C method, then ivar lookup happens as
81 // well.
82 if (CurMethodDecl) {
Steve Naroffe57c21a2008-04-01 23:04:06 +000083 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000084 // There are two cases to handle here. 1) scoped lookup could have failed,
85 // in which case we should look for an ivar. 2) scoped lookup could have
86 // found a decl, but that decl is outside the current method (i.e. a global
87 // variable). In these two cases, we do a lookup for an ivar with this
88 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +000089 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000090 ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface(), *DeclClass;
91 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, DeclClass)) {
92 // FIXME: This should use a new expr for a direct reference, don't turn
93 // this into Self->ivar, just return a BareIVarExpr or something.
94 IdentifierInfo &II = Context.Idents.get("self");
95 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
96 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
97 static_cast<Expr*>(SelfExpr.Val), true, true);
98 }
99 }
100 }
101
Chris Lattner4b009652007-07-25 00:24:17 +0000102 if (D == 0) {
103 // Otherwise, this could be an implicitly declared function reference (legal
104 // in C90, extension in C99).
105 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000106 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000107 D = ImplicitlyDefineFunction(Loc, II, S);
108 else {
109 // If this name wasn't predeclared and if this is not a function call,
110 // diagnose the problem.
111 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
112 }
113 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000114
Steve Naroff91b03f72007-08-28 03:03:08 +0000115 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000116 // check if referencing an identifier with __attribute__((deprecated)).
117 if (VD->getAttr<DeprecatedAttr>())
118 Diag(Loc, diag::warn_deprecated, VD->getName());
119
Steve Naroffcae537d2007-08-28 18:45:29 +0000120 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000121 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000122 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000123 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000124 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000125
Chris Lattner4b009652007-07-25 00:24:17 +0000126 if (isa<TypedefDecl>(D))
127 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000128 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000129 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000130
131 assert(0 && "Invalid decl");
132 abort();
133}
134
Steve Naroff87d58b42007-09-16 03:34:24 +0000135Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000136 tok::TokenKind Kind) {
137 PreDefinedExpr::IdentType IT;
138
139 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000140 default: assert(0 && "Unknown simple primary expr!");
141 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
142 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
143 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000144 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000145
146 // Verify that this is in a function context.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000147 if (CurFunctionDecl == 0 && CurMethodDecl == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000148 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000149
Chris Lattner7e637512008-01-12 08:14:25 +0000150 // Pre-defined identifiers are of type char[x], where x is the length of the
151 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000152 unsigned Length;
153 if (CurFunctionDecl)
154 Length = CurFunctionDecl->getIdentifier()->getLength();
155 else
Fariborz Jahaniandcecd5c2008-01-17 17:37:26 +0000156 Length = CurMethodDecl->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000157
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000158 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000159 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000160 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000161 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000162}
163
Steve Naroff87d58b42007-09-16 03:34:24 +0000164Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000165 llvm::SmallString<16> CharBuffer;
166 CharBuffer.resize(Tok.getLength());
167 const char *ThisTokBegin = &CharBuffer[0];
168 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
169
170 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
171 Tok.getLocation(), PP);
172 if (Literal.hadError())
173 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000174
175 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
176
177 return new CharacterLiteral(Literal.getValue(), type, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000178}
179
Steve Naroff87d58b42007-09-16 03:34:24 +0000180Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000181 // fast path for a single digit (which is quite common). A single digit
182 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
183 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000184 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000185
Chris Lattner8cd0e932008-03-05 18:54:05 +0000186 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000187 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000188 Context.IntTy,
189 Tok.getLocation()));
190 }
191 llvm::SmallString<512> IntegerBuffer;
192 IntegerBuffer.resize(Tok.getLength());
193 const char *ThisTokBegin = &IntegerBuffer[0];
194
195 // Get the spelling of the token, which eliminates trigraphs, etc.
196 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
197 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
198 Tok.getLocation(), PP);
199 if (Literal.hadError)
200 return ExprResult(true);
201
Chris Lattner1de66eb2007-08-26 03:42:43 +0000202 Expr *Res;
203
204 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000205 QualType Ty;
206 const llvm::fltSemantics *Format;
Chris Lattner858eece2007-09-22 18:29:59 +0000207
208 if (Literal.isFloat) {
209 Ty = Context.FloatTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000210 Format = Context.Target.getFloatFormat();
211 } else if (!Literal.isLong) {
Chris Lattner858eece2007-09-22 18:29:59 +0000212 Ty = Context.DoubleTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000213 Format = Context.Target.getDoubleFormat();
214 } else {
215 Ty = Context.LongDoubleTy;
216 Format = Context.Target.getLongDoubleFormat();
Chris Lattner858eece2007-09-22 18:29:59 +0000217 }
218
Ted Kremenekddedbe22007-11-29 00:56:49 +0000219 // isExact will be set by GetFloatValue().
220 bool isExact = false;
221
222 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
223 Ty, Tok.getLocation());
224
Chris Lattner1de66eb2007-08-26 03:42:43 +0000225 } else if (!Literal.isIntegerLiteral()) {
226 return ExprResult(true);
227 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000228 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000229
Neil Booth7421e9c2007-08-29 22:00:19 +0000230 // long long is a C99 feature.
231 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000232 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000233 Diag(Tok.getLocation(), diag::ext_longlong);
234
Chris Lattner4b009652007-07-25 00:24:17 +0000235 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000236 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000237
238 if (Literal.GetIntegerValue(ResultVal)) {
239 // If this value didn't fit into uintmax_t, warn and force to ull.
240 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000241 Ty = Context.UnsignedLongLongTy;
242 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000243 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000244 } else {
245 // If this value fits into a ULL, try to figure out what else it fits into
246 // according to the rules of C99 6.4.4.1p5.
247
248 // Octal, Hexadecimal, and integers with a U suffix are allowed to
249 // be an unsigned int.
250 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
251
252 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000253 if (!Literal.isLong && !Literal.isLongLong) {
254 // Are int/unsigned possibilities?
Chris Lattner8cd0e932008-03-05 18:54:05 +0000255 unsigned IntSize =
256 static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000257 // Does it fit in a unsigned int?
258 if (ResultVal.isIntN(IntSize)) {
259 // Does it fit in a signed int?
260 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000261 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000262 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000263 Ty = Context.UnsignedIntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000264 }
265
Chris Lattner48d7f382008-04-02 04:24:33 +0000266 if (!Ty.isNull())
Chris Lattner4b009652007-07-25 00:24:17 +0000267 ResultVal.trunc(IntSize);
268 }
269
270 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000271 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000272 unsigned LongSize =
273 static_cast<unsigned>(Context.getTypeSize(Context.LongTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000274
275 // Does it fit in a unsigned long?
276 if (ResultVal.isIntN(LongSize)) {
277 // Does it fit in a signed long?
278 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000279 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000280 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000281 Ty = Context.UnsignedLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000282 }
Chris Lattner48d7f382008-04-02 04:24:33 +0000283 if (!Ty.isNull())
Chris Lattner4b009652007-07-25 00:24:17 +0000284 ResultVal.trunc(LongSize);
285 }
286
287 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000288 if (Ty.isNull()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000289 unsigned LongLongSize =
290 static_cast<unsigned>(Context.getTypeSize(Context.LongLongTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000291
292 // Does it fit in a unsigned long long?
293 if (ResultVal.isIntN(LongLongSize)) {
294 // Does it fit in a signed long long?
295 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000296 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000297 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000298 Ty = Context.UnsignedLongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000299 }
300 }
301
302 // If we still couldn't decide a type, we probably have something that
303 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000304 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000305 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000306 Ty = Context.UnsignedLongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000307 }
308 }
309
Chris Lattner48d7f382008-04-02 04:24:33 +0000310 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000311 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000312
313 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
314 if (Literal.isImaginary)
315 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
316
317 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000318}
319
Steve Naroff87d58b42007-09-16 03:34:24 +0000320Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000321 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000322 Expr *E = (Expr *)Val;
323 assert((E != 0) && "ActOnParenExpr() missing expr");
324 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000325}
326
327/// The UsualUnaryConversions() function is *not* called by this routine.
328/// See C99 6.3.2.1p[2-4] for more details.
329QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
330 SourceLocation OpLoc, bool isSizeof) {
331 // C99 6.5.3.4p1:
332 if (isa<FunctionType>(exprType) && isSizeof)
333 // alignof(function) is allowed.
334 Diag(OpLoc, diag::ext_sizeof_function_type);
335 else if (exprType->isVoidType())
336 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
337 else if (exprType->isIncompleteType()) {
338 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
339 diag::err_alignof_incomplete_type,
340 exprType.getAsString());
341 return QualType(); // error
342 }
343 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
344 return Context.getSizeType();
345}
346
347Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000348ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000349 SourceLocation LPLoc, TypeTy *Ty,
350 SourceLocation RPLoc) {
351 // If error parsing type, ignore.
352 if (Ty == 0) return true;
353
354 // Verify that this is a valid expression.
355 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
356
357 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
358
359 if (resultType.isNull())
360 return true;
361 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
362}
363
Chris Lattner5110ad52007-08-24 21:41:10 +0000364QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000365 DefaultFunctionArrayConversion(V);
366
Chris Lattnera16e42d2007-08-26 05:39:26 +0000367 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000368 if (const ComplexType *CT = V->getType()->getAsComplexType())
369 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000370
371 // Otherwise they pass through real integer and floating point types here.
372 if (V->getType()->isArithmeticType())
373 return V->getType();
374
375 // Reject anything else.
376 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
377 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000378}
379
380
Chris Lattner4b009652007-07-25 00:24:17 +0000381
Steve Naroff87d58b42007-09-16 03:34:24 +0000382Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000383 tok::TokenKind Kind,
384 ExprTy *Input) {
385 UnaryOperator::Opcode Opc;
386 switch (Kind) {
387 default: assert(0 && "Unknown unary op!");
388 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
389 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
390 }
391 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
392 if (result.isNull())
393 return true;
394 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
395}
396
397Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000398ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000399 ExprTy *Idx, SourceLocation RLoc) {
400 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
401
402 // Perform default conversions.
403 DefaultFunctionArrayConversion(LHSExp);
404 DefaultFunctionArrayConversion(RHSExp);
405
406 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
407
408 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000409 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000410 // in the subscript position. As a result, we need to derive the array base
411 // and index from the expression types.
412 Expr *BaseExpr, *IndexExpr;
413 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000414 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000415 BaseExpr = LHSExp;
416 IndexExpr = RHSExp;
417 // FIXME: need to deal with const...
418 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000419 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000420 // Handle the uncommon case of "123[Ptr]".
421 BaseExpr = RHSExp;
422 IndexExpr = LHSExp;
423 // FIXME: need to deal with const...
424 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000425 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
426 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000427 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000428
429 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman506806b2008-02-19 01:11:03 +0000430 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
Steve Naroff89345522007-08-03 22:40:33 +0000431 return Diag(LLoc, diag::err_ocuvector_component_access,
432 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000433 // FIXME: need to deal with const...
434 ResultType = VTy->getElementType();
435 } else {
436 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
437 RHSExp->getSourceRange());
438 }
439 // C99 6.5.2.1p1
440 if (!IndexExpr->getType()->isIntegerType())
441 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
442 IndexExpr->getSourceRange());
443
444 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
445 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000446 // void (*)(int)) and pointers to incomplete types. Functions are not
447 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000448 if (!ResultType->isObjectType())
449 return Diag(BaseExpr->getLocStart(),
450 diag::err_typecheck_subscript_not_object,
451 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
452
453 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
454}
455
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000456QualType Sema::
457CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
458 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000459 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000460
461 // The vector accessor can't exceed the number of elements.
462 const char *compStr = CompName.getName();
463 if (strlen(compStr) > vecType->getNumElements()) {
464 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
465 baseType.getAsString(), SourceRange(CompLoc));
466 return QualType();
467 }
468 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000469 if (vecType->getPointAccessorIdx(*compStr) != -1) {
470 do
471 compStr++;
472 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
473 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
474 do
475 compStr++;
476 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
477 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
478 do
479 compStr++;
480 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
481 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000482
483 if (*compStr) {
484 // We didn't get to the end of the string. This means the component names
485 // didn't come from the same set *or* we encountered an illegal name.
486 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
487 std::string(compStr,compStr+1), SourceRange(CompLoc));
488 return QualType();
489 }
490 // Each component accessor can't exceed the vector type.
491 compStr = CompName.getName();
492 while (*compStr) {
493 if (vecType->isAccessorWithinNumElements(*compStr))
494 compStr++;
495 else
496 break;
497 }
498 if (*compStr) {
499 // We didn't get to the end of the string. This means a component accessor
500 // exceeds the number of elements in the vector.
501 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
502 baseType.getAsString(), SourceRange(CompLoc));
503 return QualType();
504 }
505 // The component accessor looks fine - now we need to compute the actual type.
506 // The vector type is implied by the component accessor. For example,
507 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
508 unsigned CompSize = strlen(CompName.getName());
509 if (CompSize == 1)
510 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000511
512 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
513 // Now look up the TypeDefDecl from the vector type. Without this,
514 // diagostics look bad. We want OCU vector types to appear built-in.
Chris Lattner48d7f382008-04-02 04:24:33 +0000515 for (unsigned i = 0, E = OCUVectorDecls.size(); i != E; ++i) {
Steve Naroff82113e32007-07-29 16:33:31 +0000516 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
517 return Context.getTypedefType(OCUVectorDecls[i]);
518 }
519 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000520}
521
Chris Lattner4b009652007-07-25 00:24:17 +0000522Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000523ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000524 tok::TokenKind OpKind, SourceLocation MemberLoc,
525 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000526 Expr *BaseExpr = static_cast<Expr *>(Base);
527 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000528
529 // Perform default conversions.
530 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000531
Steve Naroff2cb66382007-07-26 03:11:44 +0000532 QualType BaseType = BaseExpr->getType();
533 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000534
Chris Lattner4b009652007-07-25 00:24:17 +0000535 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000536 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000537 BaseType = PT->getPointeeType();
538 else
539 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
540 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000541 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000542 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000543 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000544 RecordDecl *RDecl = RTy->getDecl();
545 if (RTy->isIncompleteType())
546 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
547 BaseExpr->getSourceRange());
548 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000549 FieldDecl *MemberDecl = RDecl->getMember(&Member);
550 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000551 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
552 SourceRange(MemberLoc));
Eli Friedman76b49832008-02-06 22:48:16 +0000553
554 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000555 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000556 QualType MemberType = MemberDecl->getType();
557 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000558 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000559 MemberType = MemberType.getQualifiedType(combinedQualifiers);
560
561 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
562 MemberLoc, MemberType);
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000563 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000564 // Component access limited to variables (reject vec4.rg.g).
Nate Begeman78a2a312008-03-17 17:22:18 +0000565 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
Steve Naroff89345522007-08-03 22:40:33 +0000566 return Diag(OpLoc, diag::err_ocuvector_component_access,
567 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000568 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
569 if (ret.isNull())
570 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000571 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000572 } else if (BaseType->isObjCInterfaceType()) {
573 ObjCInterfaceDecl *IFace;
574 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
575 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000576 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000577 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
578 ObjCInterfaceDecl *clsDeclared;
579 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000580 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
581 OpKind==tok::arrow);
582 }
583 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
584 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000585}
586
Steve Naroff87d58b42007-09-16 03:34:24 +0000587/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000588/// This provides the location of the left/right parens and a list of comma
589/// locations.
590Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000591ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000592 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000593 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
594 Expr *Fn = static_cast<Expr *>(fn);
595 Expr **Args = reinterpret_cast<Expr**>(args);
596 assert(Fn && "no function call expression");
597
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000598 // Make the call expr early, before semantic checks. This guarantees cleanup
599 // of arguments and function on error.
600 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
601 Context.BoolTy, RParenLoc));
602
603 // Promote the function operand.
604 TheCall->setCallee(UsualUnaryConversions(Fn));
605
Chris Lattner4b009652007-07-25 00:24:17 +0000606 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
607 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000608 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000609 if (PT == 0)
610 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
611 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000612 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
613 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000614 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
615 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000616
617 // We know the result type of the call, set it.
618 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000619
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000620 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000621 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
622 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000623 unsigned NumArgsInProto = Proto->getNumArgs();
624 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000625
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000626 // If too few arguments are available, don't make the call.
627 if (NumArgs < NumArgsInProto)
628 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
629 Fn->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000630
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000631 // If too many are passed and not variadic, error on the extras and drop
632 // them.
633 if (NumArgs > NumArgsInProto) {
634 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000635 Diag(Args[NumArgsInProto]->getLocStart(),
636 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
637 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000638 Args[NumArgs-1]->getLocEnd()));
639 // This deletes the extra arguments.
640 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000641 }
642 NumArgsToCheck = NumArgsInProto;
643 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000644
Chris Lattner4b009652007-07-25 00:24:17 +0000645 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000646 for (unsigned i = 0; i != NumArgsToCheck; i++) {
647 Expr *Arg = Args[i];
Chris Lattner005ed752008-01-04 18:04:52 +0000648 QualType ProtoArgType = Proto->getArgType(i);
649 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000650
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000651 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000652 AssignConvertType ConvTy =
653 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000654 TheCall->setArg(i, Arg);
655
Chris Lattner005ed752008-01-04 18:04:52 +0000656 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
657 ArgType, Arg, "passing"))
658 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000659 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000660
661 // If this is a variadic call, handle args passed through "...".
662 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000663 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000664 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
665 Expr *Arg = Args[i];
666 DefaultArgumentPromotion(Arg);
667 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000668 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000669 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000670 } else {
671 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
672
Steve Naroffdb65e052007-08-28 23:30:39 +0000673 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000674 for (unsigned i = 0; i != NumArgs; i++) {
675 Expr *Arg = Args[i];
676 DefaultArgumentPromotion(Arg);
677 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000678 }
Chris Lattner4b009652007-07-25 00:24:17 +0000679 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000680
Chris Lattner2e64c072007-08-10 20:18:51 +0000681 // Do special checking on direct calls to functions.
682 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
683 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
684 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000685 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000686 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000687
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000688 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000689}
690
691Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000692ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000693 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000694 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000695 QualType literalType = QualType::getFromOpaquePtr(Ty);
696 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000697 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000698 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000699
Steve Naroffcb69fb72007-12-10 22:44:33 +0000700 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Narofff0b23542008-01-10 22:15:12 +0000701 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000702 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000703
704 bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
705 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000706 if (CheckForConstantInitializer(literalExpr, literalType))
707 return true;
708 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000709 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000710}
711
712Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000713ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000714 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000715 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000716
Steve Naroff0acc9c92007-09-15 18:49:24 +0000717 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000718 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000719
Chris Lattner48d7f382008-04-02 04:24:33 +0000720 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
721 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
722 return E;
Chris Lattner4b009652007-07-25 00:24:17 +0000723}
724
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000725bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000726 assert(VectorTy->isVectorType() && "Not a vector type!");
727
728 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000729 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000730 return Diag(R.getBegin(),
731 Ty->isVectorType() ?
732 diag::err_invalid_conversion_between_vectors :
733 diag::err_invalid_conversion_between_vector_and_integer,
734 VectorTy.getAsString().c_str(),
735 Ty.getAsString().c_str(), R);
736 } else
737 return Diag(R.getBegin(),
738 diag::err_invalid_conversion_between_vector_and_scalar,
739 VectorTy.getAsString().c_str(),
740 Ty.getAsString().c_str(), R);
741
742 return false;
743}
744
Chris Lattner4b009652007-07-25 00:24:17 +0000745Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000746ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000747 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000748 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000749
750 Expr *castExpr = static_cast<Expr*>(Op);
751 QualType castType = QualType::getFromOpaquePtr(Ty);
752
Steve Naroff68adb482007-08-31 00:32:44 +0000753 UsualUnaryConversions(castExpr);
754
Chris Lattner4b009652007-07-25 00:24:17 +0000755 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
756 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000757 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Narofff459ee52008-01-24 22:55:05 +0000758 if (!castType->isScalarType() && !castType->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000759 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
760 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Steve Narofff459ee52008-01-24 22:55:05 +0000761 if (!castExpr->getType()->isScalarType() &&
762 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000763 return Diag(castExpr->getLocStart(),
764 diag::err_typecheck_expect_scalar_operand,
765 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000766
767 if (castExpr->getType()->isVectorType()) {
768 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
769 castExpr->getType(), castType))
770 return true;
771 } else if (castType->isVectorType()) {
772 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
773 castType, castExpr->getType()))
774 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000775 }
Chris Lattner4b009652007-07-25 00:24:17 +0000776 }
777 return new CastExpr(castType, castExpr, LParenLoc);
778}
779
Chris Lattner98a425c2007-11-26 01:40:58 +0000780/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
781/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000782inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
783 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
784 UsualUnaryConversions(cond);
785 UsualUnaryConversions(lex);
786 UsualUnaryConversions(rex);
787 QualType condT = cond->getType();
788 QualType lexT = lex->getType();
789 QualType rexT = rex->getType();
790
791 // first, check the condition.
792 if (!condT->isScalarType()) { // C99 6.5.15p2
793 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
794 condT.getAsString());
795 return QualType();
796 }
Chris Lattner992ae932008-01-06 22:42:25 +0000797
798 // Now check the two expressions.
799
800 // If both operands have arithmetic type, do the usual arithmetic conversions
801 // to find a common type: C99 6.5.15p3,5.
802 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000803 UsualArithmeticConversions(lex, rex);
804 return lex->getType();
805 }
Chris Lattner992ae932008-01-06 22:42:25 +0000806
807 // If both operands are the same structure or union type, the result is that
808 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000809 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000810 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000811 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000812 // "If both the operands have structure or union type, the result has
813 // that type." This implies that CV qualifiers are dropped.
814 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000815 }
Chris Lattner992ae932008-01-06 22:42:25 +0000816
817 // C99 6.5.15p5: "If both operands have void type, the result has void type."
818 if (lexT->isVoidType() && rexT->isVoidType())
819 return lexT.getUnqualifiedType();
Steve Naroff12ebf272008-01-08 01:11:38 +0000820
821 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
822 // the type of the other operand."
823 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000824 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000825 return lexT;
826 }
827 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000828 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000829 return rexT;
830 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000831 // Handle the case where both operands are pointers before we handle null
832 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000833 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
834 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
835 // get the "pointed to" types
836 QualType lhptee = LHSPT->getPointeeType();
837 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000838
Chris Lattner71225142007-07-31 21:27:01 +0000839 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
840 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +0000841 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000842 // Figure out necessary qualifiers (C99 6.5.15p6)
843 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000844 QualType destType = Context.getPointerType(destPointee);
845 ImpCastExprToType(lex, destType); // add qualifiers if necessary
846 ImpCastExprToType(rex, destType); // promote to void*
847 return destType;
848 }
Chris Lattner9db553e2008-04-02 06:59:01 +0000849 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000850 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000851 QualType destType = Context.getPointerType(destPointee);
852 ImpCastExprToType(lex, destType); // add qualifiers if necessary
853 ImpCastExprToType(rex, destType); // promote to void*
854 return destType;
855 }
Chris Lattner4b009652007-07-25 00:24:17 +0000856
Steve Naroff85f0dc52007-10-15 20:41:53 +0000857 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
858 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +0000859 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +0000860 lexT.getAsString(), rexT.getAsString(),
861 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +0000862 // In this situation, we assume void* type. No especially good
863 // reason, but this is what gcc does, and we do have to pick
864 // to get a consistent AST.
865 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
866 ImpCastExprToType(lex, voidPtrTy);
867 ImpCastExprToType(rex, voidPtrTy);
868 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +0000869 }
870 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000871 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
872 // differently qualified versions of compatible types, the result type is
873 // a pointer to an appropriately qualified version of the *composite*
874 // type.
Chris Lattner0ac51632008-01-06 22:50:31 +0000875 // FIXME: Need to return the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +0000876 // FIXME: Need to add qualifiers
Chris Lattner0ac51632008-01-06 22:50:31 +0000877 return lexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000878 }
Chris Lattner4b009652007-07-25 00:24:17 +0000879 }
Chris Lattner71225142007-07-31 21:27:01 +0000880
Chris Lattner992ae932008-01-06 22:42:25 +0000881 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000882 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
883 lexT.getAsString(), rexT.getAsString(),
884 lex->getSourceRange(), rex->getSourceRange());
885 return QualType();
886}
887
Steve Naroff87d58b42007-09-16 03:34:24 +0000888/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000889/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000890Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000891 SourceLocation ColonLoc,
892 ExprTy *Cond, ExprTy *LHS,
893 ExprTy *RHS) {
894 Expr *CondExpr = (Expr *) Cond;
895 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000896
897 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
898 // was the condition.
899 bool isLHSNull = LHSExpr == 0;
900 if (isLHSNull)
901 LHSExpr = CondExpr;
902
Chris Lattner4b009652007-07-25 00:24:17 +0000903 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
904 RHSExpr, QuestionLoc);
905 if (result.isNull())
906 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000907 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
908 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000909}
910
Steve Naroffdb65e052007-08-28 23:30:39 +0000911/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +0000912/// do not have a prototype. Arguments that have type float are promoted to
913/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000914void Sema::DefaultArgumentPromotion(Expr *&Expr) {
915 QualType Ty = Expr->getType();
916 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000917
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000918 if (Ty == Context.FloatTy)
Chris Lattnere992d6c2008-01-16 19:17:22 +0000919 ImpCastExprToType(Expr, Context.DoubleTy);
Steve Naroffbbaed752008-01-29 02:42:22 +0000920 else
921 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +0000922}
923
Chris Lattner4b009652007-07-25 00:24:17 +0000924/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Chris Lattner48d7f382008-04-02 04:24:33 +0000925void Sema::DefaultFunctionArrayConversion(Expr *&E) {
926 QualType Ty = E->getType();
927 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000928
Chris Lattner48d7f382008-04-02 04:24:33 +0000929 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +0000930 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
Chris Lattner48d7f382008-04-02 04:24:33 +0000931 Ty = E->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000932 }
Chris Lattner48d7f382008-04-02 04:24:33 +0000933 if (Ty->isFunctionType())
934 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner19eb97e2008-04-02 05:18:44 +0000935 else if (Ty->isArrayType())
936 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
Chris Lattner4b009652007-07-25 00:24:17 +0000937}
938
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000939/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +0000940/// operators (C99 6.3). The conversions of array and function types are
941/// sometimes surpressed. For example, the array->pointer conversion doesn't
942/// apply if the array is an argument to the sizeof or address (&) operators.
943/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000944Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
945 QualType Ty = Expr->getType();
946 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000947
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000948 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +0000949 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000950 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000951 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000952 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +0000953 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000954 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000955 DefaultFunctionArrayConversion(Expr);
956
957 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000958}
959
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000960/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000961/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
962/// routine returns the first non-arithmetic type found. The client is
963/// responsible for emitting appropriate error diagnostics.
Chris Lattner48d7f382008-04-02 04:24:33 +0000964/// FIXME: verify the conversion rules for "complex int" are consistent with
965/// GCC.
Steve Naroff8f708362007-08-24 19:07:16 +0000966QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
967 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000968 if (!isCompAssign) {
969 UsualUnaryConversions(lhsExpr);
970 UsualUnaryConversions(rhsExpr);
971 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000972 // For conversion purposes, we ignore any qualifiers.
973 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000974 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
975 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000976
977 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000978 if (lhs == rhs)
979 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000980
981 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
982 // The caller can deal with this (e.g. pointer + int).
983 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000984 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000985
986 // At this point, we have two different arithmetic types.
987
988 // Handle complex types first (C99 6.3.1.8p1).
989 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +0000990 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +0000991 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +0000992 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +0000993 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +0000994 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +0000995 }
Steve Naroffe8419ca2008-01-15 22:21:49 +0000996 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +0000997 // convert the lhs to the rhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +0000998 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +0000999 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001000 }
Steve Naroff3cf497f2007-08-27 01:27:54 +00001001 // This handles complex/complex, complex/float, or float/complex.
1002 // When both operands are complex, the shorter operand is converted to the
1003 // type of the longer, and that is the type of the result. This corresponds
1004 // to what is done when combining two real floating-point operands.
1005 // The fun begins when size promotion occur across type domains.
1006 // From H&S 6.3.4: When one operand is complex and the other is a real
1007 // floating-point type, the less precise type is converted, within it's
1008 // real or complex domain, to the precision of the other type. For example,
1009 // when combining a "long double" with a "double _Complex", the
1010 // "double _Complex" is promoted to "long double _Complex".
Chris Lattnerd7135b42008-04-06 23:38:49 +00001011 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001012
1013 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001014 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1015 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001016 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001017 } else if (result < 0) { // The right side is bigger, convert lhs.
1018 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1019 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001020 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001021 }
1022 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1023 // domains match. This is a requirement for our implementation, C99
1024 // does not require this promotion.
1025 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1026 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001027 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001028 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001029 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001030 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001031 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001032 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001033 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001034 }
Chris Lattner4b009652007-07-25 00:24:17 +00001035 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001036 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001037 }
1038 // Now handle "real" floating types (i.e. float, double, long double).
1039 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1040 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001041 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001042 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001043 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001044 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001045 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001046 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001047 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001048 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001049 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001050 }
1051 // We have two real floating types, float/complex combos were handled above.
1052 // Convert the smaller operand to the bigger result.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001053 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001054
1055 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001056 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001057 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001058 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001059 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001060 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001061 return rhs;
1062 }
1063 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001064 }
Steve Naroff43001212008-01-15 19:36:10 +00001065 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1066 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001067 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001068 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001069
Eli Friedman50727042008-02-08 01:19:44 +00001070 if (lhsComplexInt && rhsComplexInt) {
Chris Lattner51285d82008-04-06 23:55:33 +00001071 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
1072 rhsComplexInt->getElementType()) >= 0) {
Eli Friedman94075c02008-02-08 01:24:30 +00001073 // convert the rhs
1074 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1075 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001076 }
1077 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001078 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001079 return rhs;
1080 } else if (lhsComplexInt && rhs->isIntegerType()) {
1081 // convert the rhs to the lhs complex type.
1082 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1083 return lhs;
1084 } else if (rhsComplexInt && lhs->isIntegerType()) {
1085 // convert the lhs to the rhs complex type.
1086 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1087 return rhs;
1088 }
Steve Naroff43001212008-01-15 19:36:10 +00001089 }
Chris Lattner4b009652007-07-25 00:24:17 +00001090 // Finally, we have two differing integer types.
Chris Lattner51285d82008-04-06 23:55:33 +00001091 if (Context.getIntegerTypeOrder(lhs, rhs) >= 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001092 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001093 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001094 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001095 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff8f708362007-08-24 19:07:16 +00001096 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001097}
1098
1099// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1100// being closely modeled after the C99 spec:-). The odd characteristic of this
1101// routine is it effectively iqnores the qualifiers on the top level pointee.
1102// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1103// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001104Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001105Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1106 QualType lhptee, rhptee;
1107
1108 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001109 lhptee = lhsType->getAsPointerType()->getPointeeType();
1110 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001111
1112 // make sure we operate on the canonical type
1113 lhptee = lhptee.getCanonicalType();
1114 rhptee = rhptee.getCanonicalType();
1115
Chris Lattner005ed752008-01-04 18:04:52 +00001116 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001117
1118 // C99 6.5.16.1p1: This following citation is common to constraints
1119 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1120 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001121 // FIXME: Handle ASQualType
1122 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1123 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001124 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001125
1126 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1127 // incomplete type and the other is a pointer to a qualified or unqualified
1128 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001129 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001130 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001131 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001132
1133 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001134 assert(rhptee->isFunctionType());
1135 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001136 }
1137
1138 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001139 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001140 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001141
1142 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001143 assert(lhptee->isFunctionType());
1144 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001145 }
1146
Chris Lattner4b009652007-07-25 00:24:17 +00001147 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1148 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001149 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1150 rhptee.getUnqualifiedType()))
1151 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001152 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001153}
1154
1155/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1156/// has code to accommodate several GCC extensions when type checking
1157/// pointers. Here are some objectionable examples that GCC considers warnings:
1158///
1159/// int a, *pint;
1160/// short *pshort;
1161/// struct foo *pfoo;
1162///
1163/// pint = pshort; // warning: assignment from incompatible pointer type
1164/// a = pint; // warning: assignment makes integer from pointer without a cast
1165/// pint = a; // warning: assignment makes pointer from integer without a cast
1166/// pint = pfoo; // warning: assignment from incompatible pointer type
1167///
1168/// As a result, the code for dealing with pointers is more complex than the
1169/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001170///
Chris Lattner005ed752008-01-04 18:04:52 +00001171Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001172Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001173 // Get canonical types. We're not formatting these types, just comparing
1174 // them.
1175 lhsType = lhsType.getCanonicalType();
1176 rhsType = rhsType.getCanonicalType();
1177
1178 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001179 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001180
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001181 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001182 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001183 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001184 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001185 }
Chris Lattner1853da22008-01-04 23:18:45 +00001186
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001187 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1188 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001189 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001190 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001191 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001192
Chris Lattner390564e2008-04-07 06:49:41 +00001193 if (isa<VectorType>(lhsType) || isa<VectorType>(rhsType)) {
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001194 // For OCUVector, allow vector splats; float -> <n x float>
Chris Lattner390564e2008-04-07 06:49:41 +00001195 if (const OCUVectorType *LV = dyn_cast<OCUVectorType>(lhsType)) {
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001196 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1197 return Compatible;
1198 }
1199
1200 // If LHS and RHS are both vectors of integer or both vectors of floating
1201 // point types, and the total vector length is the same, allow the
1202 // conversion. This is a bitcast; no bits are changed but the result type
1203 // is different.
1204 if (getLangOptions().LaxVectorConversions &&
1205 lhsType->isVectorType() && rhsType->isVectorType()) {
1206 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1207 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001208 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Nate Begemanec2d1062007-12-30 02:59:45 +00001209 return Compatible;
1210 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001211 }
1212 return Incompatible;
1213 }
1214
1215 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001216 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001217
Chris Lattner390564e2008-04-07 06:49:41 +00001218 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001219 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001220 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001221
Chris Lattner390564e2008-04-07 06:49:41 +00001222 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001223 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001224 return Incompatible;
1225 }
1226
Chris Lattner390564e2008-04-07 06:49:41 +00001227 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001228 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Chris Lattner390564e2008-04-07 06:49:41 +00001229 if (lhsType->isIntegerType() && lhsType != Context.BoolTy)
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001230 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001231
Chris Lattner390564e2008-04-07 06:49:41 +00001232 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001233 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001234 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001235 }
1236
1237 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001238 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001239 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001240 }
1241 return Incompatible;
1242}
1243
Chris Lattner005ed752008-01-04 18:04:52 +00001244Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001245Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001246 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1247 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001248 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001249 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001250 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001251 return Compatible;
1252 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001253 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001254 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001255 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001256 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001257 //
1258 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1259 // are better understood.
1260 if (!lhsType->isReferenceType())
1261 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001262
Chris Lattner005ed752008-01-04 18:04:52 +00001263 Sema::AssignConvertType result =
1264 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001265
1266 // C99 6.5.16.1p2: The value of the right operand is converted to the
1267 // type of the assignment expression.
1268 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001269 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001270 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001271}
1272
Chris Lattner005ed752008-01-04 18:04:52 +00001273Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001274Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1275 return CheckAssignmentConstraints(lhsType, rhsType);
1276}
1277
Chris Lattner2c8bff72007-12-12 05:47:28 +00001278QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001279 Diag(loc, diag::err_typecheck_invalid_operands,
1280 lex->getType().getAsString(), rex->getType().getAsString(),
1281 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001282 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001283}
1284
1285inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1286 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001287 // For conversion purposes, we ignore any qualifiers.
1288 // For example, "const float" and "float" are equivalent.
1289 QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType();
1290 QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001291
1292 // make sure the vector types are identical.
Nate Begeman03105572008-04-04 01:30:25 +00001293 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001294 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001295
1296 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1297 // promote the rhs to the vector type.
1298 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1299 if (V->getElementType().getCanonicalType().getTypePtr()
1300 == rhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001301 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001302 return lhsType;
1303 }
1304 }
1305
1306 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1307 // promote the lhs to the vector type.
1308 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1309 if (V->getElementType().getCanonicalType().getTypePtr()
1310 == lhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001311 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001312 return rhsType;
1313 }
1314 }
1315
Chris Lattner4b009652007-07-25 00:24:17 +00001316 // You cannot convert between vector values of different size.
1317 Diag(loc, diag::err_typecheck_vector_not_convertable,
1318 lex->getType().getAsString(), rex->getType().getAsString(),
1319 lex->getSourceRange(), rex->getSourceRange());
1320 return QualType();
1321}
1322
1323inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001324 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001325{
1326 QualType lhsType = lex->getType(), rhsType = rex->getType();
1327
1328 if (lhsType->isVectorType() || rhsType->isVectorType())
1329 return CheckVectorOperands(loc, lex, rex);
1330
Steve Naroff8f708362007-08-24 19:07:16 +00001331 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001332
Chris Lattner4b009652007-07-25 00:24:17 +00001333 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001334 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001335 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001336}
1337
1338inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001339 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001340{
1341 QualType lhsType = lex->getType(), rhsType = rex->getType();
1342
Steve Naroff8f708362007-08-24 19:07:16 +00001343 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001344
Chris Lattner4b009652007-07-25 00:24:17 +00001345 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001346 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001347 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001348}
1349
1350inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001351 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001352{
1353 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1354 return CheckVectorOperands(loc, lex, rex);
1355
Steve Naroff8f708362007-08-24 19:07:16 +00001356 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001357
1358 // handle the common case first (both operands are arithmetic).
1359 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001360 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001361
1362 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1363 return lex->getType();
1364 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1365 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001366 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001367}
1368
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001369// C99 6.5.6
1370QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1371 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001372 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1373 return CheckVectorOperands(loc, lex, rex);
1374
Steve Naroff8f708362007-08-24 19:07:16 +00001375 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001376
Chris Lattnerf6da2912007-12-09 21:53:25 +00001377 // Enforce type constraints: C99 6.5.6p3.
1378
1379 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001380 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001381 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001382
1383 // Either ptr - int or ptr - ptr.
1384 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001385 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001386
Chris Lattnerf6da2912007-12-09 21:53:25 +00001387 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001388 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001389 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001390 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001391 Diag(loc, diag::ext_gnu_void_ptr,
1392 lex->getSourceRange(), rex->getSourceRange());
1393 } else {
1394 Diag(loc, diag::err_typecheck_sub_ptr_object,
1395 lex->getType().getAsString(), lex->getSourceRange());
1396 return QualType();
1397 }
1398 }
1399
1400 // The result type of a pointer-int computation is the pointer type.
1401 if (rex->getType()->isIntegerType())
1402 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001403
Chris Lattnerf6da2912007-12-09 21:53:25 +00001404 // Handle pointer-pointer subtractions.
1405 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001406 QualType rpointee = RHSPTy->getPointeeType();
1407
Chris Lattnerf6da2912007-12-09 21:53:25 +00001408 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001409 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001410 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001411 if (rpointee->isVoidType()) {
1412 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001413 Diag(loc, diag::ext_gnu_void_ptr,
1414 lex->getSourceRange(), rex->getSourceRange());
1415 } else {
1416 Diag(loc, diag::err_typecheck_sub_ptr_object,
1417 rex->getType().getAsString(), rex->getSourceRange());
1418 return QualType();
1419 }
1420 }
1421
1422 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001423 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1424 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001425 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1426 lex->getType().getAsString(), rex->getType().getAsString(),
1427 lex->getSourceRange(), rex->getSourceRange());
1428 return QualType();
1429 }
1430
1431 return Context.getPointerDiffType();
1432 }
1433 }
1434
Chris Lattner2c8bff72007-12-12 05:47:28 +00001435 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001436}
1437
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001438// C99 6.5.7
1439QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1440 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001441 // C99 6.5.7p2: Each of the operands shall have integer type.
1442 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1443 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001444
Chris Lattner2c8bff72007-12-12 05:47:28 +00001445 // Shifts don't perform usual arithmetic conversions, they just do integer
1446 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001447 if (!isCompAssign)
1448 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001449 UsualUnaryConversions(rex);
1450
1451 // "The type of the result is that of the promoted left operand."
1452 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001453}
1454
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001455// C99 6.5.8
1456QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1457 bool isRelational) {
Chris Lattner254f3bc2007-08-26 01:18:55 +00001458 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001459 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1460 UsualArithmeticConversions(lex, rex);
1461 else {
1462 UsualUnaryConversions(lex);
1463 UsualUnaryConversions(rex);
1464 }
Chris Lattner4b009652007-07-25 00:24:17 +00001465 QualType lType = lex->getType();
1466 QualType rType = rex->getType();
1467
Ted Kremenek486509e2007-10-29 17:13:39 +00001468 // For non-floating point types, check for self-comparisons of the form
1469 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1470 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001471 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001472 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1473 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001474 if (DRL->getDecl() == DRR->getDecl())
1475 Diag(loc, diag::warn_selfcomparison);
1476 }
1477
Chris Lattner254f3bc2007-08-26 01:18:55 +00001478 if (isRelational) {
1479 if (lType->isRealType() && rType->isRealType())
1480 return Context.IntTy;
1481 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001482 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001483 if (lType->isFloatingType()) {
1484 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001485 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001486 }
1487
Chris Lattner254f3bc2007-08-26 01:18:55 +00001488 if (lType->isArithmeticType() && rType->isArithmeticType())
1489 return Context.IntTy;
1490 }
Chris Lattner4b009652007-07-25 00:24:17 +00001491
Chris Lattner22be8422007-08-26 01:10:14 +00001492 bool LHSIsNull = lex->isNullPointerConstant(Context);
1493 bool RHSIsNull = rex->isNullPointerConstant(Context);
1494
Chris Lattner254f3bc2007-08-26 01:18:55 +00001495 // All of the following pointer related warnings are GCC extensions, except
1496 // when handling null pointer constants. One day, we can consider making them
1497 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001498 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001499 QualType LCanPointeeTy =
1500 lType->getAsPointerType()->getPointeeType().getCanonicalType();
1501 QualType RCanPointeeTy =
1502 rType->getAsPointerType()->getPointeeType().getCanonicalType();
Eli Friedman50727042008-02-08 01:19:44 +00001503
Steve Naroff3b435622007-11-13 14:57:38 +00001504 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001505 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1506 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1507 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001508 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1509 lType.getAsString(), rType.getAsString(),
1510 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001511 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001512 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001513 return Context.IntTy;
1514 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001515 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001516 && ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001517 ImpCastExprToType(rex, lType);
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001518 return Context.IntTy;
1519 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001520 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001521 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001522 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1523 lType.getAsString(), rType.getAsString(),
1524 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001525 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001526 return Context.IntTy;
1527 }
1528 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001529 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001530 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1531 lType.getAsString(), rType.getAsString(),
1532 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001533 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001534 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001535 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001536 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001537}
1538
Chris Lattner4b009652007-07-25 00:24:17 +00001539inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001540 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001541{
1542 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1543 return CheckVectorOperands(loc, lex, rex);
1544
Steve Naroff8f708362007-08-24 19:07:16 +00001545 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001546
1547 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001548 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001549 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001550}
1551
1552inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1553 Expr *&lex, Expr *&rex, SourceLocation loc)
1554{
1555 UsualUnaryConversions(lex);
1556 UsualUnaryConversions(rex);
1557
1558 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1559 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001560 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001561}
1562
1563inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001564 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001565{
1566 QualType lhsType = lex->getType();
1567 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001568 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1569
1570 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001571 case Expr::MLV_Valid:
1572 break;
1573 case Expr::MLV_ConstQualified:
1574 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1575 return QualType();
1576 case Expr::MLV_ArrayType:
1577 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1578 lhsType.getAsString(), lex->getSourceRange());
1579 return QualType();
1580 case Expr::MLV_NotObjectType:
1581 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1582 lhsType.getAsString(), lex->getSourceRange());
1583 return QualType();
1584 case Expr::MLV_InvalidExpression:
1585 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1586 lex->getSourceRange());
1587 return QualType();
1588 case Expr::MLV_IncompleteType:
1589 case Expr::MLV_IncompleteVoidType:
1590 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1591 lhsType.getAsString(), lex->getSourceRange());
1592 return QualType();
1593 case Expr::MLV_DuplicateVectorComponents:
1594 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1595 lex->getSourceRange());
1596 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001597 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001598
Chris Lattner005ed752008-01-04 18:04:52 +00001599 AssignConvertType ConvTy;
1600 if (compoundType.isNull())
1601 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1602 else
1603 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1604
1605 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1606 rex, "assigning"))
1607 return QualType();
1608
Chris Lattner4b009652007-07-25 00:24:17 +00001609 // C99 6.5.16p3: The type of an assignment expression is the type of the
1610 // left operand unless the left operand has qualified type, in which case
1611 // it is the unqualified version of the type of the left operand.
1612 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1613 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001614 // C++ 5.17p1: the type of the assignment expression is that of its left
1615 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001616 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001617}
1618
1619inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1620 Expr *&lex, Expr *&rex, SourceLocation loc) {
1621 UsualUnaryConversions(rex);
1622 return rex->getType();
1623}
1624
1625/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1626/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1627QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1628 QualType resType = op->getType();
1629 assert(!resType.isNull() && "no type for increment/decrement expression");
1630
Steve Naroffd30e1932007-08-24 17:20:07 +00001631 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001632 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001633 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1634 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1635 resType.getAsString(), op->getSourceRange());
1636 return QualType();
1637 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001638 } else if (!resType->isRealType()) {
1639 if (resType->isComplexType())
1640 // C99 does not support ++/-- on complex types.
1641 Diag(OpLoc, diag::ext_integer_increment_complex,
1642 resType.getAsString(), op->getSourceRange());
1643 else {
1644 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1645 resType.getAsString(), op->getSourceRange());
1646 return QualType();
1647 }
Chris Lattner4b009652007-07-25 00:24:17 +00001648 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001649 // At this point, we know we have a real, complex or pointer type.
1650 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001651 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1652 if (mlval != Expr::MLV_Valid) {
1653 // FIXME: emit a more precise diagnostic...
1654 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1655 op->getSourceRange());
1656 return QualType();
1657 }
1658 return resType;
1659}
1660
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001661/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001662/// This routine allows us to typecheck complex/recursive expressions
1663/// where the declaration is needed for type checking. Here are some
1664/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Chris Lattner48d7f382008-04-02 04:24:33 +00001665static ValueDecl *getPrimaryDecl(Expr *E) {
1666 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001667 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001668 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001669 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001670 // Fields cannot be declared with a 'register' storage class.
1671 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00001672 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00001673 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00001674 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001675 case Stmt::ArraySubscriptExprClass: {
1676 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1677
Chris Lattner48d7f382008-04-02 04:24:33 +00001678 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001679 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001680 return 0;
1681 else
1682 return VD;
1683 }
Chris Lattner4b009652007-07-25 00:24:17 +00001684 case Stmt::UnaryOperatorClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001685 return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001686 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001687 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001688 case Stmt::ImplicitCastExprClass:
1689 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00001690 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001691 default:
1692 return 0;
1693 }
1694}
1695
1696/// CheckAddressOfOperand - The operand of & must be either a function
1697/// designator or an lvalue designating an object. If it is an lvalue, the
1698/// object cannot be declared with storage class register or be a bit field.
1699/// Note: The usual conversions are *not* applied to the operand of the &
1700/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1701QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001702 if (getLangOptions().C99) {
1703 // Implement C99-only parts of addressof rules.
1704 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1705 if (uOp->getOpcode() == UnaryOperator::Deref)
1706 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1707 // (assuming the deref expression is valid).
1708 return uOp->getSubExpr()->getType();
1709 }
1710 // Technically, there should be a check for array subscript
1711 // expressions here, but the result of one is always an lvalue anyway.
1712 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001713 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001714 Expr::isLvalueResult lval = op->isLvalue();
1715
1716 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001717 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1718 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001719 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1720 op->getSourceRange());
1721 return QualType();
1722 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00001723 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1724 if (MemExpr->getMemberDecl()->isBitField()) {
1725 Diag(OpLoc, diag::err_typecheck_address_of,
1726 std::string("bit-field"), op->getSourceRange());
1727 return QualType();
1728 }
1729 // Check for Apple extension for accessing vector components.
1730 } else if (isa<ArraySubscriptExpr>(op) &&
1731 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
1732 Diag(OpLoc, diag::err_typecheck_address_of,
1733 std::string("vector"), op->getSourceRange());
1734 return QualType();
1735 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00001736 // We have an lvalue with a decl. Make sure the decl is not declared
1737 // with the register storage-class specifier.
1738 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1739 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00001740 Diag(OpLoc, diag::err_typecheck_address_of,
1741 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001742 return QualType();
1743 }
1744 } else
1745 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00001746 }
1747 // If the operand has type "type", the result has type "pointer to type".
1748 return Context.getPointerType(op->getType());
1749}
1750
1751QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1752 UsualUnaryConversions(op);
1753 QualType qType = op->getType();
1754
Chris Lattner7931f4a2007-07-31 16:53:04 +00001755 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001756 // Note that per both C89 and C99, this is always legal, even
1757 // if ptype is an incomplete type or void.
1758 // It would be possible to warn about dereferencing a
1759 // void pointer, but it's completely well-defined,
1760 // and such a warning is unlikely to catch any mistakes.
1761 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001762 }
1763 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1764 qType.getAsString(), op->getSourceRange());
1765 return QualType();
1766}
1767
1768static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1769 tok::TokenKind Kind) {
1770 BinaryOperator::Opcode Opc;
1771 switch (Kind) {
1772 default: assert(0 && "Unknown binop!");
1773 case tok::star: Opc = BinaryOperator::Mul; break;
1774 case tok::slash: Opc = BinaryOperator::Div; break;
1775 case tok::percent: Opc = BinaryOperator::Rem; break;
1776 case tok::plus: Opc = BinaryOperator::Add; break;
1777 case tok::minus: Opc = BinaryOperator::Sub; break;
1778 case tok::lessless: Opc = BinaryOperator::Shl; break;
1779 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1780 case tok::lessequal: Opc = BinaryOperator::LE; break;
1781 case tok::less: Opc = BinaryOperator::LT; break;
1782 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1783 case tok::greater: Opc = BinaryOperator::GT; break;
1784 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1785 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1786 case tok::amp: Opc = BinaryOperator::And; break;
1787 case tok::caret: Opc = BinaryOperator::Xor; break;
1788 case tok::pipe: Opc = BinaryOperator::Or; break;
1789 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1790 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1791 case tok::equal: Opc = BinaryOperator::Assign; break;
1792 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1793 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1794 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1795 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1796 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1797 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1798 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1799 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1800 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1801 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1802 case tok::comma: Opc = BinaryOperator::Comma; break;
1803 }
1804 return Opc;
1805}
1806
1807static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1808 tok::TokenKind Kind) {
1809 UnaryOperator::Opcode Opc;
1810 switch (Kind) {
1811 default: assert(0 && "Unknown unary op!");
1812 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1813 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1814 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1815 case tok::star: Opc = UnaryOperator::Deref; break;
1816 case tok::plus: Opc = UnaryOperator::Plus; break;
1817 case tok::minus: Opc = UnaryOperator::Minus; break;
1818 case tok::tilde: Opc = UnaryOperator::Not; break;
1819 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1820 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1821 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1822 case tok::kw___real: Opc = UnaryOperator::Real; break;
1823 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1824 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1825 }
1826 return Opc;
1827}
1828
1829// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001830Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001831 ExprTy *LHS, ExprTy *RHS) {
1832 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1833 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1834
Steve Naroff87d58b42007-09-16 03:34:24 +00001835 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1836 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001837
1838 QualType ResultTy; // Result type of the binary operator.
1839 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1840
1841 switch (Opc) {
1842 default:
1843 assert(0 && "Unknown binary expr!");
1844 case BinaryOperator::Assign:
1845 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1846 break;
1847 case BinaryOperator::Mul:
1848 case BinaryOperator::Div:
1849 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1850 break;
1851 case BinaryOperator::Rem:
1852 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1853 break;
1854 case BinaryOperator::Add:
1855 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1856 break;
1857 case BinaryOperator::Sub:
1858 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1859 break;
1860 case BinaryOperator::Shl:
1861 case BinaryOperator::Shr:
1862 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1863 break;
1864 case BinaryOperator::LE:
1865 case BinaryOperator::LT:
1866 case BinaryOperator::GE:
1867 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001868 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001869 break;
1870 case BinaryOperator::EQ:
1871 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001872 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001873 break;
1874 case BinaryOperator::And:
1875 case BinaryOperator::Xor:
1876 case BinaryOperator::Or:
1877 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1878 break;
1879 case BinaryOperator::LAnd:
1880 case BinaryOperator::LOr:
1881 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1882 break;
1883 case BinaryOperator::MulAssign:
1884 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001885 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001886 if (!CompTy.isNull())
1887 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1888 break;
1889 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001890 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001891 if (!CompTy.isNull())
1892 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1893 break;
1894 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001895 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001896 if (!CompTy.isNull())
1897 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1898 break;
1899 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001900 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001901 if (!CompTy.isNull())
1902 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1903 break;
1904 case BinaryOperator::ShlAssign:
1905 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001906 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001907 if (!CompTy.isNull())
1908 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1909 break;
1910 case BinaryOperator::AndAssign:
1911 case BinaryOperator::XorAssign:
1912 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001913 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001914 if (!CompTy.isNull())
1915 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1916 break;
1917 case BinaryOperator::Comma:
1918 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1919 break;
1920 }
1921 if (ResultTy.isNull())
1922 return true;
1923 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001924 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001925 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001926 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001927}
1928
1929// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001930Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001931 ExprTy *input) {
1932 Expr *Input = (Expr*)input;
1933 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1934 QualType resultType;
1935 switch (Opc) {
1936 default:
1937 assert(0 && "Unimplemented unary expr!");
1938 case UnaryOperator::PreInc:
1939 case UnaryOperator::PreDec:
1940 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1941 break;
1942 case UnaryOperator::AddrOf:
1943 resultType = CheckAddressOfOperand(Input, OpLoc);
1944 break;
1945 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001946 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001947 resultType = CheckIndirectionOperand(Input, OpLoc);
1948 break;
1949 case UnaryOperator::Plus:
1950 case UnaryOperator::Minus:
1951 UsualUnaryConversions(Input);
1952 resultType = Input->getType();
1953 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1954 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1955 resultType.getAsString());
1956 break;
1957 case UnaryOperator::Not: // bitwise complement
1958 UsualUnaryConversions(Input);
1959 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001960 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1961 if (!resultType->isIntegerType()) {
1962 if (resultType->isComplexType())
1963 // C99 does not support '~' for complex conjugation.
1964 Diag(OpLoc, diag::ext_integer_complement_complex,
1965 resultType.getAsString());
1966 else
1967 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1968 resultType.getAsString());
1969 }
Chris Lattner4b009652007-07-25 00:24:17 +00001970 break;
1971 case UnaryOperator::LNot: // logical negation
1972 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1973 DefaultFunctionArrayConversion(Input);
1974 resultType = Input->getType();
1975 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1976 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1977 resultType.getAsString());
1978 // LNot always has type int. C99 6.5.3.3p5.
1979 resultType = Context.IntTy;
1980 break;
1981 case UnaryOperator::SizeOf:
1982 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1983 break;
1984 case UnaryOperator::AlignOf:
1985 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1986 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001987 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001988 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001989 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001990 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001991 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001992 resultType = Input->getType();
1993 break;
1994 }
1995 if (resultType.isNull())
1996 return true;
1997 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1998}
1999
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002000/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2001Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002002 SourceLocation LabLoc,
2003 IdentifierInfo *LabelII) {
2004 // Look up the record for this label identifier.
2005 LabelStmt *&LabelDecl = LabelMap[LabelII];
2006
2007 // If we haven't seen this label yet, create a forward reference.
2008 if (LabelDecl == 0)
2009 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2010
2011 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002012 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2013 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002014}
2015
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002016Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002017 SourceLocation RPLoc) { // "({..})"
2018 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2019 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2020 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2021
2022 // FIXME: there are a variety of strange constraints to enforce here, for
2023 // example, it is not possible to goto into a stmt expression apparently.
2024 // More semantic analysis is needed.
2025
2026 // FIXME: the last statement in the compount stmt has its value used. We
2027 // should not warn about it being unused.
2028
2029 // If there are sub stmts in the compound stmt, take the type of the last one
2030 // as the type of the stmtexpr.
2031 QualType Ty = Context.VoidTy;
2032
2033 if (!Compound->body_empty())
2034 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2035 Ty = LastExpr->getType();
2036
2037 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2038}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002039
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002040Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002041 SourceLocation TypeLoc,
2042 TypeTy *argty,
2043 OffsetOfComponent *CompPtr,
2044 unsigned NumComponents,
2045 SourceLocation RPLoc) {
2046 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2047 assert(!ArgTy.isNull() && "Missing type argument!");
2048
2049 // We must have at least one component that refers to the type, and the first
2050 // one is known to be a field designator. Verify that the ArgTy represents
2051 // a struct/union/class.
2052 if (!ArgTy->isRecordType())
2053 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2054
2055 // Otherwise, create a compound literal expression as the base, and
2056 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002057 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002058
Chris Lattnerb37522e2007-08-31 21:49:13 +00002059 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2060 // GCC extension, diagnose them.
2061 if (NumComponents != 1)
2062 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2063 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2064
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002065 for (unsigned i = 0; i != NumComponents; ++i) {
2066 const OffsetOfComponent &OC = CompPtr[i];
2067 if (OC.isBrackets) {
2068 // Offset of an array sub-field. TODO: Should we allow vector elements?
2069 const ArrayType *AT = Res->getType()->getAsArrayType();
2070 if (!AT) {
2071 delete Res;
2072 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2073 Res->getType().getAsString());
2074 }
2075
Chris Lattner2af6a802007-08-30 17:59:59 +00002076 // FIXME: C++: Verify that operator[] isn't overloaded.
2077
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002078 // C99 6.5.2.1p1
2079 Expr *Idx = static_cast<Expr*>(OC.U.E);
2080 if (!Idx->getType()->isIntegerType())
2081 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2082 Idx->getSourceRange());
2083
2084 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2085 continue;
2086 }
2087
2088 const RecordType *RC = Res->getType()->getAsRecordType();
2089 if (!RC) {
2090 delete Res;
2091 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2092 Res->getType().getAsString());
2093 }
2094
2095 // Get the decl corresponding to this.
2096 RecordDecl *RD = RC->getDecl();
2097 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2098 if (!MemberDecl)
2099 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2100 OC.U.IdentInfo->getName(),
2101 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002102
2103 // FIXME: C++: Verify that MemberDecl isn't a static field.
2104 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002105 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2106 // matter here.
2107 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002108 }
2109
2110 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2111 BuiltinLoc);
2112}
2113
2114
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002115Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002116 TypeTy *arg1, TypeTy *arg2,
2117 SourceLocation RPLoc) {
2118 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2119 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2120
2121 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2122
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002123 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002124}
2125
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002126Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002127 ExprTy *expr1, ExprTy *expr2,
2128 SourceLocation RPLoc) {
2129 Expr *CondExpr = static_cast<Expr*>(cond);
2130 Expr *LHSExpr = static_cast<Expr*>(expr1);
2131 Expr *RHSExpr = static_cast<Expr*>(expr2);
2132
2133 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2134
2135 // The conditional expression is required to be a constant expression.
2136 llvm::APSInt condEval(32);
2137 SourceLocation ExpLoc;
2138 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2139 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2140 CondExpr->getSourceRange());
2141
2142 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2143 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2144 RHSExpr->getType();
2145 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2146}
2147
Nate Begemanbd881ef2008-01-30 20:50:20 +00002148/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002149/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002150/// The number of arguments has already been validated to match the number of
2151/// arguments in FnType.
2152static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002153 unsigned NumParams = FnType->getNumArgs();
2154 for (unsigned i = 0; i != NumParams; ++i)
Nate Begemanbd881ef2008-01-30 20:50:20 +00002155 if (Args[i]->getType().getCanonicalType() !=
2156 FnType->getArgType(i).getCanonicalType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002157 return false;
2158 return true;
2159}
2160
2161Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2162 SourceLocation *CommaLocs,
2163 SourceLocation BuiltinLoc,
2164 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002165 // __builtin_overload requires at least 2 arguments
2166 if (NumArgs < 2)
2167 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2168 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002169
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002170 // The first argument is required to be a constant expression. It tells us
2171 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002172 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002173 Expr *NParamsExpr = Args[0];
2174 llvm::APSInt constEval(32);
2175 SourceLocation ExpLoc;
2176 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2177 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2178 NParamsExpr->getSourceRange());
2179
2180 // Verify that the number of parameters is > 0
2181 unsigned NumParams = constEval.getZExtValue();
2182 if (NumParams == 0)
2183 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2184 NParamsExpr->getSourceRange());
2185 // Verify that we have at least 1 + NumParams arguments to the builtin.
2186 if ((NumParams + 1) > NumArgs)
2187 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2188 SourceRange(BuiltinLoc, RParenLoc));
2189
2190 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002191 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002192 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002193 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2194 // UsualUnaryConversions will convert the function DeclRefExpr into a
2195 // pointer to function.
2196 Expr *Fn = UsualUnaryConversions(Args[i]);
2197 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002198 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2199 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2200 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2201 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002202
2203 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2204 // parameters, and the number of parameters must match the value passed to
2205 // the builtin.
2206 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002207 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2208 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002209
2210 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002211 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002212 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002213 if (ExprsMatchFnType(Args+1, FnType)) {
2214 if (OE)
2215 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2216 OE->getFn()->getSourceRange());
2217 // Remember our match, and continue processing the remaining arguments
2218 // to catch any errors.
2219 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2220 BuiltinLoc, RParenLoc);
2221 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002222 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002223 // Return the newly created OverloadExpr node, if we succeded in matching
2224 // exactly one of the candidate functions.
2225 if (OE)
2226 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002227
2228 // If we didn't find a matching function Expr in the __builtin_overload list
2229 // the return an error.
2230 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002231 for (unsigned i = 0; i != NumParams; ++i) {
2232 if (i != 0) typeNames += ", ";
2233 typeNames += Args[i+1]->getType().getAsString();
2234 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002235
2236 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2237 SourceRange(BuiltinLoc, RParenLoc));
2238}
2239
Anders Carlsson36760332007-10-15 20:28:48 +00002240Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2241 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002242 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002243 Expr *E = static_cast<Expr*>(expr);
2244 QualType T = QualType::getFromOpaquePtr(type);
2245
2246 InitBuiltinVaListType();
2247
Chris Lattner005ed752008-01-04 18:04:52 +00002248 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2249 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002250 return Diag(E->getLocStart(),
2251 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2252 E->getType().getAsString(),
2253 E->getSourceRange());
2254
2255 // FIXME: Warn if a non-POD type is passed in.
2256
2257 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2258}
2259
Chris Lattner005ed752008-01-04 18:04:52 +00002260bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2261 SourceLocation Loc,
2262 QualType DstType, QualType SrcType,
2263 Expr *SrcExpr, const char *Flavor) {
2264 // Decode the result (notice that AST's are still created for extensions).
2265 bool isInvalid = false;
2266 unsigned DiagKind;
2267 switch (ConvTy) {
2268 default: assert(0 && "Unknown conversion type");
2269 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002270 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002271 DiagKind = diag::ext_typecheck_convert_pointer_int;
2272 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002273 case IntToPointer:
2274 DiagKind = diag::ext_typecheck_convert_int_pointer;
2275 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002276 case IncompatiblePointer:
2277 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2278 break;
2279 case FunctionVoidPointer:
2280 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2281 break;
2282 case CompatiblePointerDiscardsQualifiers:
2283 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2284 break;
2285 case Incompatible:
2286 DiagKind = diag::err_typecheck_convert_incompatible;
2287 isInvalid = true;
2288 break;
2289 }
2290
2291 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2292 SrcExpr->getSourceRange());
2293 return isInvalid;
2294}
2295