blob: 897432578bc176e4c79b4ecea34a483c624fa0b5 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000015#include "SemaUtil.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/Expr.h"
Steve Naroff563477d2007-09-18 23:55:05 +000018#include "clang/Parse/DeclSpec.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Chris Lattner925e60d2007-12-28 05:29:59 +000023#include "llvm/ADT/OwningPtr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
Steve Narofff69936d2007-09-16 03:34:24 +000028/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +000029/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +000035Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +000036 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
45
46 // FIXME: handle wchar_t
Anders Carlssonee98ac52007-10-15 02:50:23 +000047 QualType t;
48
49 if (Literal.Pascal)
50 t = Context.getPointerType(Context.UnsignedCharTy);
51 else
52 t = Context.getPointerType(Context.CharTy);
53
54 if (Literal.Pascal && Literal.GetStringLength() > 256)
55 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
56 SourceRange(StringToks[0].getLocation(),
57 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +000058
59 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
60 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlssonee98ac52007-10-15 02:50:23 +000061 Literal.AnyWide, t,
62 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +000063 StringToks[NumStringToks-1].getLocation());
64}
65
66
Steve Naroff08d92e42007-09-15 18:49:24 +000067/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +000068/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
69/// identifier is used in an function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +000070Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +000071 IdentifierInfo &II,
72 bool HasTrailingLParen) {
73 // Could be enum-constant or decl.
Steve Naroff8c9f13e2007-09-16 16:16:00 +000074 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Reid Spencer5f016e22007-07-11 17:01:13 +000075 if (D == 0) {
76 // Otherwise, this could be an implicitly declared function reference (legal
77 // in C90, extension in C99).
78 if (HasTrailingLParen &&
79 // Not in C++.
80 !getLangOptions().CPlusPlus)
81 D = ImplicitlyDefineFunction(Loc, II, S);
82 else {
Steve Naroff7779db42007-11-12 14:29:37 +000083 if (CurMethodDecl) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +000084 ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
85 ObjCInterfaceDecl *clsDeclared;
86 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
Steve Naroff7e3411b2007-11-15 02:58:25 +000087 IdentifierInfo &II = Context.Idents.get("self");
88 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
89 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
90 static_cast<Expr*>(SelfExpr.Val), true, true);
91 }
Steve Naroff7779db42007-11-12 14:29:37 +000092 }
Reid Spencer5f016e22007-07-11 17:01:13 +000093 // If this name wasn't predeclared and if this is not a function call,
94 // diagnose the problem.
95 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
96 }
97 }
Steve Naroffe1223f72007-08-28 03:03:08 +000098 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroff53a32342007-08-28 18:45:29 +000099 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +0000100 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +0000101 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +0000103 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 if (isa<TypedefDecl>(D))
105 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000106 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000107 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000108
109 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +0000110 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +0000111}
112
Steve Narofff69936d2007-09-16 03:34:24 +0000113Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000114 tok::TokenKind Kind) {
115 PreDefinedExpr::IdentType IT;
116
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 switch (Kind) {
118 default:
119 assert(0 && "Unknown simple primary expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
Anders Carlsson22742662007-07-21 05:21:51 +0000121 IT = PreDefinedExpr::Func;
122 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000124 IT = PreDefinedExpr::Function;
125 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000127 IT = PreDefinedExpr::PrettyFunction;
128 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 }
Anders Carlsson22742662007-07-21 05:21:51 +0000130
131 // Pre-defined identifiers are always of type char *.
132 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000133}
134
Steve Narofff69936d2007-09-16 03:34:24 +0000135Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 llvm::SmallString<16> CharBuffer;
137 CharBuffer.resize(Tok.getLength());
138 const char *ThisTokBegin = &CharBuffer[0];
139 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
140
141 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
142 Tok.getLocation(), PP);
143 if (Literal.hadError())
144 return ExprResult(true);
145 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
146 Tok.getLocation());
147}
148
Steve Narofff69936d2007-09-16 03:34:24 +0000149Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 // fast path for a single digit (which is quite common). A single digit
151 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
152 if (Tok.getLength() == 1) {
153 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
154
Chris Lattner701e5eb2007-09-04 02:45:27 +0000155 unsigned IntSize = static_cast<unsigned>(
156 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
158 Context.IntTy,
159 Tok.getLocation()));
160 }
161 llvm::SmallString<512> IntegerBuffer;
162 IntegerBuffer.resize(Tok.getLength());
163 const char *ThisTokBegin = &IntegerBuffer[0];
164
165 // Get the spelling of the token, which eliminates trigraphs, etc.
166 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
167 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
168 Tok.getLocation(), PP);
169 if (Literal.hadError)
170 return ExprResult(true);
171
Chris Lattner5d661452007-08-26 03:42:43 +0000172 Expr *Res;
173
174 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000175 QualType Ty;
176 const llvm::fltSemantics *Format;
177 uint64_t Size; unsigned Align;
178
179 if (Literal.isFloat) {
180 Ty = Context.FloatTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000181 Context.Target.getFloatInfo(Size, Align, Format,
182 Context.getFullLoc(Tok.getLocation()));
183
Chris Lattner525a0502007-09-22 18:29:59 +0000184 } else if (Literal.isLong) {
185 Ty = Context.LongDoubleTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000186 Context.Target.getLongDoubleInfo(Size, Align, Format,
187 Context.getFullLoc(Tok.getLocation()));
Chris Lattner525a0502007-09-22 18:29:59 +0000188 } else {
189 Ty = Context.DoubleTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000190 Context.Target.getDoubleInfo(Size, Align, Format,
191 Context.getFullLoc(Tok.getLocation()));
Chris Lattner525a0502007-09-22 18:29:59 +0000192 }
193
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000194 // isExact will be set by GetFloatValue().
195 bool isExact = false;
196
197 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
198 Ty, Tok.getLocation());
199
Chris Lattner5d661452007-08-26 03:42:43 +0000200 } else if (!Literal.isIntegerLiteral()) {
201 return ExprResult(true);
202 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000203 QualType t;
204
Neil Boothb9449512007-08-29 22:00:19 +0000205 // long long is a C99 feature.
206 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000207 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000208 Diag(Tok.getLocation(), diag::ext_longlong);
209
Reid Spencer5f016e22007-07-11 17:01:13 +0000210 // Get the value in the widest-possible width.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000211 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
212 Context.getFullLoc(Tok.getLocation())), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000213
214 if (Literal.GetIntegerValue(ResultVal)) {
215 // If this value didn't fit into uintmax_t, warn and force to ull.
216 Diag(Tok.getLocation(), diag::warn_integer_too_large);
217 t = Context.UnsignedLongLongTy;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000218 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000219 ResultVal.getBitWidth() && "long long is not intmax_t?");
220 } else {
221 // If this value fits into a ULL, try to figure out what else it fits into
222 // according to the rules of C99 6.4.4.1p5.
223
224 // Octal, Hexadecimal, and integers with a U suffix are allowed to
225 // be an unsigned int.
226 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
227
228 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner97c51562007-08-23 21:58:08 +0000229 if (!Literal.isLong && !Literal.isLongLong) {
230 // Are int/unsigned possibilities?
Chris Lattner701e5eb2007-09-04 02:45:27 +0000231 unsigned IntSize = static_cast<unsigned>(
232 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000233 // Does it fit in a unsigned int?
234 if (ResultVal.isIntN(IntSize)) {
235 // Does it fit in a signed int?
236 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
237 t = Context.IntTy;
238 else if (AllowUnsigned)
239 t = Context.UnsignedIntTy;
240 }
241
242 if (!t.isNull())
243 ResultVal.trunc(IntSize);
244 }
245
246 // Are long/unsigned long possibilities?
247 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000248 unsigned LongSize = static_cast<unsigned>(
249 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000250
251 // Does it fit in a unsigned long?
252 if (ResultVal.isIntN(LongSize)) {
253 // Does it fit in a signed long?
254 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
255 t = Context.LongTy;
256 else if (AllowUnsigned)
257 t = Context.UnsignedLongTy;
258 }
259 if (!t.isNull())
260 ResultVal.trunc(LongSize);
261 }
262
263 // Finally, check long long if needed.
264 if (t.isNull()) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000265 unsigned LongLongSize = static_cast<unsigned>(
266 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000267
268 // Does it fit in a unsigned long long?
269 if (ResultVal.isIntN(LongLongSize)) {
270 // Does it fit in a signed long long?
271 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
272 t = Context.LongLongTy;
273 else if (AllowUnsigned)
274 t = Context.UnsignedLongLongTy;
275 }
276 }
277
278 // If we still couldn't decide a type, we probably have something that
279 // does not fit in a signed long long, but has no U suffix.
280 if (t.isNull()) {
281 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
282 t = Context.UnsignedLongLongTy;
283 }
284 }
285
Chris Lattner5d661452007-08-26 03:42:43 +0000286 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 }
Chris Lattner5d661452007-08-26 03:42:43 +0000288
289 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
290 if (Literal.isImaginary)
291 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
292
293 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000294}
295
Steve Narofff69936d2007-09-16 03:34:24 +0000296Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 ExprTy *Val) {
298 Expr *e = (Expr *)Val;
Steve Narofff69936d2007-09-16 03:34:24 +0000299 assert((e != 0) && "ActOnParenExpr() missing expr");
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 return new ParenExpr(L, R, e);
301}
302
303/// The UsualUnaryConversions() function is *not* called by this routine.
304/// See C99 6.3.2.1p[2-4] for more details.
305QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
306 SourceLocation OpLoc, bool isSizeof) {
307 // C99 6.5.3.4p1:
308 if (isa<FunctionType>(exprType) && isSizeof)
309 // alignof(function) is allowed.
310 Diag(OpLoc, diag::ext_sizeof_function_type);
311 else if (exprType->isVoidType())
312 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
313 else if (exprType->isIncompleteType()) {
314 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
315 diag::err_alignof_incomplete_type,
316 exprType.getAsString());
317 return QualType(); // error
318 }
319 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
320 return Context.getSizeType();
321}
322
323Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000324ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 SourceLocation LPLoc, TypeTy *Ty,
326 SourceLocation RPLoc) {
327 // If error parsing type, ignore.
328 if (Ty == 0) return true;
329
330 // Verify that this is a valid expression.
331 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
332
333 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
334
335 if (resultType.isNull())
336 return true;
337 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
338}
339
Chris Lattner5d794252007-08-24 21:41:10 +0000340QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000341 DefaultFunctionArrayConversion(V);
342
Chris Lattnercc26ed72007-08-26 05:39:26 +0000343 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000344 if (const ComplexType *CT = V->getType()->getAsComplexType())
345 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000346
347 // Otherwise they pass through real integer and floating point types here.
348 if (V->getType()->isArithmeticType())
349 return V->getType();
350
351 // Reject anything else.
352 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
353 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000354}
355
356
Reid Spencer5f016e22007-07-11 17:01:13 +0000357
Steve Narofff69936d2007-09-16 03:34:24 +0000358Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 tok::TokenKind Kind,
360 ExprTy *Input) {
361 UnaryOperator::Opcode Opc;
362 switch (Kind) {
363 default: assert(0 && "Unknown unary op!");
364 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
365 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
366 }
367 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
368 if (result.isNull())
369 return true;
370 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
371}
372
373Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000374ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000376 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000377
378 // Perform default conversions.
379 DefaultFunctionArrayConversion(LHSExp);
380 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000381
Chris Lattner12d9ff62007-07-16 00:14:47 +0000382 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000383
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000385 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 // in the subscript position. As a result, we need to derive the array base
387 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000388 Expr *BaseExpr, *IndexExpr;
389 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000390 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000391 BaseExpr = LHSExp;
392 IndexExpr = RHSExp;
393 // FIXME: need to deal with const...
394 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000395 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000396 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000397 BaseExpr = RHSExp;
398 IndexExpr = LHSExp;
399 // FIXME: need to deal with const...
400 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000401 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
402 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000403 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000404
405 // Component access limited to variables (reject vec4.rg[1]).
406 if (!isa<DeclRefExpr>(BaseExpr))
407 return Diag(LLoc, diag::err_ocuvector_component_access,
408 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000409 // FIXME: need to deal with const...
410 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000412 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
413 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 }
415 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000416 if (!IndexExpr->getType()->isIntegerType())
417 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
418 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000419
Chris Lattner12d9ff62007-07-16 00:14:47 +0000420 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
421 // the following check catches trying to index a pointer to a function (e.g.
422 // void (*)(int)). Functions are not objects in C99.
423 if (!ResultType->isObjectType())
424 return Diag(BaseExpr->getLocStart(),
425 diag::err_typecheck_subscript_not_object,
426 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
427
428 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000429}
430
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000431QualType Sema::
432CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
433 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnerc8629632007-07-31 19:29:30 +0000434 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000435
436 // The vector accessor can't exceed the number of elements.
437 const char *compStr = CompName.getName();
438 if (strlen(compStr) > vecType->getNumElements()) {
439 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
440 baseType.getAsString(), SourceRange(CompLoc));
441 return QualType();
442 }
443 // The component names must come from the same set.
Chris Lattner88dca042007-08-02 22:33:49 +0000444 if (vecType->getPointAccessorIdx(*compStr) != -1) {
445 do
446 compStr++;
447 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
448 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
449 do
450 compStr++;
451 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
452 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
453 do
454 compStr++;
455 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
456 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000457
458 if (*compStr) {
459 // We didn't get to the end of the string. This means the component names
460 // didn't come from the same set *or* we encountered an illegal name.
461 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
462 std::string(compStr,compStr+1), SourceRange(CompLoc));
463 return QualType();
464 }
465 // Each component accessor can't exceed the vector type.
466 compStr = CompName.getName();
467 while (*compStr) {
468 if (vecType->isAccessorWithinNumElements(*compStr))
469 compStr++;
470 else
471 break;
472 }
473 if (*compStr) {
474 // We didn't get to the end of the string. This means a component accessor
475 // exceeds the number of elements in the vector.
476 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
477 baseType.getAsString(), SourceRange(CompLoc));
478 return QualType();
479 }
480 // The component accessor looks fine - now we need to compute the actual type.
481 // The vector type is implied by the component accessor. For example,
482 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
483 unsigned CompSize = strlen(CompName.getName());
484 if (CompSize == 1)
485 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000486
487 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
488 // Now look up the TypeDefDecl from the vector type. Without this,
489 // diagostics look bad. We want OCU vector types to appear built-in.
490 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
491 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
492 return Context.getTypedefType(OCUVectorDecls[i]);
493 }
494 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000495}
496
Reid Spencer5f016e22007-07-11 17:01:13 +0000497Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000498ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 tok::TokenKind OpKind, SourceLocation MemberLoc,
500 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000501 Expr *BaseExpr = static_cast<Expr *>(Base);
502 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000503
504 // Perform default conversions.
505 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000506
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000507 QualType BaseType = BaseExpr->getType();
508 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000509
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000511 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000512 BaseType = PT->getPointeeType();
513 else
514 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
515 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000516 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000517 // The base type is either a record or an OCUVectorType.
Chris Lattnerc8629632007-07-31 19:29:30 +0000518 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000519 RecordDecl *RDecl = RTy->getDecl();
520 if (RTy->isIncompleteType())
521 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
522 BaseExpr->getSourceRange());
523 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000524 FieldDecl *MemberDecl = RDecl->getMember(&Member);
525 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000526 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
527 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000528 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
529 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff608e0ee2007-08-03 22:40:33 +0000530 // Component access limited to variables (reject vec4.rg.g).
531 if (!isa<DeclRefExpr>(BaseExpr))
532 return Diag(OpLoc, diag::err_ocuvector_component_access,
533 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000534 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
535 if (ret.isNull())
536 return true;
Chris Lattner6481a572007-08-03 17:31:20 +0000537 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000538 } else if (BaseType->isObjCInterfaceType()) {
539 ObjCInterfaceDecl *IFace;
540 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
541 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000542 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000543 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
544 ObjCInterfaceDecl *clsDeclared;
545 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000546 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
547 OpKind==tok::arrow);
548 }
549 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
550 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000551}
552
Steve Narofff69936d2007-09-16 03:34:24 +0000553/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000554/// This provides the location of the left/right parens and a list of comma
555/// locations.
556Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000557ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +0000558 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000560 Expr *Fn = static_cast<Expr *>(fn);
561 Expr **Args = reinterpret_cast<Expr**>(args);
562 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000563
Chris Lattner925e60d2007-12-28 05:29:59 +0000564 // Make the call expr early, before semantic checks. This guarantees cleanup
565 // of arguments and function on error.
566 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
567 Context.BoolTy, RParenLoc));
568
569 // Promote the function operand.
570 TheCall->setCallee(UsualUnaryConversions(Fn));
571
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
573 // type pointer to function".
Chris Lattner925e60d2007-12-28 05:29:59 +0000574 const PointerType *PT = Fn->getType()->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000576 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
577 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner925e60d2007-12-28 05:29:59 +0000578 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
579 if (FuncT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000580 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
581 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner925e60d2007-12-28 05:29:59 +0000582
583 // We know the result type of the call, set it.
584 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000585
Chris Lattner925e60d2007-12-28 05:29:59 +0000586 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
588 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +0000589 unsigned NumArgsInProto = Proto->getNumArgs();
590 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000591
Chris Lattner925e60d2007-12-28 05:29:59 +0000592 // If too few arguments are available, don't make the call.
593 if (NumArgs < NumArgsInProto)
594 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
595 Fn->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000596
Chris Lattner925e60d2007-12-28 05:29:59 +0000597 // If too many are passed and not variadic, error on the extras and drop
598 // them.
599 if (NumArgs > NumArgsInProto) {
600 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000601 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000602 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000603 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000604 Args[NumArgs-1]->getLocEnd()));
605 // This deletes the extra arguments.
606 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +0000607 }
608 NumArgsToCheck = NumArgsInProto;
609 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000610
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +0000612 for (unsigned i = 0; i != NumArgsToCheck; i++) {
613 Expr *Arg = Args[i];
Chris Lattner5cf216b2008-01-04 18:04:52 +0000614 QualType ProtoArgType = Proto->getArgType(i);
615 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000616
Chris Lattner925e60d2007-12-28 05:29:59 +0000617 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000618 AssignConvertType ConvTy =
619 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +0000620 TheCall->setArg(i, Arg);
621
Chris Lattner5cf216b2008-01-04 18:04:52 +0000622 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
623 ArgType, Arg, "passing"))
624 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000626
627 // If this is a variadic call, handle args passed through "...".
628 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +0000629 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +0000630 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
631 Expr *Arg = Args[i];
632 DefaultArgumentPromotion(Arg);
633 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +0000634 }
Steve Naroffb291ab62007-08-28 23:30:39 +0000635 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000636 } else {
637 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
638
Steve Naroffb291ab62007-08-28 23:30:39 +0000639 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +0000640 for (unsigned i = 0; i != NumArgs; i++) {
641 Expr *Arg = Args[i];
642 DefaultArgumentPromotion(Arg);
643 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +0000644 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000646
Chris Lattner59907c42007-08-10 20:18:51 +0000647 // Do special checking on direct calls to functions.
648 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
649 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
650 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner925e60d2007-12-28 05:29:59 +0000651 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlsson71993dd2007-08-17 05:31:46 +0000652 return true;
Chris Lattner59907c42007-08-10 20:18:51 +0000653
Chris Lattner925e60d2007-12-28 05:29:59 +0000654 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +0000655}
656
657Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000658ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000659 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +0000660 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +0000661 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000662 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +0000663 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +0000664 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +0000665
Steve Naroff2fdc3742007-12-10 22:44:33 +0000666 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Naroff58d18212008-01-09 20:58:06 +0000667 bool requireConstantExprs = !CurFunctionDecl && !CurMethodDecl;
668 if (CheckInitializer(literalExpr, literalType, requireConstantExprs))
669 return true;
Anders Carlssond35c8322007-12-05 07:24:19 +0000670
Chris Lattner0fc53df2008-01-02 21:46:24 +0000671 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000672}
673
674Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000675ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000676 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +0000677 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000678
Steve Naroff08d92e42007-09-15 18:49:24 +0000679 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +0000680 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000681
Steve Naroff38374b02007-09-02 20:30:18 +0000682 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
683 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
684 return e;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000685}
686
Chris Lattnerfe23e212007-12-20 00:44:32 +0000687bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +0000688 assert(VectorTy->isVectorType() && "Not a vector type!");
689
690 if (Ty->isVectorType() || Ty->isIntegerType()) {
691 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
692 Context.getTypeSize(Ty, SourceLocation()))
693 return Diag(R.getBegin(),
694 Ty->isVectorType() ?
695 diag::err_invalid_conversion_between_vectors :
696 diag::err_invalid_conversion_between_vector_and_integer,
697 VectorTy.getAsString().c_str(),
698 Ty.getAsString().c_str(), R);
699 } else
700 return Diag(R.getBegin(),
701 diag::err_invalid_conversion_between_vector_and_scalar,
702 VectorTy.getAsString().c_str(),
703 Ty.getAsString().c_str(), R);
704
705 return false;
706}
707
Steve Naroff4aa88f82007-07-19 01:06:55 +0000708Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000709ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +0000711 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +0000712
713 Expr *castExpr = static_cast<Expr*>(Op);
714 QualType castType = QualType::getFromOpaquePtr(Ty);
715
Steve Naroff711602b2007-08-31 00:32:44 +0000716 UsualUnaryConversions(castExpr);
717
Chris Lattner75af4802007-07-18 16:00:06 +0000718 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
719 // type needs to be scalar.
Chris Lattner3da2db42007-10-29 04:26:44 +0000720 if (!castType->isVoidType()) { // Cast to void allows any expr type.
721 if (!castType->isScalarType())
722 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
723 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssona64db8f2007-11-27 05:51:55 +0000724 if (!castExpr->getType()->isScalarType())
Chris Lattner3da2db42007-10-29 04:26:44 +0000725 return Diag(castExpr->getLocStart(),
726 diag::err_typecheck_expect_scalar_operand,
727 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssona64db8f2007-11-27 05:51:55 +0000728
729 if (castExpr->getType()->isVectorType()) {
730 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
731 castExpr->getType(), castType))
732 return true;
733 } else if (castType->isVectorType()) {
734 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
735 castType, castExpr->getType()))
736 return true;
Chris Lattner3da2db42007-10-29 04:26:44 +0000737 }
Steve Naroff16beff82007-07-16 23:25:18 +0000738 }
739 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000740}
741
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000742// promoteExprToType - a helper function to ensure we create exactly one
743// ImplicitCastExpr.
744static void promoteExprToType(Expr *&expr, QualType type) {
745 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
746 impCast->setType(type);
747 else
748 expr = new ImplicitCastExpr(type, expr);
749 return;
750}
751
Chris Lattnera21ddb32007-11-26 01:40:58 +0000752/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
753/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +0000754inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000755 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000756 UsualUnaryConversions(cond);
757 UsualUnaryConversions(lex);
758 UsualUnaryConversions(rex);
759 QualType condT = cond->getType();
760 QualType lexT = lex->getType();
761 QualType rexT = rex->getType();
762
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000764 if (!condT->isScalarType()) { // C99 6.5.15p2
765 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
766 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000767 return QualType();
768 }
Chris Lattner70d67a92008-01-06 22:42:25 +0000769
770 // Now check the two expressions.
771
772 // If both operands have arithmetic type, do the usual arithmetic conversions
773 // to find a common type: C99 6.5.15p3,5.
774 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +0000775 UsualArithmeticConversions(lex, rex);
776 return lex->getType();
777 }
Chris Lattner70d67a92008-01-06 22:42:25 +0000778
779 // If both operands are the same structure or union type, the result is that
780 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000781 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +0000782 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +0000783 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +0000784 // "If both the operands have structure or union type, the result has
785 // that type." This implies that CV qualifiers are dropped.
786 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 }
Chris Lattner70d67a92008-01-06 22:42:25 +0000788
789 // C99 6.5.15p5: "If both operands have void type, the result has void type."
790 if (lexT->isVoidType() && rexT->isVoidType())
791 return lexT.getUnqualifiedType();
Steve Naroffb6d54e52008-01-08 01:11:38 +0000792
793 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
794 // the type of the other operand."
795 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
796 promoteExprToType(rex, lexT); // promote the null to a pointer.
797 return lexT;
798 }
799 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
800 promoteExprToType(lex, rexT); // promote the null to a pointer.
801 return rexT;
802 }
Chris Lattnerbd57d362008-01-06 22:50:31 +0000803 // Handle the case where both operands are pointers before we handle null
804 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000805 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
806 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
807 // get the "pointed to" types
808 QualType lhptee = LHSPT->getPointeeType();
809 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000810
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000811 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
812 if (lhptee->isVoidType() &&
813 (rhptee->isObjectType() || rhptee->isIncompleteType()))
814 return lexT;
815 if (rhptee->isVoidType() &&
816 (lhptee->isObjectType() || lhptee->isIncompleteType()))
817 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000818
Steve Naroffec0550f2007-10-15 20:41:53 +0000819 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
820 rhptee.getUnqualifiedType())) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000821 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
822 lexT.getAsString(), rexT.getAsString(),
823 lex->getSourceRange(), rex->getSourceRange());
824 return lexT; // FIXME: this is an _ext - is this return o.k?
825 }
826 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000827 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
828 // differently qualified versions of compatible types, the result type is
829 // a pointer to an appropriately qualified version of the *composite*
830 // type.
Chris Lattnerbd57d362008-01-06 22:50:31 +0000831 // FIXME: Need to return the composite type.
832 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 }
834 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000835
Chris Lattner70d67a92008-01-06 22:42:25 +0000836 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000838 lexT.getAsString(), rexT.getAsString(),
839 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000840 return QualType();
841}
842
Steve Narofff69936d2007-09-16 03:34:24 +0000843/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +0000844/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +0000845Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000846 SourceLocation ColonLoc,
847 ExprTy *Cond, ExprTy *LHS,
848 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000849 Expr *CondExpr = (Expr *) Cond;
850 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000851
852 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
853 // was the condition.
854 bool isLHSNull = LHSExpr == 0;
855 if (isLHSNull)
856 LHSExpr = CondExpr;
857
Chris Lattner26824902007-07-16 21:39:03 +0000858 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
859 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 if (result.isNull())
861 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000862 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
863 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000864}
865
Steve Naroffb291ab62007-08-28 23:30:39 +0000866/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
867/// do not have a prototype. Integer promotions are performed on each
868/// argument, and arguments that have type float are promoted to double.
Chris Lattner925e60d2007-12-28 05:29:59 +0000869void Sema::DefaultArgumentPromotion(Expr *&Expr) {
870 QualType Ty = Expr->getType();
871 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffb291ab62007-08-28 23:30:39 +0000872
Chris Lattner925e60d2007-12-28 05:29:59 +0000873 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
874 promoteExprToType(Expr, Context.IntTy);
875 if (Ty == Context.FloatTy)
876 promoteExprToType(Expr, Context.DoubleTy);
Steve Naroffb291ab62007-08-28 23:30:39 +0000877}
878
Steve Narofffa2eaab2007-07-15 02:02:06 +0000879/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000880void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000881 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000882 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000883
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000884 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000885 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
886 t = e->getType();
887 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000888 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000889 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnerc8629632007-07-31 19:29:30 +0000890 else if (const ArrayType *ary = t->getAsArrayType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000891 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000892}
893
894/// UsualUnaryConversion - Performs various conversions that are common to most
895/// operators (C99 6.3). The conversions of array and function types are
896/// sometimes surpressed. For example, the array->pointer conversion doesn't
897/// apply if the array is an argument to the sizeof or address (&) operators.
898/// In these instances, this routine should *not* be called.
Chris Lattner925e60d2007-12-28 05:29:59 +0000899Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
900 QualType Ty = Expr->getType();
901 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000902
Chris Lattner925e60d2007-12-28 05:29:59 +0000903 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
904 promoteExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
905 Ty = Expr->getType();
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000906 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000907 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
908 promoteExprToType(Expr, Context.IntTy);
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000909 else
Chris Lattner925e60d2007-12-28 05:29:59 +0000910 DefaultFunctionArrayConversion(Expr);
911
912 return Expr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000913}
914
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000915/// UsualArithmeticConversions - Performs various conversions that are common to
Reid Spencer5f016e22007-07-11 17:01:13 +0000916/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
917/// routine returns the first non-arithmetic type found. The client is
918/// responsible for emitting appropriate error diagnostics.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000919QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
920 bool isCompAssign) {
Steve Naroff8702a0f2007-08-25 19:54:59 +0000921 if (!isCompAssign) {
922 UsualUnaryConversions(lhsExpr);
923 UsualUnaryConversions(rhsExpr);
924 }
Steve Naroff3187e202007-10-18 18:55:53 +0000925 // For conversion purposes, we ignore any qualifiers.
926 // For example, "const float" and "float" are equivalent.
Steve Narofff68a63f2007-11-10 19:45:54 +0000927 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
928 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000929
930 // If both types are identical, no conversion is needed.
Steve Naroff3187e202007-10-18 18:55:53 +0000931 if (lhs == rhs)
932 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000933
934 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
935 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000936 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000937 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000938
939 // At this point, we have two different arithmetic types.
940
941 // Handle complex types first (C99 6.3.1.8p1).
942 if (lhs->isComplexType() || rhs->isComplexType()) {
943 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000944 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000945 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
946 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000947 }
948 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000949 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
950 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000951 }
Steve Narofff1448a02007-08-27 01:27:54 +0000952 // This handles complex/complex, complex/float, or float/complex.
953 // When both operands are complex, the shorter operand is converted to the
954 // type of the longer, and that is the type of the result. This corresponds
955 // to what is done when combining two real floating-point operands.
956 // The fun begins when size promotion occur across type domains.
957 // From H&S 6.3.4: When one operand is complex and the other is a real
958 // floating-point type, the less precise type is converted, within it's
959 // real or complex domain, to the precision of the other type. For example,
960 // when combining a "long double" with a "double _Complex", the
961 // "double _Complex" is promoted to "long double _Complex".
Steve Narofffb0d4962007-08-27 15:30:22 +0000962 int result = Context.compareFloatingType(lhs, rhs);
963
964 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff55fe4552007-08-27 21:32:55 +0000965 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
966 if (!isCompAssign)
967 promoteExprToType(rhsExpr, rhs);
968 } else if (result < 0) { // The right side is bigger, convert lhs.
969 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
970 if (!isCompAssign)
971 promoteExprToType(lhsExpr, lhs);
972 }
973 // At this point, lhs and rhs have the same rank/size. Now, make sure the
974 // domains match. This is a requirement for our implementation, C99
975 // does not require this promotion.
976 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
977 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff29960362007-08-27 21:43:43 +0000978 if (!isCompAssign)
979 promoteExprToType(lhsExpr, rhs);
980 return rhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000981 } else { // handle "_Complex double, double".
Steve Naroff29960362007-08-27 21:43:43 +0000982 if (!isCompAssign)
983 promoteExprToType(rhsExpr, lhs);
984 return lhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000985 }
Steve Naroffa4332e22007-07-17 00:58:39 +0000986 }
Steve Naroff29960362007-08-27 21:43:43 +0000987 return lhs; // The domain/size match exactly.
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 // Now handle "real" floating types (i.e. float, double, long double).
990 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
991 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000992 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000993 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
994 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000995 }
996 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000997 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
998 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000999 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001000 // We have two real floating types, float/complex combos were handled above.
1001 // Convert the smaller operand to the bigger result.
Steve Narofffb0d4962007-08-27 15:30:22 +00001002 int result = Context.compareFloatingType(lhs, rhs);
1003
1004 if (result > 0) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001005 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1006 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001007 }
Steve Narofffb0d4962007-08-27 15:30:22 +00001008 if (result < 0) { // convert the lhs
1009 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1010 return rhs;
1011 }
1012 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001014 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +00001015 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001016 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1017 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001018 }
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001019 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1020 return rhs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001021}
1022
1023// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1024// being closely modeled after the C99 spec:-). The odd characteristic of this
1025// routine is it effectively iqnores the qualifiers on the top level pointee.
1026// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1027// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001028Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001029Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1030 QualType lhptee, rhptee;
1031
1032 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001033 lhptee = lhsType->getAsPointerType()->getPointeeType();
1034 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001035
1036 // make sure we operate on the canonical type
1037 lhptee = lhptee.getCanonicalType();
1038 rhptee = rhptee.getCanonicalType();
1039
Chris Lattner5cf216b2008-01-04 18:04:52 +00001040 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001041
1042 // C99 6.5.16.1p1: This following citation is common to constraints
1043 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1044 // qualifiers of the type *pointed to* by the right;
1045 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1046 rhptee.getQualifiers())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001047 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001048
1049 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1050 // incomplete type and the other is a pointer to a qualified or unqualified
1051 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001052 if (lhptee->isVoidType()) {
1053 if (rhptee->isObjectType() || rhptee->isIncompleteType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001054 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001055
1056 // As an extension, we allow cast to/from void* to function pointer.
1057 if (rhptee->isFunctionType())
1058 return FunctionVoidPointer;
1059 }
1060
1061 if (rhptee->isVoidType()) {
1062 if (lhptee->isObjectType() || lhptee->isIncompleteType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001063 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001064
1065 // As an extension, we allow cast to/from void* to function pointer.
1066 if (lhptee->isFunctionType())
1067 return FunctionVoidPointer;
1068 }
1069
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1071 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001072 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1073 rhptee.getUnqualifiedType()))
1074 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001075 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001076}
1077
1078/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1079/// has code to accommodate several GCC extensions when type checking
1080/// pointers. Here are some objectionable examples that GCC considers warnings:
1081///
1082/// int a, *pint;
1083/// short *pshort;
1084/// struct foo *pfoo;
1085///
1086/// pint = pshort; // warning: assignment from incompatible pointer type
1087/// a = pint; // warning: assignment makes integer from pointer without a cast
1088/// pint = a; // warning: assignment makes pointer from integer without a cast
1089/// pint = pfoo; // warning: assignment from incompatible pointer type
1090///
1091/// As a result, the code for dealing with pointers is more complex than the
1092/// C99 spec dictates.
1093/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1094///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001095Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001096Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001097 // Get canonical types. We're not formatting these types, just comparing
1098 // them.
1099 lhsType = lhsType.getCanonicalType();
1100 rhsType = rhsType.getCanonicalType();
1101
1102 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001103 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001104
Anders Carlsson793680e2007-10-12 23:56:29 +00001105 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001106 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001107 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001108 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001109 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001110
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001111 if (lhsType->isObjCQualifiedIdType()
1112 || rhsType->isObjCQualifiedIdType()) {
1113 if (Context.ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001114 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001115 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001116 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001117
1118 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1119 // For OCUVector, allow vector splats; float -> <n x float>
1120 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1121 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1122 return Compatible;
1123 }
1124
1125 // If LHS and RHS are both vectors of integer or both vectors of floating
1126 // point types, and the total vector length is the same, allow the
1127 // conversion. This is a bitcast; no bits are changed but the result type
1128 // is different.
1129 if (getLangOptions().LaxVectorConversions &&
1130 lhsType->isVectorType() && rhsType->isVectorType()) {
1131 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1132 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
1133 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1134 Context.getTypeSize(rhsType, SourceLocation()))
Nate Begeman4119d1a2007-12-30 02:59:45 +00001135 return Compatible;
1136 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001137 }
1138 return Incompatible;
1139 }
1140
1141 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001142 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001143
1144 if (lhsType->isPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001146 return IntToPointer;
Reid Spencer5f016e22007-07-11 17:01:13 +00001147
1148 if (rhsType->isPointerType())
1149 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattnerfc144e22008-01-04 23:18:45 +00001150 return Incompatible;
1151 }
1152
1153 if (rhsType->isPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001154 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1155 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
Chris Lattnerb7b61152008-01-04 18:22:42 +00001156 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001157
1158 if (lhsType->isPointerType())
1159 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattnerfc144e22008-01-04 23:18:45 +00001160 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001161 }
1162
1163 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001164 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001165 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 }
1167 return Incompatible;
1168}
1169
Chris Lattner5cf216b2008-01-04 18:04:52 +00001170Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001171Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001172 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1173 // a null pointer constant.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001174 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001175 && rExpr->isNullPointerConstant(Context)) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001176 promoteExprToType(rExpr, lhsType);
1177 return Compatible;
1178 }
Chris Lattner943140e2007-10-16 02:55:40 +00001179 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001180 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001181 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001182 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001183 //
1184 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1185 // are better understood.
1186 if (!lhsType->isReferenceType())
1187 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001188
Chris Lattner5cf216b2008-01-04 18:04:52 +00001189 Sema::AssignConvertType result =
1190 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001191
1192 // C99 6.5.16.1p2: The value of the right operand is converted to the
1193 // type of the assignment expression.
1194 if (rExpr->getType() != lhsType)
1195 promoteExprToType(rExpr, lhsType);
1196 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001197}
1198
Chris Lattner5cf216b2008-01-04 18:04:52 +00001199Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001200Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1201 return CheckAssignmentConstraints(lhsType, rhsType);
1202}
1203
Chris Lattnerca5eede2007-12-12 05:47:28 +00001204QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 Diag(loc, diag::err_typecheck_invalid_operands,
1206 lex->getType().getAsString(), rex->getType().getAsString(),
1207 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001208 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001209}
1210
Steve Naroff49b45262007-07-13 16:58:59 +00001211inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1212 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 QualType lhsType = lex->getType(), rhsType = rex->getType();
1214
1215 // make sure the vector types are identical.
1216 if (lhsType == rhsType)
1217 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001218
1219 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1220 // promote the rhs to the vector type.
1221 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1222 if (V->getElementType().getCanonicalType().getTypePtr()
1223 == rhsType.getCanonicalType().getTypePtr()) {
1224 promoteExprToType(rex, lhsType);
1225 return lhsType;
1226 }
1227 }
1228
1229 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1230 // promote the lhs to the vector type.
1231 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1232 if (V->getElementType().getCanonicalType().getTypePtr()
1233 == lhsType.getCanonicalType().getTypePtr()) {
1234 promoteExprToType(lex, rhsType);
1235 return rhsType;
1236 }
1237 }
1238
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 // You cannot convert between vector values of different size.
1240 Diag(loc, diag::err_typecheck_vector_not_convertable,
1241 lex->getType().getAsString(), rex->getType().getAsString(),
1242 lex->getSourceRange(), rex->getSourceRange());
1243 return QualType();
1244}
1245
1246inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001247 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001248{
Steve Naroff90045e82007-07-13 23:32:42 +00001249 QualType lhsType = lex->getType(), rhsType = rex->getType();
1250
1251 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001253
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001254 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001255
Steve Naroffa4332e22007-07-17 00:58:39 +00001256 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001257 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001258 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001259}
1260
1261inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001262 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001263{
Steve Naroff90045e82007-07-13 23:32:42 +00001264 QualType lhsType = lex->getType(), rhsType = rex->getType();
1265
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001266 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001267
Steve Naroffa4332e22007-07-17 00:58:39 +00001268 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001269 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001270 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001271}
1272
1273inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001274 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001275{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001276 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001277 return CheckVectorOperands(loc, lex, rex);
1278
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001279 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Steve Naroff3e5e5562007-07-16 22:23:01 +00001280
Reid Spencer5f016e22007-07-11 17:01:13 +00001281 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001282 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001283 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001284
Steve Naroffa4332e22007-07-17 00:58:39 +00001285 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1286 return lex->getType();
1287 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1288 return rex->getType();
Chris Lattnerca5eede2007-12-12 05:47:28 +00001289 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001290}
1291
1292inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001293 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001294{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001295 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001297
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001298 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001299
Chris Lattner6e4ab612007-12-09 21:53:25 +00001300 // Enforce type constraints: C99 6.5.6p3.
1301
1302 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001303 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001304 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001305
1306 // Either ptr - int or ptr - ptr.
1307 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1308 // The LHS must be an object type, not incomplete, function, etc.
1309 if (!LHSPTy->getPointeeType()->isObjectType()) {
1310 // Handle the GNU void* extension.
1311 if (LHSPTy->getPointeeType()->isVoidType()) {
1312 Diag(loc, diag::ext_gnu_void_ptr,
1313 lex->getSourceRange(), rex->getSourceRange());
1314 } else {
1315 Diag(loc, diag::err_typecheck_sub_ptr_object,
1316 lex->getType().getAsString(), lex->getSourceRange());
1317 return QualType();
1318 }
1319 }
1320
1321 // The result type of a pointer-int computation is the pointer type.
1322 if (rex->getType()->isIntegerType())
1323 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001324
Chris Lattner6e4ab612007-12-09 21:53:25 +00001325 // Handle pointer-pointer subtractions.
1326 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1327 // RHS must be an object type, unless void (GNU).
1328 if (!RHSPTy->getPointeeType()->isObjectType()) {
1329 // Handle the GNU void* extension.
1330 if (RHSPTy->getPointeeType()->isVoidType()) {
1331 if (!LHSPTy->getPointeeType()->isVoidType())
1332 Diag(loc, diag::ext_gnu_void_ptr,
1333 lex->getSourceRange(), rex->getSourceRange());
1334 } else {
1335 Diag(loc, diag::err_typecheck_sub_ptr_object,
1336 rex->getType().getAsString(), rex->getSourceRange());
1337 return QualType();
1338 }
1339 }
1340
1341 // Pointee types must be compatible.
1342 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1343 RHSPTy->getPointeeType())) {
1344 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1345 lex->getType().getAsString(), rex->getType().getAsString(),
1346 lex->getSourceRange(), rex->getSourceRange());
1347 return QualType();
1348 }
1349
1350 return Context.getPointerDiffType();
1351 }
1352 }
1353
Chris Lattnerca5eede2007-12-12 05:47:28 +00001354 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001355}
1356
1357inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattnerca5eede2007-12-12 05:47:28 +00001358 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1359 // C99 6.5.7p2: Each of the operands shall have integer type.
1360 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1361 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001362
Chris Lattnerca5eede2007-12-12 05:47:28 +00001363 // Shifts don't perform usual arithmetic conversions, they just do integer
1364 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001365 if (!isCompAssign)
1366 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001367 UsualUnaryConversions(rex);
1368
1369 // "The type of the result is that of the promoted left operand."
1370 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001371}
1372
Chris Lattnera5937dd2007-08-26 01:18:55 +00001373inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1374 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Reid Spencer5f016e22007-07-11 17:01:13 +00001375{
Chris Lattnera5937dd2007-08-26 01:18:55 +00001376 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001377 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1378 UsualArithmeticConversions(lex, rex);
1379 else {
1380 UsualUnaryConversions(lex);
1381 UsualUnaryConversions(rex);
1382 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001383 QualType lType = lex->getType();
1384 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001385
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001386 // For non-floating point types, check for self-comparisons of the form
1387 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1388 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001389 if (!lType->isFloatingType()) {
1390 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1391 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1392 if (DRL->getDecl() == DRR->getDecl())
1393 Diag(loc, diag::warn_selfcomparison);
1394 }
1395
Chris Lattnera5937dd2007-08-26 01:18:55 +00001396 if (isRelational) {
1397 if (lType->isRealType() && rType->isRealType())
1398 return Context.IntTy;
1399 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001400 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001401 if (lType->isFloatingType()) {
1402 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001403 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001404 }
1405
Chris Lattnera5937dd2007-08-26 01:18:55 +00001406 if (lType->isArithmeticType() && rType->isArithmeticType())
1407 return Context.IntTy;
1408 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001409
Chris Lattnerd28f8152007-08-26 01:10:14 +00001410 bool LHSIsNull = lex->isNullPointerConstant(Context);
1411 bool RHSIsNull = rex->isNullPointerConstant(Context);
1412
Chris Lattnera5937dd2007-08-26 01:18:55 +00001413 // All of the following pointer related warnings are GCC extensions, except
1414 // when handling null pointer constants. One day, we can consider making them
1415 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001416 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff66296cb2007-11-13 14:57:38 +00001417
1418 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1419 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1420 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroffec0550f2007-10-15 20:41:53 +00001421 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1422 rType.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001423 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1424 lType.getAsString(), rType.getAsString(),
1425 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 }
Chris Lattnerd28f8152007-08-26 01:10:14 +00001427 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001428 return Context.IntTy;
1429 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001430 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
1431 && Context.ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Fariborz Jahanian7359f042007-12-20 01:06:58 +00001432 promoteExprToType(rex, lType);
1433 return Context.IntTy;
1434 }
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001435 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001436 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001437 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1438 lType.getAsString(), rType.getAsString(),
1439 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001440 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001441 return Context.IntTy;
1442 }
1443 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001444 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001445 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1446 lType.getAsString(), rType.getAsString(),
1447 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001448 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001449 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00001451 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001452}
1453
Reid Spencer5f016e22007-07-11 17:01:13 +00001454inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001455 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001456{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001457 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001459
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001460 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001461
Steve Naroffa4332e22007-07-17 00:58:39 +00001462 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001463 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001464 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001465}
1466
1467inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001468 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001469{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001470 UsualUnaryConversions(lex);
1471 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001472
Steve Naroffa4332e22007-07-17 00:58:39 +00001473 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001474 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001475 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001476}
1477
1478inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001479 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001480{
1481 QualType lhsType = lex->getType();
1482 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1484
1485 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00001486 case Expr::MLV_Valid:
1487 break;
1488 case Expr::MLV_ConstQualified:
1489 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1490 return QualType();
1491 case Expr::MLV_ArrayType:
1492 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1493 lhsType.getAsString(), lex->getSourceRange());
1494 return QualType();
1495 case Expr::MLV_NotObjectType:
1496 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1497 lhsType.getAsString(), lex->getSourceRange());
1498 return QualType();
1499 case Expr::MLV_InvalidExpression:
1500 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1501 lex->getSourceRange());
1502 return QualType();
1503 case Expr::MLV_IncompleteType:
1504 case Expr::MLV_IncompleteVoidType:
1505 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1506 lhsType.getAsString(), lex->getSourceRange());
1507 return QualType();
1508 case Expr::MLV_DuplicateVectorComponents:
1509 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1510 lex->getSourceRange());
1511 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00001513
Chris Lattner5cf216b2008-01-04 18:04:52 +00001514 AssignConvertType ConvTy;
1515 if (compoundType.isNull())
1516 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1517 else
1518 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1519
1520 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1521 rex, "assigning"))
1522 return QualType();
1523
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 // C99 6.5.16p3: The type of an assignment expression is the type of the
1525 // left operand unless the left operand has qualified type, in which case
1526 // it is the unqualified version of the type of the left operand.
1527 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1528 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001529 // C++ 5.17p1: the type of the assignment expression is that of its left
1530 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001531 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001532}
1533
1534inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001535 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001536 UsualUnaryConversions(rex);
1537 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001538}
1539
Steve Naroff49b45262007-07-13 16:58:59 +00001540/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1541/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001542QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001543 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 assert(!resType.isNull() && "no type for increment/decrement expression");
1545
Steve Naroff084f9ed2007-08-24 17:20:07 +00001546 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00001547 if (const PointerType *pt = resType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1549 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1550 resType.getAsString(), op->getSourceRange());
1551 return QualType();
1552 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001553 } else if (!resType->isRealType()) {
1554 if (resType->isComplexType())
1555 // C99 does not support ++/-- on complex types.
1556 Diag(OpLoc, diag::ext_integer_increment_complex,
1557 resType.getAsString(), op->getSourceRange());
1558 else {
1559 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1560 resType.getAsString(), op->getSourceRange());
1561 return QualType();
1562 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001564 // At this point, we know we have a real, complex or pointer type.
1565 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1567 if (mlval != Expr::MLV_Valid) {
1568 // FIXME: emit a more precise diagnostic...
1569 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1570 op->getSourceRange());
1571 return QualType();
1572 }
1573 return resType;
1574}
1575
1576/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1577/// This routine allows us to typecheck complex/recursive expressions
1578/// where the declaration is needed for type checking. Here are some
1579/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1580static Decl *getPrimaryDeclaration(Expr *e) {
1581 switch (e->getStmtClass()) {
1582 case Stmt::DeclRefExprClass:
1583 return cast<DeclRefExpr>(e)->getDecl();
1584 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001585 // Fields cannot be declared with a 'register' storage class.
1586 // &X->f is always ok, even if X is declared register.
1587 if (cast<MemberExpr>(e)->isArrow())
1588 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1590 case Stmt::ArraySubscriptExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001591 // &X[4] and &4[X] is invalid if X is invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 case Stmt::UnaryOperatorClass:
1594 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1595 case Stmt::ParenExprClass:
1596 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00001597 case Stmt::ImplicitCastExprClass:
1598 // &X[4] when X is an array, has an implicit cast from array to pointer.
1599 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 default:
1601 return 0;
1602 }
1603}
1604
1605/// CheckAddressOfOperand - The operand of & must be either a function
1606/// designator or an lvalue designating an object. If it is an lvalue, the
1607/// object cannot be declared with storage class register or be a bit field.
1608/// Note: The usual conversions are *not* applied to the operand of the &
1609/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1610QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1611 Decl *dcl = getPrimaryDeclaration(op);
1612 Expr::isLvalueResult lval = op->isLvalue();
1613
1614 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00001615 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1616 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1618 op->getSourceRange());
1619 return QualType();
1620 }
1621 } else if (dcl) {
1622 // We have an lvalue with a decl. Make sure the decl is not declared
1623 // with the register storage-class specifier.
1624 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1625 if (vd->getStorageClass() == VarDecl::Register) {
1626 Diag(OpLoc, diag::err_typecheck_address_of_register,
1627 op->getSourceRange());
1628 return QualType();
1629 }
1630 } else
1631 assert(0 && "Unknown/unexpected decl type");
1632
1633 // FIXME: add check for bitfields!
1634 }
1635 // If the operand has type "type", the result has type "pointer to type".
1636 return Context.getPointerType(op->getType());
1637}
1638
1639QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001640 UsualUnaryConversions(op);
1641 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001642
Chris Lattnerbefee482007-07-31 16:53:04 +00001643 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 QualType ptype = PT->getPointeeType();
1645 // C99 6.5.3.2p4. "if it points to an object,...".
1646 if (ptype->isIncompleteType()) { // An incomplete type is not an object
Chris Lattner5d5d2102008-01-06 22:21:46 +00001647 // GCC compat: special case 'void *' (treat as extension, not error).
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 if (ptype->isVoidType()) {
Chris Lattner5d5d2102008-01-06 22:21:46 +00001649 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001650 } else {
1651 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1652 ptype.getAsString(), op->getSourceRange());
1653 return QualType();
1654 }
1655 }
1656 return ptype;
1657 }
1658 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1659 qType.getAsString(), op->getSourceRange());
1660 return QualType();
1661}
1662
1663static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1664 tok::TokenKind Kind) {
1665 BinaryOperator::Opcode Opc;
1666 switch (Kind) {
1667 default: assert(0 && "Unknown binop!");
1668 case tok::star: Opc = BinaryOperator::Mul; break;
1669 case tok::slash: Opc = BinaryOperator::Div; break;
1670 case tok::percent: Opc = BinaryOperator::Rem; break;
1671 case tok::plus: Opc = BinaryOperator::Add; break;
1672 case tok::minus: Opc = BinaryOperator::Sub; break;
1673 case tok::lessless: Opc = BinaryOperator::Shl; break;
1674 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1675 case tok::lessequal: Opc = BinaryOperator::LE; break;
1676 case tok::less: Opc = BinaryOperator::LT; break;
1677 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1678 case tok::greater: Opc = BinaryOperator::GT; break;
1679 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1680 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1681 case tok::amp: Opc = BinaryOperator::And; break;
1682 case tok::caret: Opc = BinaryOperator::Xor; break;
1683 case tok::pipe: Opc = BinaryOperator::Or; break;
1684 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1685 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1686 case tok::equal: Opc = BinaryOperator::Assign; break;
1687 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1688 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1689 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1690 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1691 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1692 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1693 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1694 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1695 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1696 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1697 case tok::comma: Opc = BinaryOperator::Comma; break;
1698 }
1699 return Opc;
1700}
1701
1702static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1703 tok::TokenKind Kind) {
1704 UnaryOperator::Opcode Opc;
1705 switch (Kind) {
1706 default: assert(0 && "Unknown unary op!");
1707 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1708 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1709 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1710 case tok::star: Opc = UnaryOperator::Deref; break;
1711 case tok::plus: Opc = UnaryOperator::Plus; break;
1712 case tok::minus: Opc = UnaryOperator::Minus; break;
1713 case tok::tilde: Opc = UnaryOperator::Not; break;
1714 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1715 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1716 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1717 case tok::kw___real: Opc = UnaryOperator::Real; break;
1718 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1719 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1720 }
1721 return Opc;
1722}
1723
1724// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001725Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 ExprTy *LHS, ExprTy *RHS) {
1727 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1728 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1729
Steve Narofff69936d2007-09-16 03:34:24 +00001730 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1731 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001732
1733 QualType ResultTy; // Result type of the binary operator.
1734 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1735
1736 switch (Opc) {
1737 default:
1738 assert(0 && "Unknown binary expr!");
1739 case BinaryOperator::Assign:
1740 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1741 break;
1742 case BinaryOperator::Mul:
1743 case BinaryOperator::Div:
1744 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1745 break;
1746 case BinaryOperator::Rem:
1747 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1748 break;
1749 case BinaryOperator::Add:
1750 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1751 break;
1752 case BinaryOperator::Sub:
1753 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1754 break;
1755 case BinaryOperator::Shl:
1756 case BinaryOperator::Shr:
1757 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1758 break;
1759 case BinaryOperator::LE:
1760 case BinaryOperator::LT:
1761 case BinaryOperator::GE:
1762 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001763 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 break;
1765 case BinaryOperator::EQ:
1766 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001767 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 break;
1769 case BinaryOperator::And:
1770 case BinaryOperator::Xor:
1771 case BinaryOperator::Or:
1772 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1773 break;
1774 case BinaryOperator::LAnd:
1775 case BinaryOperator::LOr:
1776 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1777 break;
1778 case BinaryOperator::MulAssign:
1779 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001780 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 if (!CompTy.isNull())
1782 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1783 break;
1784 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001785 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 if (!CompTy.isNull())
1787 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1788 break;
1789 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001790 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001791 if (!CompTy.isNull())
1792 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1793 break;
1794 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001795 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 if (!CompTy.isNull())
1797 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1798 break;
1799 case BinaryOperator::ShlAssign:
1800 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001801 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 if (!CompTy.isNull())
1803 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1804 break;
1805 case BinaryOperator::AndAssign:
1806 case BinaryOperator::XorAssign:
1807 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001808 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 if (!CompTy.isNull())
1810 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1811 break;
1812 case BinaryOperator::Comma:
1813 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1814 break;
1815 }
1816 if (ResultTy.isNull())
1817 return true;
1818 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001819 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001820 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001821 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001822}
1823
1824// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001825Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00001826 ExprTy *input) {
1827 Expr *Input = (Expr*)input;
1828 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1829 QualType resultType;
1830 switch (Opc) {
1831 default:
1832 assert(0 && "Unimplemented unary expr!");
1833 case UnaryOperator::PreInc:
1834 case UnaryOperator::PreDec:
1835 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1836 break;
1837 case UnaryOperator::AddrOf:
1838 resultType = CheckAddressOfOperand(Input, OpLoc);
1839 break;
1840 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00001841 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00001842 resultType = CheckIndirectionOperand(Input, OpLoc);
1843 break;
1844 case UnaryOperator::Plus:
1845 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001846 UsualUnaryConversions(Input);
1847 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001848 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1849 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1850 resultType.getAsString());
1851 break;
1852 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001853 UsualUnaryConversions(Input);
1854 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00001855 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1856 if (!resultType->isIntegerType()) {
1857 if (resultType->isComplexType())
1858 // C99 does not support '~' for complex conjugation.
1859 Diag(OpLoc, diag::ext_integer_complement_complex,
1860 resultType.getAsString());
1861 else
1862 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1863 resultType.getAsString());
1864 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001865 break;
1866 case UnaryOperator::LNot: // logical negation
1867 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001868 DefaultFunctionArrayConversion(Input);
1869 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001870 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1871 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1872 resultType.getAsString());
1873 // LNot always has type int. C99 6.5.3.3p5.
1874 resultType = Context.IntTy;
1875 break;
1876 case UnaryOperator::SizeOf:
1877 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1878 break;
1879 case UnaryOperator::AlignOf:
1880 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1881 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001882 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00001883 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00001884 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00001885 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001886 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00001887 resultType = Input->getType();
1888 break;
1889 }
1890 if (resultType.isNull())
1891 return true;
1892 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1893}
1894
Steve Naroff1b273c42007-09-16 14:56:35 +00001895/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1896Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001897 SourceLocation LabLoc,
1898 IdentifierInfo *LabelII) {
1899 // Look up the record for this label identifier.
1900 LabelStmt *&LabelDecl = LabelMap[LabelII];
1901
1902 // If we haven't seen this label yet, create a forward reference.
1903 if (LabelDecl == 0)
1904 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1905
1906 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001907 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1908 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001909}
1910
Steve Naroff1b273c42007-09-16 14:56:35 +00001911Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001912 SourceLocation RPLoc) { // "({..})"
1913 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1914 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1915 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1916
1917 // FIXME: there are a variety of strange constraints to enforce here, for
1918 // example, it is not possible to goto into a stmt expression apparently.
1919 // More semantic analysis is needed.
1920
1921 // FIXME: the last statement in the compount stmt has its value used. We
1922 // should not warn about it being unused.
1923
1924 // If there are sub stmts in the compound stmt, take the type of the last one
1925 // as the type of the stmtexpr.
1926 QualType Ty = Context.VoidTy;
1927
1928 if (!Compound->body_empty())
1929 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1930 Ty = LastExpr->getType();
1931
1932 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1933}
Steve Naroffd34e9152007-08-01 22:05:33 +00001934
Steve Naroff1b273c42007-09-16 14:56:35 +00001935Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001936 SourceLocation TypeLoc,
1937 TypeTy *argty,
1938 OffsetOfComponent *CompPtr,
1939 unsigned NumComponents,
1940 SourceLocation RPLoc) {
1941 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1942 assert(!ArgTy.isNull() && "Missing type argument!");
1943
1944 // We must have at least one component that refers to the type, and the first
1945 // one is known to be a field designator. Verify that the ArgTy represents
1946 // a struct/union/class.
1947 if (!ArgTy->isRecordType())
1948 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1949
1950 // Otherwise, create a compound literal expression as the base, and
1951 // iteratively process the offsetof designators.
Chris Lattner0fc53df2008-01-02 21:46:24 +00001952 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001953
Chris Lattner9e2b75c2007-08-31 21:49:13 +00001954 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1955 // GCC extension, diagnose them.
1956 if (NumComponents != 1)
1957 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1958 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1959
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001960 for (unsigned i = 0; i != NumComponents; ++i) {
1961 const OffsetOfComponent &OC = CompPtr[i];
1962 if (OC.isBrackets) {
1963 // Offset of an array sub-field. TODO: Should we allow vector elements?
1964 const ArrayType *AT = Res->getType()->getAsArrayType();
1965 if (!AT) {
1966 delete Res;
1967 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1968 Res->getType().getAsString());
1969 }
1970
Chris Lattner704fe352007-08-30 17:59:59 +00001971 // FIXME: C++: Verify that operator[] isn't overloaded.
1972
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001973 // C99 6.5.2.1p1
1974 Expr *Idx = static_cast<Expr*>(OC.U.E);
1975 if (!Idx->getType()->isIntegerType())
1976 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1977 Idx->getSourceRange());
1978
1979 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1980 continue;
1981 }
1982
1983 const RecordType *RC = Res->getType()->getAsRecordType();
1984 if (!RC) {
1985 delete Res;
1986 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1987 Res->getType().getAsString());
1988 }
1989
1990 // Get the decl corresponding to this.
1991 RecordDecl *RD = RC->getDecl();
1992 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1993 if (!MemberDecl)
1994 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1995 OC.U.IdentInfo->getName(),
1996 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00001997
1998 // FIXME: C++: Verify that MemberDecl isn't a static field.
1999 // FIXME: Verify that MemberDecl isn't a bitfield.
2000
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002001 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
2002 }
2003
2004 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2005 BuiltinLoc);
2006}
2007
2008
Steve Naroff1b273c42007-09-16 14:56:35 +00002009Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002010 TypeTy *arg1, TypeTy *arg2,
2011 SourceLocation RPLoc) {
2012 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2013 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2014
2015 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2016
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002017 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002018}
2019
Steve Naroff1b273c42007-09-16 14:56:35 +00002020Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002021 ExprTy *expr1, ExprTy *expr2,
2022 SourceLocation RPLoc) {
2023 Expr *CondExpr = static_cast<Expr*>(cond);
2024 Expr *LHSExpr = static_cast<Expr*>(expr1);
2025 Expr *RHSExpr = static_cast<Expr*>(expr2);
2026
2027 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2028
2029 // The conditional expression is required to be a constant expression.
2030 llvm::APSInt condEval(32);
2031 SourceLocation ExpLoc;
2032 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2033 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2034 CondExpr->getSourceRange());
2035
2036 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2037 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2038 RHSExpr->getType();
2039 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2040}
2041
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002042Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2043 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00002044 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002045 Expr *E = static_cast<Expr*>(expr);
2046 QualType T = QualType::getFromOpaquePtr(type);
2047
2048 InitBuiltinVaListType();
2049
Chris Lattner5cf216b2008-01-04 18:04:52 +00002050 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2051 != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002052 return Diag(E->getLocStart(),
2053 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2054 E->getType().getAsString(),
2055 E->getSourceRange());
2056
2057 // FIXME: Warn if a non-POD type is passed in.
2058
2059 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2060}
2061
Chris Lattner5cf216b2008-01-04 18:04:52 +00002062bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2063 SourceLocation Loc,
2064 QualType DstType, QualType SrcType,
2065 Expr *SrcExpr, const char *Flavor) {
2066 // Decode the result (notice that AST's are still created for extensions).
2067 bool isInvalid = false;
2068 unsigned DiagKind;
2069 switch (ConvTy) {
2070 default: assert(0 && "Unknown conversion type");
2071 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00002072 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00002073 DiagKind = diag::ext_typecheck_convert_pointer_int;
2074 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00002075 case IntToPointer:
2076 DiagKind = diag::ext_typecheck_convert_int_pointer;
2077 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002078 case IncompatiblePointer:
2079 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2080 break;
2081 case FunctionVoidPointer:
2082 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2083 break;
2084 case CompatiblePointerDiscardsQualifiers:
2085 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2086 break;
2087 case Incompatible:
2088 DiagKind = diag::err_typecheck_convert_incompatible;
2089 isInvalid = true;
2090 break;
2091 }
2092
2093 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2094 SrcExpr->getSourceRange());
2095 return isInvalid;
2096}
2097