blob: f75c3924a000e8e4cb3a2948a088a0da7a3c0db8 [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"
Chris Lattner3e254fb2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000027#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29
Steve Naroff87d58b42007-09-16 03:34:24 +000030/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000031/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
32/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
33/// multiple tokens. However, the common case is that StringToks points to one
34/// string.
35///
36Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000037Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000038 assert(NumStringToks && "Must have at least one string!");
39
40 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
41 if (Literal.hadError)
42 return ExprResult(true);
43
44 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
45 for (unsigned i = 0; i != NumStringToks; ++i)
46 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +000047
48 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000049 if (Literal.Pascal && Literal.GetStringLength() > 256)
50 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
51 SourceRange(StringToks[0].getLocation(),
52 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000053
Chris Lattnera6dcce32008-02-11 00:02:17 +000054 QualType StrTy = Context.CharTy;
Eli Friedman256b7d72008-05-27 07:57:14 +000055 if (Literal.AnyWide) StrTy = Context.getWcharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +000056 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
57
58 // Get an array type for the string, according to C99 6.4.5. This includes
59 // the nul terminator character as well as the string length for pascal
60 // strings.
61 StrTy = Context.getConstantArrayType(StrTy,
62 llvm::APInt(32, Literal.GetStringLength()+1),
63 ArrayType::Normal, 0);
64
Chris Lattner4b009652007-07-25 00:24:17 +000065 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
66 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +000067 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000068 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000069 StringToks[NumStringToks-1].getLocation());
70}
71
72
Steve Naroff0acc9c92007-09-15 18:49:24 +000073/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000074/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +000075/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000076Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000077 IdentifierInfo &II,
78 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000079 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +000080 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000081
82 // If this reference is in an Objective-C method, then ivar lookup happens as
83 // well.
84 if (CurMethodDecl) {
Steve Naroffe57c21a2008-04-01 23:04:06 +000085 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000086 // There are two cases to handle here. 1) scoped lookup could have failed,
87 // in which case we should look for an ivar. 2) scoped lookup could have
88 // found a decl, but that decl is outside the current method (i.e. a global
89 // variable). In these two cases, we do a lookup for an ivar with this
90 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +000091 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000092 ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface(), *DeclClass;
93 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, DeclClass)) {
94 // FIXME: This should use a new expr for a direct reference, don't turn
95 // this into Self->ivar, just return a BareIVarExpr or something.
96 IdentifierInfo &II = Context.Idents.get("self");
97 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
98 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
99 static_cast<Expr*>(SelfExpr.Val), true, true);
100 }
101 }
102 }
103
Chris Lattner4b009652007-07-25 00:24:17 +0000104 if (D == 0) {
105 // Otherwise, this could be an implicitly declared function reference (legal
106 // in C90, extension in C99).
107 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000108 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000109 D = ImplicitlyDefineFunction(Loc, II, S);
110 else {
111 // If this name wasn't predeclared and if this is not a function call,
112 // diagnose the problem.
113 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
114 }
115 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000116
Steve Naroff91b03f72007-08-28 03:03:08 +0000117 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000118 // check if referencing an identifier with __attribute__((deprecated)).
119 if (VD->getAttr<DeprecatedAttr>())
120 Diag(Loc, diag::warn_deprecated, VD->getName());
121
Steve Naroffcae537d2007-08-28 18:45:29 +0000122 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000123 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000124 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000125 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000126 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000127
Chris Lattner4b009652007-07-25 00:24:17 +0000128 if (isa<TypedefDecl>(D))
129 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000130 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000131 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000132 if (isa<NamespaceDecl>(D))
133 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000134
135 assert(0 && "Invalid decl");
136 abort();
137}
138
Steve Naroff87d58b42007-09-16 03:34:24 +0000139Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000140 tok::TokenKind Kind) {
141 PreDefinedExpr::IdentType IT;
142
143 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000144 default: assert(0 && "Unknown simple primary expr!");
145 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
146 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
147 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000148 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000149
150 // Verify that this is in a function context.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000151 if (CurFunctionDecl == 0 && CurMethodDecl == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000152 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000153
Chris Lattner7e637512008-01-12 08:14:25 +0000154 // Pre-defined identifiers are of type char[x], where x is the length of the
155 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000156 unsigned Length;
157 if (CurFunctionDecl)
158 Length = CurFunctionDecl->getIdentifier()->getLength();
159 else
Fariborz Jahaniandcecd5c2008-01-17 17:37:26 +0000160 Length = CurMethodDecl->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000161
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000162 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000163 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000164 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000165 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000166}
167
Steve Naroff87d58b42007-09-16 03:34:24 +0000168Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000169 llvm::SmallString<16> CharBuffer;
170 CharBuffer.resize(Tok.getLength());
171 const char *ThisTokBegin = &CharBuffer[0];
172 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
173
174 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
175 Tok.getLocation(), PP);
176 if (Literal.hadError())
177 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000178
179 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
180
181 return new CharacterLiteral(Literal.getValue(), type, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000182}
183
Steve Naroff87d58b42007-09-16 03:34:24 +0000184Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000185 // fast path for a single digit (which is quite common). A single digit
186 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
187 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000188 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000189
Chris Lattner8cd0e932008-03-05 18:54:05 +0000190 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000191 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000192 Context.IntTy,
193 Tok.getLocation()));
194 }
195 llvm::SmallString<512> IntegerBuffer;
196 IntegerBuffer.resize(Tok.getLength());
197 const char *ThisTokBegin = &IntegerBuffer[0];
198
199 // Get the spelling of the token, which eliminates trigraphs, etc.
200 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
201 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
202 Tok.getLocation(), PP);
203 if (Literal.hadError)
204 return ExprResult(true);
205
Chris Lattner1de66eb2007-08-26 03:42:43 +0000206 Expr *Res;
207
208 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000209 QualType Ty;
210 const llvm::fltSemantics *Format;
Chris Lattner858eece2007-09-22 18:29:59 +0000211
212 if (Literal.isFloat) {
213 Ty = Context.FloatTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000214 Format = Context.Target.getFloatFormat();
215 } else if (!Literal.isLong) {
Chris Lattner858eece2007-09-22 18:29:59 +0000216 Ty = Context.DoubleTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000217 Format = Context.Target.getDoubleFormat();
218 } else {
219 Ty = Context.LongDoubleTy;
220 Format = Context.Target.getLongDoubleFormat();
Chris Lattner858eece2007-09-22 18:29:59 +0000221 }
222
Ted Kremenekddedbe22007-11-29 00:56:49 +0000223 // isExact will be set by GetFloatValue().
224 bool isExact = false;
225
226 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
227 Ty, Tok.getLocation());
228
Chris Lattner1de66eb2007-08-26 03:42:43 +0000229 } else if (!Literal.isIntegerLiteral()) {
230 return ExprResult(true);
231 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000232 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000233
Neil Booth7421e9c2007-08-29 22:00:19 +0000234 // long long is a C99 feature.
235 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000236 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000237 Diag(Tok.getLocation(), diag::ext_longlong);
238
Chris Lattner4b009652007-07-25 00:24:17 +0000239 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000240 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000241
242 if (Literal.GetIntegerValue(ResultVal)) {
243 // If this value didn't fit into uintmax_t, warn and force to ull.
244 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000245 Ty = Context.UnsignedLongLongTy;
246 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000247 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000248 } else {
249 // If this value fits into a ULL, try to figure out what else it fits into
250 // according to the rules of C99 6.4.4.1p5.
251
252 // Octal, Hexadecimal, and integers with a U suffix are allowed to
253 // be an unsigned int.
254 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
255
256 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000257 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000258 if (!Literal.isLong && !Literal.isLongLong) {
259 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000260 unsigned IntSize = Context.Target.getIntWidth();
261
Chris Lattner4b009652007-07-25 00:24:17 +0000262 // Does it fit in a unsigned int?
263 if (ResultVal.isIntN(IntSize)) {
264 // Does it fit in a signed int?
265 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000266 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000267 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000268 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000269 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000270 }
Chris Lattner4b009652007-07-25 00:24:17 +0000271 }
272
273 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000274 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000275 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000276
277 // Does it fit in a unsigned long?
278 if (ResultVal.isIntN(LongSize)) {
279 // Does it fit in a signed long?
280 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000281 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000282 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000283 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000284 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000285 }
Chris Lattner4b009652007-07-25 00:24:17 +0000286 }
287
288 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000289 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000290 unsigned LongLongSize = Context.Target.getLongLongWidth();
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 Lattnere4068872008-05-09 05:59:00 +0000299 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000300 }
301 }
302
303 // If we still couldn't decide a type, we probably have something that
304 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000305 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000306 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000307 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000308 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000309 }
Chris Lattnere4068872008-05-09 05:59:00 +0000310
311 if (ResultVal.getBitWidth() != Width)
312 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000313 }
314
Chris Lattner48d7f382008-04-02 04:24:33 +0000315 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000316 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000317
318 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
319 if (Literal.isImaginary)
320 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
321
322 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000323}
324
Steve Naroff87d58b42007-09-16 03:34:24 +0000325Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000326 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000327 Expr *E = (Expr *)Val;
328 assert((E != 0) && "ActOnParenExpr() missing expr");
329 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000330}
331
332/// The UsualUnaryConversions() function is *not* called by this routine.
333/// See C99 6.3.2.1p[2-4] for more details.
334QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
335 SourceLocation OpLoc, bool isSizeof) {
336 // C99 6.5.3.4p1:
337 if (isa<FunctionType>(exprType) && isSizeof)
338 // alignof(function) is allowed.
339 Diag(OpLoc, diag::ext_sizeof_function_type);
340 else if (exprType->isVoidType())
341 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
342 else if (exprType->isIncompleteType()) {
343 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
344 diag::err_alignof_incomplete_type,
345 exprType.getAsString());
346 return QualType(); // error
347 }
348 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
349 return Context.getSizeType();
350}
351
352Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000353ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000354 SourceLocation LPLoc, TypeTy *Ty,
355 SourceLocation RPLoc) {
356 // If error parsing type, ignore.
357 if (Ty == 0) return true;
358
359 // Verify that this is a valid expression.
360 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
361
362 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
363
364 if (resultType.isNull())
365 return true;
366 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
367}
368
Chris Lattner5110ad52007-08-24 21:41:10 +0000369QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000370 DefaultFunctionArrayConversion(V);
371
Chris Lattnera16e42d2007-08-26 05:39:26 +0000372 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000373 if (const ComplexType *CT = V->getType()->getAsComplexType())
374 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000375
376 // Otherwise they pass through real integer and floating point types here.
377 if (V->getType()->isArithmeticType())
378 return V->getType();
379
380 // Reject anything else.
381 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
382 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000383}
384
385
Chris Lattner4b009652007-07-25 00:24:17 +0000386
Steve Naroff87d58b42007-09-16 03:34:24 +0000387Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000388 tok::TokenKind Kind,
389 ExprTy *Input) {
390 UnaryOperator::Opcode Opc;
391 switch (Kind) {
392 default: assert(0 && "Unknown unary op!");
393 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
394 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
395 }
396 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
397 if (result.isNull())
398 return true;
399 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
400}
401
402Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000403ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000404 ExprTy *Idx, SourceLocation RLoc) {
405 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
406
407 // Perform default conversions.
408 DefaultFunctionArrayConversion(LHSExp);
409 DefaultFunctionArrayConversion(RHSExp);
410
411 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
412
413 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000414 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000415 // in the subscript position. As a result, we need to derive the array base
416 // and index from the expression types.
417 Expr *BaseExpr, *IndexExpr;
418 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000419 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000420 BaseExpr = LHSExp;
421 IndexExpr = RHSExp;
422 // FIXME: need to deal with const...
423 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000424 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000425 // Handle the uncommon case of "123[Ptr]".
426 BaseExpr = RHSExp;
427 IndexExpr = LHSExp;
428 // FIXME: need to deal with const...
429 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000430 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
431 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000432 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000433
434 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000435 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
436 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000437 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000438 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000439 // FIXME: need to deal with const...
440 ResultType = VTy->getElementType();
441 } else {
442 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
443 RHSExp->getSourceRange());
444 }
445 // C99 6.5.2.1p1
446 if (!IndexExpr->getType()->isIntegerType())
447 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
448 IndexExpr->getSourceRange());
449
450 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
451 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000452 // void (*)(int)) and pointers to incomplete types. Functions are not
453 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000454 if (!ResultType->isObjectType())
455 return Diag(BaseExpr->getLocStart(),
456 diag::err_typecheck_subscript_not_object,
457 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
458
459 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
460}
461
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000462QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000463CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000464 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000465 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000466
467 // This flag determines whether or not the component is to be treated as a
468 // special name, or a regular GLSL-style component access.
469 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000470
471 // The vector accessor can't exceed the number of elements.
472 const char *compStr = CompName.getName();
473 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000474 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000475 baseType.getAsString(), SourceRange(CompLoc));
476 return QualType();
477 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000478
479 // Check that we've found one of the special components, or that the component
480 // names must come from the same set.
481 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
482 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
483 SpecialComponent = true;
484 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000485 do
486 compStr++;
487 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
488 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
489 do
490 compStr++;
491 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
492 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
493 do
494 compStr++;
495 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
496 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000497
Nate Begemanc8e51f82008-05-09 06:41:27 +0000498 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000499 // We didn't get to the end of the string. This means the component names
500 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000501 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000502 std::string(compStr,compStr+1), SourceRange(CompLoc));
503 return QualType();
504 }
505 // Each component accessor can't exceed the vector type.
506 compStr = CompName.getName();
507 while (*compStr) {
508 if (vecType->isAccessorWithinNumElements(*compStr))
509 compStr++;
510 else
511 break;
512 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000513 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000514 // We didn't get to the end of the string. This means a component accessor
515 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000516 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000517 baseType.getAsString(), SourceRange(CompLoc));
518 return QualType();
519 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000520
521 // If we have a special component name, verify that the current vector length
522 // is an even number, since all special component names return exactly half
523 // the elements.
524 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
525 return QualType();
526 }
527
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000528 // The component accessor looks fine - now we need to compute the actual type.
529 // The vector type is implied by the component accessor. For example,
530 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000531 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
532 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
533 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000534 if (CompSize == 1)
535 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000536
Nate Begemanaf6ed502008-04-18 23:10:10 +0000537 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000538 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000539 // diagostics look bad. We want extended vector types to appear built-in.
540 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
541 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
542 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000543 }
544 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000545}
546
Chris Lattner4b009652007-07-25 00:24:17 +0000547Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000548ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000549 tok::TokenKind OpKind, SourceLocation MemberLoc,
550 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000551 Expr *BaseExpr = static_cast<Expr *>(Base);
552 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000553
554 // Perform default conversions.
555 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000556
Steve Naroff2cb66382007-07-26 03:11:44 +0000557 QualType BaseType = BaseExpr->getType();
558 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000559
Chris Lattner4b009652007-07-25 00:24:17 +0000560 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000561 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000562 BaseType = PT->getPointeeType();
563 else
564 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
565 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000566 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000567 // The base type is either a record or an ExtVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000568 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000569 RecordDecl *RDecl = RTy->getDecl();
570 if (RTy->isIncompleteType())
571 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
572 BaseExpr->getSourceRange());
573 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000574 FieldDecl *MemberDecl = RDecl->getMember(&Member);
575 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000576 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
577 SourceRange(MemberLoc));
Eli Friedman76b49832008-02-06 22:48:16 +0000578
579 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000580 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000581 QualType MemberType = MemberDecl->getType();
582 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000583 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000584 MemberType = MemberType.getQualifiedType(combinedQualifiers);
585
586 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
587 MemberLoc, MemberType);
Nate Begemanaf6ed502008-04-18 23:10:10 +0000588 } else if (BaseType->isExtVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000589 // Component access limited to variables (reject vec4.rg.g).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000590 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
591 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000592 return Diag(OpLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000593 SourceRange(MemberLoc));
Nate Begemanaf6ed502008-04-18 23:10:10 +0000594 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000595 if (ret.isNull())
596 return true;
Nate Begemanaf6ed502008-04-18 23:10:10 +0000597 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000598 } else if (BaseType->isObjCInterfaceType()) {
599 ObjCInterfaceDecl *IFace;
600 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
601 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000602 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000603 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
604 ObjCInterfaceDecl *clsDeclared;
605 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000606 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
607 OpKind==tok::arrow);
Steve Naroff05391d22008-05-30 00:40:33 +0000608 } else if (isObjCObjectPointerType(BaseType)) {
609 PointerType *pointerType = static_cast<PointerType*>(BaseType.getTypePtr());
610 BaseType = pointerType->getPointeeType();
611 ObjCInterfaceDecl *IFace;
612 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
613 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
614 else
615 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
616 ObjCInterfaceDecl *clsDeclared;
617 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
618 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
619 OpKind==tok::arrow);
620 // Check for properties.
621 if (OpKind==tok::period) {
622 // Before we look for explicit property declarations, we check for
623 // nullary methods (which allow '.' notation).
624 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
625 ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel);
626 if (MD)
627 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
628 MemberLoc, BaseExpr);
629 // FIXME: Need to deal with setter methods that take 1 argument. E.g.:
630 // @interface NSBundle : NSObject {}
631 // - (NSString *)bundlePath;
632 // - (void)setBundlePath:(NSString *)x;
633 // @end
634 // void someMethod() { frameworkBundle.bundlePath = 0; }
635 //
636 // FIXME: lookup explicit properties...
637 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000638 }
639 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
640 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000641}
642
Steve Naroff87d58b42007-09-16 03:34:24 +0000643/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000644/// This provides the location of the left/right parens and a list of comma
645/// locations.
646Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000647ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000648 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000649 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
650 Expr *Fn = static_cast<Expr *>(fn);
651 Expr **Args = reinterpret_cast<Expr**>(args);
652 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000653 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000654
655 // Promote the function operand.
656 UsualUnaryConversions(Fn);
657
658 // If we're directly calling a function, get the declaration for
659 // that function.
660 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
661 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
662 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
663
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000664 // Make the call expr early, before semantic checks. This guarantees cleanup
665 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000666 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000667 Context.BoolTy, RParenLoc));
668
Chris Lattner4b009652007-07-25 00:24:17 +0000669 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
670 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000671 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000672 if (PT == 0)
673 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
674 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000675 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
676 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000677 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
678 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000679
680 // We know the result type of the call, set it.
681 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000682
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000683 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000684 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
685 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000686 unsigned NumArgsInProto = Proto->getNumArgs();
687 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000688
Chris Lattner3e254fb2008-04-08 04:40:51 +0000689 // If too few arguments are available (and we don't have default
690 // arguments for the remaining parameters), don't make the call.
691 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +0000692 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000693 // Use default arguments for missing arguments
694 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +0000695 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000696 } else
697 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
698 Fn->getSourceRange());
699 }
700
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000701 // If too many are passed and not variadic, error on the extras and drop
702 // them.
703 if (NumArgs > NumArgsInProto) {
704 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000705 Diag(Args[NumArgsInProto]->getLocStart(),
706 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
707 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000708 Args[NumArgs-1]->getLocEnd()));
709 // This deletes the extra arguments.
710 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000711 }
712 NumArgsToCheck = NumArgsInProto;
713 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000714
Chris Lattner4b009652007-07-25 00:24:17 +0000715 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000716 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +0000717 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000718
719 Expr *Arg;
720 if (i < NumArgs)
721 Arg = Args[i];
722 else
723 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +0000724 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000725
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000726 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000727 AssignConvertType ConvTy =
728 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000729 TheCall->setArg(i, Arg);
730
Chris Lattner005ed752008-01-04 18:04:52 +0000731 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
732 ArgType, Arg, "passing"))
733 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000734 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000735
736 // If this is a variadic call, handle args passed through "...".
737 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000738 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000739 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
740 Expr *Arg = Args[i];
741 DefaultArgumentPromotion(Arg);
742 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000743 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000744 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000745 } else {
746 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
747
Steve Naroffdb65e052007-08-28 23:30:39 +0000748 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000749 for (unsigned i = 0; i != NumArgs; i++) {
750 Expr *Arg = Args[i];
751 DefaultArgumentPromotion(Arg);
752 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000753 }
Chris Lattner4b009652007-07-25 00:24:17 +0000754 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000755
Chris Lattner2e64c072007-08-10 20:18:51 +0000756 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +0000757 if (FDecl)
758 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +0000759
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000760 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000761}
762
763Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000764ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000765 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000766 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000767 QualType literalType = QualType::getFromOpaquePtr(Ty);
768 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000769 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000770 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000771
Eli Friedman8c2173d2008-05-20 05:22:08 +0000772 if (literalType->isArrayType()) {
773 if (literalType->getAsVariableArrayType())
774 return Diag(LParenLoc,
775 diag::err_variable_object_no_init,
776 SourceRange(LParenLoc,
777 literalExpr->getSourceRange().getEnd()));
778 } else if (literalType->isIncompleteType()) {
779 return Diag(LParenLoc,
780 diag::err_typecheck_decl_incomplete_type,
781 literalType.getAsString(),
782 SourceRange(LParenLoc,
783 literalExpr->getSourceRange().getEnd()));
784 }
785
Steve Narofff0b23542008-01-10 22:15:12 +0000786 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000787 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000788
789 bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
790 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000791 if (CheckForConstantInitializer(literalExpr, literalType))
792 return true;
793 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000794 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000795}
796
797Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000798ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000799 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000800 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000801
Steve Naroff0acc9c92007-09-15 18:49:24 +0000802 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000803 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000804
Chris Lattner48d7f382008-04-02 04:24:33 +0000805 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
806 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
807 return E;
Chris Lattner4b009652007-07-25 00:24:17 +0000808}
809
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000810bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000811 assert(VectorTy->isVectorType() && "Not a vector type!");
812
813 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000814 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000815 return Diag(R.getBegin(),
816 Ty->isVectorType() ?
817 diag::err_invalid_conversion_between_vectors :
818 diag::err_invalid_conversion_between_vector_and_integer,
819 VectorTy.getAsString().c_str(),
820 Ty.getAsString().c_str(), R);
821 } else
822 return Diag(R.getBegin(),
823 diag::err_invalid_conversion_between_vector_and_scalar,
824 VectorTy.getAsString().c_str(),
825 Ty.getAsString().c_str(), R);
826
827 return false;
828}
829
Chris Lattner4b009652007-07-25 00:24:17 +0000830Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000831ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000832 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000833 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000834
835 Expr *castExpr = static_cast<Expr*>(Op);
836 QualType castType = QualType::getFromOpaquePtr(Ty);
837
Steve Naroff68adb482007-08-31 00:32:44 +0000838 UsualUnaryConversions(castExpr);
839
Chris Lattner4b009652007-07-25 00:24:17 +0000840 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
841 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000842 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Narofff459ee52008-01-24 22:55:05 +0000843 if (!castType->isScalarType() && !castType->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000844 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
845 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Steve Narofff459ee52008-01-24 22:55:05 +0000846 if (!castExpr->getType()->isScalarType() &&
847 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000848 return Diag(castExpr->getLocStart(),
849 diag::err_typecheck_expect_scalar_operand,
850 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000851
852 if (castExpr->getType()->isVectorType()) {
853 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
854 castExpr->getType(), castType))
855 return true;
856 } else if (castType->isVectorType()) {
857 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
858 castType, castExpr->getType()))
859 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000860 }
Chris Lattner4b009652007-07-25 00:24:17 +0000861 }
862 return new CastExpr(castType, castExpr, LParenLoc);
863}
864
Chris Lattner98a425c2007-11-26 01:40:58 +0000865/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
866/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000867inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
868 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
869 UsualUnaryConversions(cond);
870 UsualUnaryConversions(lex);
871 UsualUnaryConversions(rex);
872 QualType condT = cond->getType();
873 QualType lexT = lex->getType();
874 QualType rexT = rex->getType();
875
876 // first, check the condition.
877 if (!condT->isScalarType()) { // C99 6.5.15p2
878 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
879 condT.getAsString());
880 return QualType();
881 }
Chris Lattner992ae932008-01-06 22:42:25 +0000882
883 // Now check the two expressions.
884
885 // If both operands have arithmetic type, do the usual arithmetic conversions
886 // to find a common type: C99 6.5.15p3,5.
887 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000888 UsualArithmeticConversions(lex, rex);
889 return lex->getType();
890 }
Chris Lattner992ae932008-01-06 22:42:25 +0000891
892 // If both operands are the same structure or union type, the result is that
893 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000894 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000895 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000896 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000897 // "If both the operands have structure or union type, the result has
898 // that type." This implies that CV qualifiers are dropped.
899 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000900 }
Chris Lattner992ae932008-01-06 22:42:25 +0000901
902 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +0000903 // The following || allows only one side to be void (a GCC-ism).
904 if (lexT->isVoidType() || rexT->isVoidType()) {
905 if (!lexT->isVoidType())
906 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
907 rex->getSourceRange());
908 if (!rexT->isVoidType())
909 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
910 lex->getSourceRange());
Chris Lattner992ae932008-01-06 22:42:25 +0000911 return lexT.getUnqualifiedType();
Steve Naroff95cb3892008-05-12 21:44:38 +0000912 }
Steve Naroff12ebf272008-01-08 01:11:38 +0000913 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
914 // the type of the other operand."
915 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000916 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000917 return lexT;
918 }
919 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000920 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000921 return rexT;
922 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000923 // Handle the case where both operands are pointers before we handle null
924 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000925 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
926 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
927 // get the "pointed to" types
928 QualType lhptee = LHSPT->getPointeeType();
929 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000930
Chris Lattner71225142007-07-31 21:27:01 +0000931 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
932 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +0000933 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000934 // Figure out necessary qualifiers (C99 6.5.15p6)
935 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000936 QualType destType = Context.getPointerType(destPointee);
937 ImpCastExprToType(lex, destType); // add qualifiers if necessary
938 ImpCastExprToType(rex, destType); // promote to void*
939 return destType;
940 }
Chris Lattner9db553e2008-04-02 06:59:01 +0000941 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000942 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000943 QualType destType = Context.getPointerType(destPointee);
944 ImpCastExprToType(lex, destType); // add qualifiers if necessary
945 ImpCastExprToType(rex, destType); // promote to void*
946 return destType;
947 }
Chris Lattner4b009652007-07-25 00:24:17 +0000948
Steve Naroff85f0dc52007-10-15 20:41:53 +0000949 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
950 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +0000951 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +0000952 lexT.getAsString(), rexT.getAsString(),
953 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +0000954 // In this situation, we assume void* type. No especially good
955 // reason, but this is what gcc does, and we do have to pick
956 // to get a consistent AST.
957 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
958 ImpCastExprToType(lex, voidPtrTy);
959 ImpCastExprToType(rex, voidPtrTy);
960 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +0000961 }
962 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000963 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
964 // differently qualified versions of compatible types, the result type is
965 // a pointer to an appropriately qualified version of the *composite*
966 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +0000967 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +0000968 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +0000969 QualType compositeType = lexT;
970 ImpCastExprToType(lex, compositeType);
971 ImpCastExprToType(rex, compositeType);
972 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +0000973 }
Chris Lattner4b009652007-07-25 00:24:17 +0000974 }
Steve Naroff605896f2008-05-31 22:33:45 +0000975 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
976 // evaluates to "struct objc_object *" (and is handled above when comparing
977 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType?
978 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
979 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true))
980 return Context.getObjCIdType();
981 }
Chris Lattner992ae932008-01-06 22:42:25 +0000982 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000983 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
984 lexT.getAsString(), rexT.getAsString(),
985 lex->getSourceRange(), rex->getSourceRange());
986 return QualType();
987}
988
Steve Naroff87d58b42007-09-16 03:34:24 +0000989/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000990/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000991Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000992 SourceLocation ColonLoc,
993 ExprTy *Cond, ExprTy *LHS,
994 ExprTy *RHS) {
995 Expr *CondExpr = (Expr *) Cond;
996 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000997
998 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
999 // was the condition.
1000 bool isLHSNull = LHSExpr == 0;
1001 if (isLHSNull)
1002 LHSExpr = CondExpr;
1003
Chris Lattner4b009652007-07-25 00:24:17 +00001004 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1005 RHSExpr, QuestionLoc);
1006 if (result.isNull())
1007 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001008 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1009 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001010}
1011
Steve Naroffdb65e052007-08-28 23:30:39 +00001012/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +00001013/// do not have a prototype. Arguments that have type float are promoted to
1014/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001015void Sema::DefaultArgumentPromotion(Expr *&Expr) {
1016 QualType Ty = Expr->getType();
1017 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +00001018
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001019 if (Ty == Context.FloatTy)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001020 ImpCastExprToType(Expr, Context.DoubleTy);
Steve Naroffbbaed752008-01-29 02:42:22 +00001021 else
1022 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +00001023}
1024
Chris Lattner4b009652007-07-25 00:24:17 +00001025/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Chris Lattner48d7f382008-04-02 04:24:33 +00001026void Sema::DefaultFunctionArrayConversion(Expr *&E) {
1027 QualType Ty = E->getType();
1028 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001029
Chris Lattner48d7f382008-04-02 04:24:33 +00001030 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +00001031 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
Chris Lattner48d7f382008-04-02 04:24:33 +00001032 Ty = E->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001033 }
Chris Lattner48d7f382008-04-02 04:24:33 +00001034 if (Ty->isFunctionType())
1035 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner19eb97e2008-04-02 05:18:44 +00001036 else if (Ty->isArrayType())
1037 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
Chris Lattner4b009652007-07-25 00:24:17 +00001038}
1039
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001040/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +00001041/// operators (C99 6.3). The conversions of array and function types are
1042/// sometimes surpressed. For example, the array->pointer conversion doesn't
1043/// apply if the array is an argument to the sizeof or address (&) operators.
1044/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001045Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
1046 QualType Ty = Expr->getType();
1047 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001048
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001049 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +00001050 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001051 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001052 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001053 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +00001054 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +00001055 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001056 DefaultFunctionArrayConversion(Expr);
1057
1058 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +00001059}
1060
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001061/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +00001062/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1063/// routine returns the first non-arithmetic type found. The client is
1064/// responsible for emitting appropriate error diagnostics.
Chris Lattner48d7f382008-04-02 04:24:33 +00001065/// FIXME: verify the conversion rules for "complex int" are consistent with
1066/// GCC.
Steve Naroff8f708362007-08-24 19:07:16 +00001067QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
1068 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +00001069 if (!isCompAssign) {
1070 UsualUnaryConversions(lhsExpr);
1071 UsualUnaryConversions(rhsExpr);
1072 }
Steve Naroff7438fdf2007-10-18 18:55:53 +00001073 // For conversion purposes, we ignore any qualifiers.
1074 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +00001075 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
1076 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001077
1078 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +00001079 if (lhs == rhs)
1080 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001081
1082 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1083 // The caller can deal with this (e.g. pointer + int).
1084 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001085 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001086
1087 // At this point, we have two different arithmetic types.
1088
1089 // Handle complex types first (C99 6.3.1.8p1).
1090 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +00001091 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001092 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001093 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001094 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001095 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +00001096 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001097 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001098 // convert the lhs to the rhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001099 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001100 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001101 }
Steve Naroff3cf497f2007-08-27 01:27:54 +00001102 // This handles complex/complex, complex/float, or float/complex.
1103 // When both operands are complex, the shorter operand is converted to the
1104 // type of the longer, and that is the type of the result. This corresponds
1105 // to what is done when combining two real floating-point operands.
1106 // The fun begins when size promotion occur across type domains.
1107 // From H&S 6.3.4: When one operand is complex and the other is a real
1108 // floating-point type, the less precise type is converted, within it's
1109 // real or complex domain, to the precision of the other type. For example,
1110 // when combining a "long double" with a "double _Complex", the
1111 // "double _Complex" is promoted to "long double _Complex".
Chris Lattnerd7135b42008-04-06 23:38:49 +00001112 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001113
1114 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001115 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1116 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001117 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001118 } else if (result < 0) { // The right side is bigger, convert lhs.
1119 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1120 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001121 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001122 }
1123 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1124 // domains match. This is a requirement for our implementation, C99
1125 // does not require this promotion.
1126 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1127 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001128 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001129 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001130 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001131 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001132 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001133 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001134 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001135 }
Chris Lattner4b009652007-07-25 00:24:17 +00001136 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001137 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001138 }
1139 // Now handle "real" floating types (i.e. float, double, long double).
1140 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1141 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001142 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001143 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001144 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001145 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001146 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001147 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001148 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001149 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001150 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001151 }
1152 // We have two real floating types, float/complex combos were handled above.
1153 // Convert the smaller operand to the bigger result.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001154 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001155
1156 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001157 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001158 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001159 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001160 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001161 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001162 return rhs;
1163 }
1164 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001165 }
Steve Naroff43001212008-01-15 19:36:10 +00001166 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1167 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001168 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001169 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001170
Eli Friedman50727042008-02-08 01:19:44 +00001171 if (lhsComplexInt && rhsComplexInt) {
Chris Lattner51285d82008-04-06 23:55:33 +00001172 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
1173 rhsComplexInt->getElementType()) >= 0) {
Eli Friedman94075c02008-02-08 01:24:30 +00001174 // convert the rhs
1175 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1176 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001177 }
1178 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001179 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001180 return rhs;
1181 } else if (lhsComplexInt && rhs->isIntegerType()) {
1182 // convert the rhs to the lhs complex type.
1183 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1184 return lhs;
1185 } else if (rhsComplexInt && lhs->isIntegerType()) {
1186 // convert the lhs to the rhs complex type.
1187 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1188 return rhs;
1189 }
Steve Naroff43001212008-01-15 19:36:10 +00001190 }
Chris Lattner4b009652007-07-25 00:24:17 +00001191 // Finally, we have two differing integer types.
Chris Lattner51285d82008-04-06 23:55:33 +00001192 if (Context.getIntegerTypeOrder(lhs, rhs) >= 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001193 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001194 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001195 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001196 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff8f708362007-08-24 19:07:16 +00001197 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001198}
1199
1200// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1201// being closely modeled after the C99 spec:-). The odd characteristic of this
1202// routine is it effectively iqnores the qualifiers on the top level pointee.
1203// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1204// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001205Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001206Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1207 QualType lhptee, rhptee;
1208
1209 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001210 lhptee = lhsType->getAsPointerType()->getPointeeType();
1211 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001212
1213 // make sure we operate on the canonical type
1214 lhptee = lhptee.getCanonicalType();
1215 rhptee = rhptee.getCanonicalType();
1216
Chris Lattner005ed752008-01-04 18:04:52 +00001217 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001218
1219 // C99 6.5.16.1p1: This following citation is common to constraints
1220 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1221 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001222 // FIXME: Handle ASQualType
1223 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1224 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001225 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001226
1227 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1228 // incomplete type and the other is a pointer to a qualified or unqualified
1229 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001230 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001231 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001232 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001233
1234 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001235 assert(rhptee->isFunctionType());
1236 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001237 }
1238
1239 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001240 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001241 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001242
1243 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001244 assert(lhptee->isFunctionType());
1245 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001246 }
1247
Chris Lattner4b009652007-07-25 00:24:17 +00001248 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1249 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001250 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1251 rhptee.getUnqualifiedType()))
1252 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001253 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001254}
1255
1256/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1257/// has code to accommodate several GCC extensions when type checking
1258/// pointers. Here are some objectionable examples that GCC considers warnings:
1259///
1260/// int a, *pint;
1261/// short *pshort;
1262/// struct foo *pfoo;
1263///
1264/// pint = pshort; // warning: assignment from incompatible pointer type
1265/// a = pint; // warning: assignment makes integer from pointer without a cast
1266/// pint = a; // warning: assignment makes pointer from integer without a cast
1267/// pint = pfoo; // warning: assignment from incompatible pointer type
1268///
1269/// As a result, the code for dealing with pointers is more complex than the
1270/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001271///
Chris Lattner005ed752008-01-04 18:04:52 +00001272Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001273Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001274 // Get canonical types. We're not formatting these types, just comparing
1275 // them.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001276 lhsType = lhsType.getCanonicalType().getUnqualifiedType();
1277 rhsType = rhsType.getCanonicalType().getUnqualifiedType();
1278
1279 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001280 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001281
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001282 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001283 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001284 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001285 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001286 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001287
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001288 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1289 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001290 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001291 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001292 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001293
Chris Lattner390564e2008-04-07 06:49:41 +00001294 if (isa<VectorType>(lhsType) || isa<VectorType>(rhsType)) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001295 // For ExtVector, allow vector splats; float -> <n x float>
1296 if (const ExtVectorType *LV = dyn_cast<ExtVectorType>(lhsType)) {
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001297 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1298 return Compatible;
1299 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001300
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001301 // If LHS and RHS are both vectors of integer or both vectors of floating
1302 // point types, and the total vector length is the same, allow the
1303 // conversion. This is a bitcast; no bits are changed but the result type
1304 // is different.
1305 if (getLangOptions().LaxVectorConversions &&
1306 lhsType->isVectorType() && rhsType->isVectorType()) {
1307 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1308 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001309 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Nate Begemanec2d1062007-12-30 02:59:45 +00001310 return Compatible;
1311 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001312 }
1313 return Incompatible;
1314 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001315
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001316 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001317 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001318
Chris Lattner390564e2008-04-07 06:49:41 +00001319 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001320 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001321 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001322
Chris Lattner390564e2008-04-07 06:49:41 +00001323 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001324 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001325 return Incompatible;
1326 }
1327
Chris Lattner390564e2008-04-07 06:49:41 +00001328 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001329 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001330 if (lhsType == Context.BoolTy)
1331 return Compatible;
1332
1333 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001334 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001335
Chris Lattner390564e2008-04-07 06:49:41 +00001336 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001337 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001338 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001339 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001340
Chris Lattner1853da22008-01-04 23:18:45 +00001341 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001342 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001343 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001344 }
1345 return Incompatible;
1346}
1347
Chris Lattner005ed752008-01-04 18:04:52 +00001348Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001349Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001350 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1351 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001352 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001353 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001354 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001355 return Compatible;
1356 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001357 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001358 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001359 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001360 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001361 //
1362 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1363 // are better understood.
1364 if (!lhsType->isReferenceType())
1365 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001366
Chris Lattner005ed752008-01-04 18:04:52 +00001367 Sema::AssignConvertType result =
1368 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001369
1370 // C99 6.5.16.1p2: The value of the right operand is converted to the
1371 // type of the assignment expression.
1372 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001373 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001374 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001375}
1376
Chris Lattner005ed752008-01-04 18:04:52 +00001377Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001378Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1379 return CheckAssignmentConstraints(lhsType, rhsType);
1380}
1381
Chris Lattner2c8bff72007-12-12 05:47:28 +00001382QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001383 Diag(loc, diag::err_typecheck_invalid_operands,
1384 lex->getType().getAsString(), rex->getType().getAsString(),
1385 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001386 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001387}
1388
1389inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1390 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001391 // For conversion purposes, we ignore any qualifiers.
1392 // For example, "const float" and "float" are equivalent.
1393 QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType();
1394 QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001395
1396 // make sure the vector types are identical.
Nate Begeman03105572008-04-04 01:30:25 +00001397 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001398 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001399
Nate Begemanaf6ed502008-04-18 23:10:10 +00001400 // if the lhs is an extended vector and the rhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001401 // promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001402 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001403 if (V->getElementType().getCanonicalType().getTypePtr()
1404 == rhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001405 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001406 return lhsType;
1407 }
1408 }
1409
Nate Begemanaf6ed502008-04-18 23:10:10 +00001410 // if the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001411 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001412 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001413 if (V->getElementType().getCanonicalType().getTypePtr()
1414 == lhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001415 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001416 return rhsType;
1417 }
1418 }
1419
Chris Lattner4b009652007-07-25 00:24:17 +00001420 // You cannot convert between vector values of different size.
1421 Diag(loc, diag::err_typecheck_vector_not_convertable,
1422 lex->getType().getAsString(), rex->getType().getAsString(),
1423 lex->getSourceRange(), rex->getSourceRange());
1424 return QualType();
1425}
1426
1427inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001428 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001429{
1430 QualType lhsType = lex->getType(), rhsType = rex->getType();
1431
1432 if (lhsType->isVectorType() || rhsType->isVectorType())
1433 return CheckVectorOperands(loc, lex, rex);
1434
Steve Naroff8f708362007-08-24 19:07:16 +00001435 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001436
Chris Lattner4b009652007-07-25 00:24:17 +00001437 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001438 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001439 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001440}
1441
1442inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001443 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001444{
1445 QualType lhsType = lex->getType(), rhsType = rex->getType();
1446
Steve Naroff8f708362007-08-24 19:07:16 +00001447 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001448
Chris Lattner4b009652007-07-25 00:24:17 +00001449 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001450 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001451 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001452}
1453
1454inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001455 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001456{
1457 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1458 return CheckVectorOperands(loc, lex, rex);
1459
Steve Naroff8f708362007-08-24 19:07:16 +00001460 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001461
Chris Lattner4b009652007-07-25 00:24:17 +00001462 // handle the common case first (both operands are arithmetic).
1463 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001464 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001465
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001466 // Put any potential pointer into PExp
1467 Expr* PExp = lex, *IExp = rex;
1468 if (IExp->getType()->isPointerType())
1469 std::swap(PExp, IExp);
1470
1471 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1472 if (IExp->getType()->isIntegerType()) {
1473 // Check for arithmetic on pointers to incomplete types
1474 if (!PTy->getPointeeType()->isObjectType()) {
1475 if (PTy->getPointeeType()->isVoidType()) {
1476 Diag(loc, diag::ext_gnu_void_ptr,
1477 lex->getSourceRange(), rex->getSourceRange());
1478 } else {
1479 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1480 lex->getType().getAsString(), lex->getSourceRange());
1481 return QualType();
1482 }
1483 }
1484 return PExp->getType();
1485 }
1486 }
1487
Chris Lattner2c8bff72007-12-12 05:47:28 +00001488 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001489}
1490
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001491// C99 6.5.6
1492QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1493 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001494 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1495 return CheckVectorOperands(loc, lex, rex);
1496
Steve Naroff8f708362007-08-24 19:07:16 +00001497 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001498
Chris Lattnerf6da2912007-12-09 21:53:25 +00001499 // Enforce type constraints: C99 6.5.6p3.
1500
1501 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001502 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001503 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001504
1505 // Either ptr - int or ptr - ptr.
1506 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001507 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001508
Chris Lattnerf6da2912007-12-09 21:53:25 +00001509 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001510 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001511 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001512 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001513 Diag(loc, diag::ext_gnu_void_ptr,
1514 lex->getSourceRange(), rex->getSourceRange());
1515 } else {
1516 Diag(loc, diag::err_typecheck_sub_ptr_object,
1517 lex->getType().getAsString(), lex->getSourceRange());
1518 return QualType();
1519 }
1520 }
1521
1522 // The result type of a pointer-int computation is the pointer type.
1523 if (rex->getType()->isIntegerType())
1524 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001525
Chris Lattnerf6da2912007-12-09 21:53:25 +00001526 // Handle pointer-pointer subtractions.
1527 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001528 QualType rpointee = RHSPTy->getPointeeType();
1529
Chris Lattnerf6da2912007-12-09 21:53:25 +00001530 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001531 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001532 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001533 if (rpointee->isVoidType()) {
1534 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001535 Diag(loc, diag::ext_gnu_void_ptr,
1536 lex->getSourceRange(), rex->getSourceRange());
1537 } else {
1538 Diag(loc, diag::err_typecheck_sub_ptr_object,
1539 rex->getType().getAsString(), rex->getSourceRange());
1540 return QualType();
1541 }
1542 }
1543
1544 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001545 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1546 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001547 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1548 lex->getType().getAsString(), rex->getType().getAsString(),
1549 lex->getSourceRange(), rex->getSourceRange());
1550 return QualType();
1551 }
1552
1553 return Context.getPointerDiffType();
1554 }
1555 }
1556
Chris Lattner2c8bff72007-12-12 05:47:28 +00001557 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001558}
1559
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001560// C99 6.5.7
1561QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1562 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001563 // C99 6.5.7p2: Each of the operands shall have integer type.
1564 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1565 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001566
Chris Lattner2c8bff72007-12-12 05:47:28 +00001567 // Shifts don't perform usual arithmetic conversions, they just do integer
1568 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001569 if (!isCompAssign)
1570 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001571 UsualUnaryConversions(rex);
1572
1573 // "The type of the result is that of the promoted left operand."
1574 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001575}
1576
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001577// C99 6.5.8
1578QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1579 bool isRelational) {
Chris Lattner254f3bc2007-08-26 01:18:55 +00001580 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001581 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1582 UsualArithmeticConversions(lex, rex);
1583 else {
1584 UsualUnaryConversions(lex);
1585 UsualUnaryConversions(rex);
1586 }
Chris Lattner4b009652007-07-25 00:24:17 +00001587 QualType lType = lex->getType();
1588 QualType rType = rex->getType();
1589
Ted Kremenek486509e2007-10-29 17:13:39 +00001590 // For non-floating point types, check for self-comparisons of the form
1591 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1592 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001593 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001594 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1595 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001596 if (DRL->getDecl() == DRR->getDecl())
1597 Diag(loc, diag::warn_selfcomparison);
1598 }
1599
Chris Lattner254f3bc2007-08-26 01:18:55 +00001600 if (isRelational) {
1601 if (lType->isRealType() && rType->isRealType())
1602 return Context.IntTy;
1603 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001604 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001605 if (lType->isFloatingType()) {
1606 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001607 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001608 }
1609
Chris Lattner254f3bc2007-08-26 01:18:55 +00001610 if (lType->isArithmeticType() && rType->isArithmeticType())
1611 return Context.IntTy;
1612 }
Chris Lattner4b009652007-07-25 00:24:17 +00001613
Chris Lattner22be8422007-08-26 01:10:14 +00001614 bool LHSIsNull = lex->isNullPointerConstant(Context);
1615 bool RHSIsNull = rex->isNullPointerConstant(Context);
1616
Chris Lattner254f3bc2007-08-26 01:18:55 +00001617 // All of the following pointer related warnings are GCC extensions, except
1618 // when handling null pointer constants. One day, we can consider making them
1619 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001620 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001621 QualType LCanPointeeTy =
1622 lType->getAsPointerType()->getPointeeType().getCanonicalType();
1623 QualType RCanPointeeTy =
1624 rType->getAsPointerType()->getPointeeType().getCanonicalType();
Eli Friedman50727042008-02-08 01:19:44 +00001625
Steve Naroff3b435622007-11-13 14:57:38 +00001626 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001627 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1628 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1629 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001630 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1631 lType.getAsString(), rType.getAsString(),
1632 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001633 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001634 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001635 return Context.IntTy;
1636 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001637 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001638 && ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001639 ImpCastExprToType(rex, lType);
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001640 return Context.IntTy;
1641 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001642 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001643 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001644 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1645 lType.getAsString(), rType.getAsString(),
1646 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001647 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001648 return Context.IntTy;
1649 }
1650 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001651 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001652 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1653 lType.getAsString(), rType.getAsString(),
1654 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001655 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001656 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001657 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001658 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001659}
1660
Chris Lattner4b009652007-07-25 00:24:17 +00001661inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001662 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001663{
1664 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1665 return CheckVectorOperands(loc, lex, rex);
1666
Steve Naroff8f708362007-08-24 19:07:16 +00001667 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001668
1669 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001670 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001671 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001672}
1673
1674inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1675 Expr *&lex, Expr *&rex, SourceLocation loc)
1676{
1677 UsualUnaryConversions(lex);
1678 UsualUnaryConversions(rex);
1679
Eli Friedmanbea3f842008-05-13 20:16:47 +00001680 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00001681 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001682 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001683}
1684
1685inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001686 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001687{
1688 QualType lhsType = lex->getType();
1689 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001690 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1691
1692 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001693 case Expr::MLV_Valid:
1694 break;
1695 case Expr::MLV_ConstQualified:
1696 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1697 return QualType();
1698 case Expr::MLV_ArrayType:
1699 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1700 lhsType.getAsString(), lex->getSourceRange());
1701 return QualType();
1702 case Expr::MLV_NotObjectType:
1703 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1704 lhsType.getAsString(), lex->getSourceRange());
1705 return QualType();
1706 case Expr::MLV_InvalidExpression:
1707 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1708 lex->getSourceRange());
1709 return QualType();
1710 case Expr::MLV_IncompleteType:
1711 case Expr::MLV_IncompleteVoidType:
1712 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1713 lhsType.getAsString(), lex->getSourceRange());
1714 return QualType();
1715 case Expr::MLV_DuplicateVectorComponents:
1716 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1717 lex->getSourceRange());
1718 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001719 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001720
Chris Lattner005ed752008-01-04 18:04:52 +00001721 AssignConvertType ConvTy;
1722 if (compoundType.isNull())
1723 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1724 else
1725 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1726
1727 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1728 rex, "assigning"))
1729 return QualType();
1730
Chris Lattner4b009652007-07-25 00:24:17 +00001731 // C99 6.5.16p3: The type of an assignment expression is the type of the
1732 // left operand unless the left operand has qualified type, in which case
1733 // it is the unqualified version of the type of the left operand.
1734 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1735 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001736 // C++ 5.17p1: the type of the assignment expression is that of its left
1737 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001738 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001739}
1740
1741inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1742 Expr *&lex, Expr *&rex, SourceLocation loc) {
1743 UsualUnaryConversions(rex);
1744 return rex->getType();
1745}
1746
1747/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1748/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1749QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1750 QualType resType = op->getType();
1751 assert(!resType.isNull() && "no type for increment/decrement expression");
1752
Steve Naroffd30e1932007-08-24 17:20:07 +00001753 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001754 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001755 if (pt->getPointeeType()->isVoidType()) {
1756 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
1757 } else if (!pt->getPointeeType()->isObjectType()) {
1758 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00001759 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1760 resType.getAsString(), op->getSourceRange());
1761 return QualType();
1762 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001763 } else if (!resType->isRealType()) {
1764 if (resType->isComplexType())
1765 // C99 does not support ++/-- on complex types.
1766 Diag(OpLoc, diag::ext_integer_increment_complex,
1767 resType.getAsString(), op->getSourceRange());
1768 else {
1769 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1770 resType.getAsString(), op->getSourceRange());
1771 return QualType();
1772 }
Chris Lattner4b009652007-07-25 00:24:17 +00001773 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001774 // At this point, we know we have a real, complex or pointer type.
1775 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001776 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1777 if (mlval != Expr::MLV_Valid) {
1778 // FIXME: emit a more precise diagnostic...
1779 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1780 op->getSourceRange());
1781 return QualType();
1782 }
1783 return resType;
1784}
1785
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001786/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001787/// This routine allows us to typecheck complex/recursive expressions
1788/// where the declaration is needed for type checking. Here are some
1789/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Chris Lattner48d7f382008-04-02 04:24:33 +00001790static ValueDecl *getPrimaryDecl(Expr *E) {
1791 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001792 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001793 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001794 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001795 // Fields cannot be declared with a 'register' storage class.
1796 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00001797 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00001798 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00001799 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001800 case Stmt::ArraySubscriptExprClass: {
1801 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1802
Chris Lattner48d7f382008-04-02 04:24:33 +00001803 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001804 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001805 return 0;
1806 else
1807 return VD;
1808 }
Chris Lattner4b009652007-07-25 00:24:17 +00001809 case Stmt::UnaryOperatorClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001810 return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001811 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001812 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001813 case Stmt::ImplicitCastExprClass:
1814 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00001815 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001816 default:
1817 return 0;
1818 }
1819}
1820
1821/// CheckAddressOfOperand - The operand of & must be either a function
1822/// designator or an lvalue designating an object. If it is an lvalue, the
1823/// object cannot be declared with storage class register or be a bit field.
1824/// Note: The usual conversions are *not* applied to the operand of the &
1825/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1826QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001827 if (getLangOptions().C99) {
1828 // Implement C99-only parts of addressof rules.
1829 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1830 if (uOp->getOpcode() == UnaryOperator::Deref)
1831 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1832 // (assuming the deref expression is valid).
1833 return uOp->getSubExpr()->getType();
1834 }
1835 // Technically, there should be a check for array subscript
1836 // expressions here, but the result of one is always an lvalue anyway.
1837 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001838 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001839 Expr::isLvalueResult lval = op->isLvalue();
1840
1841 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001842 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1843 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001844 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1845 op->getSourceRange());
1846 return QualType();
1847 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00001848 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1849 if (MemExpr->getMemberDecl()->isBitField()) {
1850 Diag(OpLoc, diag::err_typecheck_address_of,
1851 std::string("bit-field"), op->getSourceRange());
1852 return QualType();
1853 }
1854 // Check for Apple extension for accessing vector components.
1855 } else if (isa<ArraySubscriptExpr>(op) &&
1856 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
1857 Diag(OpLoc, diag::err_typecheck_address_of,
1858 std::string("vector"), op->getSourceRange());
1859 return QualType();
1860 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00001861 // We have an lvalue with a decl. Make sure the decl is not declared
1862 // with the register storage-class specifier.
1863 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1864 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00001865 Diag(OpLoc, diag::err_typecheck_address_of,
1866 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001867 return QualType();
1868 }
1869 } else
1870 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00001871 }
1872 // If the operand has type "type", the result has type "pointer to type".
1873 return Context.getPointerType(op->getType());
1874}
1875
1876QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1877 UsualUnaryConversions(op);
1878 QualType qType = op->getType();
1879
Chris Lattner7931f4a2007-07-31 16:53:04 +00001880 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001881 // Note that per both C89 and C99, this is always legal, even
1882 // if ptype is an incomplete type or void.
1883 // It would be possible to warn about dereferencing a
1884 // void pointer, but it's completely well-defined,
1885 // and such a warning is unlikely to catch any mistakes.
1886 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001887 }
1888 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1889 qType.getAsString(), op->getSourceRange());
1890 return QualType();
1891}
1892
1893static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1894 tok::TokenKind Kind) {
1895 BinaryOperator::Opcode Opc;
1896 switch (Kind) {
1897 default: assert(0 && "Unknown binop!");
1898 case tok::star: Opc = BinaryOperator::Mul; break;
1899 case tok::slash: Opc = BinaryOperator::Div; break;
1900 case tok::percent: Opc = BinaryOperator::Rem; break;
1901 case tok::plus: Opc = BinaryOperator::Add; break;
1902 case tok::minus: Opc = BinaryOperator::Sub; break;
1903 case tok::lessless: Opc = BinaryOperator::Shl; break;
1904 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1905 case tok::lessequal: Opc = BinaryOperator::LE; break;
1906 case tok::less: Opc = BinaryOperator::LT; break;
1907 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1908 case tok::greater: Opc = BinaryOperator::GT; break;
1909 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1910 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1911 case tok::amp: Opc = BinaryOperator::And; break;
1912 case tok::caret: Opc = BinaryOperator::Xor; break;
1913 case tok::pipe: Opc = BinaryOperator::Or; break;
1914 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1915 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1916 case tok::equal: Opc = BinaryOperator::Assign; break;
1917 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1918 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1919 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1920 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1921 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1922 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1923 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1924 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1925 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1926 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1927 case tok::comma: Opc = BinaryOperator::Comma; break;
1928 }
1929 return Opc;
1930}
1931
1932static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1933 tok::TokenKind Kind) {
1934 UnaryOperator::Opcode Opc;
1935 switch (Kind) {
1936 default: assert(0 && "Unknown unary op!");
1937 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1938 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1939 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1940 case tok::star: Opc = UnaryOperator::Deref; break;
1941 case tok::plus: Opc = UnaryOperator::Plus; break;
1942 case tok::minus: Opc = UnaryOperator::Minus; break;
1943 case tok::tilde: Opc = UnaryOperator::Not; break;
1944 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1945 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1946 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1947 case tok::kw___real: Opc = UnaryOperator::Real; break;
1948 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1949 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1950 }
1951 return Opc;
1952}
1953
1954// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001955Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001956 ExprTy *LHS, ExprTy *RHS) {
1957 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1958 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1959
Steve Naroff87d58b42007-09-16 03:34:24 +00001960 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1961 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001962
1963 QualType ResultTy; // Result type of the binary operator.
1964 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1965
1966 switch (Opc) {
1967 default:
1968 assert(0 && "Unknown binary expr!");
1969 case BinaryOperator::Assign:
1970 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1971 break;
1972 case BinaryOperator::Mul:
1973 case BinaryOperator::Div:
1974 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1975 break;
1976 case BinaryOperator::Rem:
1977 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1978 break;
1979 case BinaryOperator::Add:
1980 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1981 break;
1982 case BinaryOperator::Sub:
1983 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1984 break;
1985 case BinaryOperator::Shl:
1986 case BinaryOperator::Shr:
1987 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1988 break;
1989 case BinaryOperator::LE:
1990 case BinaryOperator::LT:
1991 case BinaryOperator::GE:
1992 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001993 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001994 break;
1995 case BinaryOperator::EQ:
1996 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001997 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001998 break;
1999 case BinaryOperator::And:
2000 case BinaryOperator::Xor:
2001 case BinaryOperator::Or:
2002 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2003 break;
2004 case BinaryOperator::LAnd:
2005 case BinaryOperator::LOr:
2006 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2007 break;
2008 case BinaryOperator::MulAssign:
2009 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002010 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002011 if (!CompTy.isNull())
2012 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2013 break;
2014 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002015 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002016 if (!CompTy.isNull())
2017 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2018 break;
2019 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002020 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002021 if (!CompTy.isNull())
2022 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2023 break;
2024 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002025 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002026 if (!CompTy.isNull())
2027 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2028 break;
2029 case BinaryOperator::ShlAssign:
2030 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002031 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002032 if (!CompTy.isNull())
2033 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2034 break;
2035 case BinaryOperator::AndAssign:
2036 case BinaryOperator::XorAssign:
2037 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002038 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002039 if (!CompTy.isNull())
2040 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2041 break;
2042 case BinaryOperator::Comma:
2043 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2044 break;
2045 }
2046 if (ResultTy.isNull())
2047 return true;
2048 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002049 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002050 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002051 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002052}
2053
2054// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002055Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002056 ExprTy *input) {
2057 Expr *Input = (Expr*)input;
2058 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2059 QualType resultType;
2060 switch (Opc) {
2061 default:
2062 assert(0 && "Unimplemented unary expr!");
2063 case UnaryOperator::PreInc:
2064 case UnaryOperator::PreDec:
2065 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2066 break;
2067 case UnaryOperator::AddrOf:
2068 resultType = CheckAddressOfOperand(Input, OpLoc);
2069 break;
2070 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002071 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002072 resultType = CheckIndirectionOperand(Input, OpLoc);
2073 break;
2074 case UnaryOperator::Plus:
2075 case UnaryOperator::Minus:
2076 UsualUnaryConversions(Input);
2077 resultType = Input->getType();
2078 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2079 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2080 resultType.getAsString());
2081 break;
2082 case UnaryOperator::Not: // bitwise complement
2083 UsualUnaryConversions(Input);
2084 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00002085 // C99 6.5.3.3p1. We allow complex as a GCC extension.
2086 if (!resultType->isIntegerType()) {
2087 if (resultType->isComplexType())
2088 // C99 does not support '~' for complex conjugation.
2089 Diag(OpLoc, diag::ext_integer_complement_complex,
2090 resultType.getAsString());
2091 else
2092 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2093 resultType.getAsString());
2094 }
Chris Lattner4b009652007-07-25 00:24:17 +00002095 break;
2096 case UnaryOperator::LNot: // logical negation
2097 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2098 DefaultFunctionArrayConversion(Input);
2099 resultType = Input->getType();
2100 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2101 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2102 resultType.getAsString());
2103 // LNot always has type int. C99 6.5.3.3p5.
2104 resultType = Context.IntTy;
2105 break;
2106 case UnaryOperator::SizeOf:
2107 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
2108 break;
2109 case UnaryOperator::AlignOf:
2110 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
2111 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002112 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002113 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002114 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002115 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002116 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002117 resultType = Input->getType();
2118 break;
2119 }
2120 if (resultType.isNull())
2121 return true;
2122 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2123}
2124
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002125/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2126Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002127 SourceLocation LabLoc,
2128 IdentifierInfo *LabelII) {
2129 // Look up the record for this label identifier.
2130 LabelStmt *&LabelDecl = LabelMap[LabelII];
2131
2132 // If we haven't seen this label yet, create a forward reference.
2133 if (LabelDecl == 0)
2134 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2135
2136 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002137 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2138 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002139}
2140
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002141Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002142 SourceLocation RPLoc) { // "({..})"
2143 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2144 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2145 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2146
2147 // FIXME: there are a variety of strange constraints to enforce here, for
2148 // example, it is not possible to goto into a stmt expression apparently.
2149 // More semantic analysis is needed.
2150
2151 // FIXME: the last statement in the compount stmt has its value used. We
2152 // should not warn about it being unused.
2153
2154 // If there are sub stmts in the compound stmt, take the type of the last one
2155 // as the type of the stmtexpr.
2156 QualType Ty = Context.VoidTy;
2157
2158 if (!Compound->body_empty())
2159 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2160 Ty = LastExpr->getType();
2161
2162 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2163}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002164
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002165Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002166 SourceLocation TypeLoc,
2167 TypeTy *argty,
2168 OffsetOfComponent *CompPtr,
2169 unsigned NumComponents,
2170 SourceLocation RPLoc) {
2171 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2172 assert(!ArgTy.isNull() && "Missing type argument!");
2173
2174 // We must have at least one component that refers to the type, and the first
2175 // one is known to be a field designator. Verify that the ArgTy represents
2176 // a struct/union/class.
2177 if (!ArgTy->isRecordType())
2178 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2179
2180 // Otherwise, create a compound literal expression as the base, and
2181 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002182 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002183
Chris Lattnerb37522e2007-08-31 21:49:13 +00002184 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2185 // GCC extension, diagnose them.
2186 if (NumComponents != 1)
2187 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2188 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2189
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002190 for (unsigned i = 0; i != NumComponents; ++i) {
2191 const OffsetOfComponent &OC = CompPtr[i];
2192 if (OC.isBrackets) {
2193 // Offset of an array sub-field. TODO: Should we allow vector elements?
2194 const ArrayType *AT = Res->getType()->getAsArrayType();
2195 if (!AT) {
2196 delete Res;
2197 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2198 Res->getType().getAsString());
2199 }
2200
Chris Lattner2af6a802007-08-30 17:59:59 +00002201 // FIXME: C++: Verify that operator[] isn't overloaded.
2202
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002203 // C99 6.5.2.1p1
2204 Expr *Idx = static_cast<Expr*>(OC.U.E);
2205 if (!Idx->getType()->isIntegerType())
2206 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2207 Idx->getSourceRange());
2208
2209 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2210 continue;
2211 }
2212
2213 const RecordType *RC = Res->getType()->getAsRecordType();
2214 if (!RC) {
2215 delete Res;
2216 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2217 Res->getType().getAsString());
2218 }
2219
2220 // Get the decl corresponding to this.
2221 RecordDecl *RD = RC->getDecl();
2222 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2223 if (!MemberDecl)
2224 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2225 OC.U.IdentInfo->getName(),
2226 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002227
2228 // FIXME: C++: Verify that MemberDecl isn't a static field.
2229 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002230 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2231 // matter here.
2232 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002233 }
2234
2235 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2236 BuiltinLoc);
2237}
2238
2239
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002240Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002241 TypeTy *arg1, TypeTy *arg2,
2242 SourceLocation RPLoc) {
2243 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2244 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2245
2246 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2247
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002248 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002249}
2250
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002251Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002252 ExprTy *expr1, ExprTy *expr2,
2253 SourceLocation RPLoc) {
2254 Expr *CondExpr = static_cast<Expr*>(cond);
2255 Expr *LHSExpr = static_cast<Expr*>(expr1);
2256 Expr *RHSExpr = static_cast<Expr*>(expr2);
2257
2258 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2259
2260 // The conditional expression is required to be a constant expression.
2261 llvm::APSInt condEval(32);
2262 SourceLocation ExpLoc;
2263 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2264 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2265 CondExpr->getSourceRange());
2266
2267 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2268 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2269 RHSExpr->getType();
2270 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2271}
2272
Nate Begemanbd881ef2008-01-30 20:50:20 +00002273/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002274/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002275/// The number of arguments has already been validated to match the number of
2276/// arguments in FnType.
2277static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002278 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002279 for (unsigned i = 0; i != NumParams; ++i) {
2280 QualType ExprTy = Args[i]->getType().getCanonicalType();
2281 QualType ParmTy = FnType->getArgType(i).getCanonicalType();
2282
2283 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002284 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002285 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002286 return true;
2287}
2288
2289Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2290 SourceLocation *CommaLocs,
2291 SourceLocation BuiltinLoc,
2292 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002293 // __builtin_overload requires at least 2 arguments
2294 if (NumArgs < 2)
2295 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2296 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002297
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002298 // The first argument is required to be a constant expression. It tells us
2299 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002300 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002301 Expr *NParamsExpr = Args[0];
2302 llvm::APSInt constEval(32);
2303 SourceLocation ExpLoc;
2304 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2305 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2306 NParamsExpr->getSourceRange());
2307
2308 // Verify that the number of parameters is > 0
2309 unsigned NumParams = constEval.getZExtValue();
2310 if (NumParams == 0)
2311 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2312 NParamsExpr->getSourceRange());
2313 // Verify that we have at least 1 + NumParams arguments to the builtin.
2314 if ((NumParams + 1) > NumArgs)
2315 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2316 SourceRange(BuiltinLoc, RParenLoc));
2317
2318 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002319 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002320 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002321 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2322 // UsualUnaryConversions will convert the function DeclRefExpr into a
2323 // pointer to function.
2324 Expr *Fn = UsualUnaryConversions(Args[i]);
2325 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002326 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2327 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2328 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2329 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002330
2331 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2332 // parameters, and the number of parameters must match the value passed to
2333 // the builtin.
2334 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002335 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2336 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002337
2338 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002339 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002340 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002341 if (ExprsMatchFnType(Args+1, FnType)) {
2342 if (OE)
2343 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2344 OE->getFn()->getSourceRange());
2345 // Remember our match, and continue processing the remaining arguments
2346 // to catch any errors.
2347 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2348 BuiltinLoc, RParenLoc);
2349 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002350 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002351 // Return the newly created OverloadExpr node, if we succeded in matching
2352 // exactly one of the candidate functions.
2353 if (OE)
2354 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002355
2356 // If we didn't find a matching function Expr in the __builtin_overload list
2357 // the return an error.
2358 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002359 for (unsigned i = 0; i != NumParams; ++i) {
2360 if (i != 0) typeNames += ", ";
2361 typeNames += Args[i+1]->getType().getAsString();
2362 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002363
2364 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2365 SourceRange(BuiltinLoc, RParenLoc));
2366}
2367
Anders Carlsson36760332007-10-15 20:28:48 +00002368Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2369 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002370 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002371 Expr *E = static_cast<Expr*>(expr);
2372 QualType T = QualType::getFromOpaquePtr(type);
2373
2374 InitBuiltinVaListType();
2375
Chris Lattner005ed752008-01-04 18:04:52 +00002376 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2377 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002378 return Diag(E->getLocStart(),
2379 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2380 E->getType().getAsString(),
2381 E->getSourceRange());
2382
2383 // FIXME: Warn if a non-POD type is passed in.
2384
2385 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2386}
2387
Chris Lattner005ed752008-01-04 18:04:52 +00002388bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2389 SourceLocation Loc,
2390 QualType DstType, QualType SrcType,
2391 Expr *SrcExpr, const char *Flavor) {
2392 // Decode the result (notice that AST's are still created for extensions).
2393 bool isInvalid = false;
2394 unsigned DiagKind;
2395 switch (ConvTy) {
2396 default: assert(0 && "Unknown conversion type");
2397 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002398 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002399 DiagKind = diag::ext_typecheck_convert_pointer_int;
2400 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002401 case IntToPointer:
2402 DiagKind = diag::ext_typecheck_convert_int_pointer;
2403 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002404 case IncompatiblePointer:
2405 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2406 break;
2407 case FunctionVoidPointer:
2408 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2409 break;
2410 case CompatiblePointerDiscardsQualifiers:
2411 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2412 break;
2413 case Incompatible:
2414 DiagKind = diag::err_typecheck_convert_incompatible;
2415 isInvalid = true;
2416 break;
2417 }
2418
2419 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2420 SrcExpr->getSourceRange());
2421 return isInvalid;
2422}
2423
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002424
2425