blob: 88ee864b24ec88ed292ab83e813f3f867ba05195 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000015#include "SemaUtil.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000018#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000023#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Steve Naroff87d58b42007-09-16 03:34:24 +000028/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000029/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000035Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000036 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
45
46 // FIXME: handle wchar_t
Anders Carlsson55bfe0d2007-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()));
Chris Lattner4b009652007-07-25 00:24:17 +000058
59 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
60 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000061 Literal.AnyWide, t,
62 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000063 StringToks[NumStringToks-1].getLocation());
64}
65
66
Steve Naroff0acc9c92007-09-15 18:49:24 +000067/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000068/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
69/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000070Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000071 IdentifierInfo &II,
72 bool HasTrailingLParen) {
73 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000074 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff5eb2a4a2007-11-12 14:29:37 +000083 if (CurMethodDecl) {
Ted Kremenek42730c52008-01-07 19:49:32 +000084 ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
85 ObjCInterfaceDecl *clsDeclared;
86 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
Steve Naroff6b759ce2007-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 Naroff5eb2a4a2007-11-12 14:29:37 +000092 }
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff91b03f72007-08-28 03:03:08 +000098 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +000099 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000100 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000101 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000102 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000103 }
Chris Lattner4b009652007-07-25 00:24:17 +0000104 if (isa<TypedefDecl>(D))
105 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000106 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000107 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000108
109 assert(0 && "Invalid decl");
110 abort();
111}
112
Steve Naroff87d58b42007-09-16 03:34:24 +0000113Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000114 tok::TokenKind Kind) {
115 PreDefinedExpr::IdentType IT;
116
117 switch (Kind) {
118 default:
119 assert(0 && "Unknown simple primary expr!");
120 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
121 IT = PreDefinedExpr::Func;
122 break;
123 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
124 IT = PreDefinedExpr::Function;
125 break;
126 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
127 IT = PreDefinedExpr::PrettyFunction;
128 break;
129 }
130
Chris Lattner7e637512008-01-12 08:14:25 +0000131 // Pre-defined identifiers are of type char[x], where x is the length of the
132 // string.
133 llvm::APSInt Length(32);
134 Length = CurFunctionDecl->getIdentifier()->getLength() + 1;
135 QualType ResTy = Context.getConstantArrayType(Context.CharTy, Length,
136 ArrayType::Normal, 0);
137 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000138}
139
Steve Naroff87d58b42007-09-16 03:34:24 +0000140Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000141 llvm::SmallString<16> CharBuffer;
142 CharBuffer.resize(Tok.getLength());
143 const char *ThisTokBegin = &CharBuffer[0];
144 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
145
146 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
147 Tok.getLocation(), PP);
148 if (Literal.hadError())
149 return ExprResult(true);
150 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
151 Tok.getLocation());
152}
153
Steve Naroff87d58b42007-09-16 03:34:24 +0000154Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000155 // fast path for a single digit (which is quite common). A single digit
156 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
157 if (Tok.getLength() == 1) {
158 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
159
Chris Lattner3496d522007-09-04 02:45:27 +0000160 unsigned IntSize = static_cast<unsigned>(
161 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000162 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
163 Context.IntTy,
164 Tok.getLocation()));
165 }
166 llvm::SmallString<512> IntegerBuffer;
167 IntegerBuffer.resize(Tok.getLength());
168 const char *ThisTokBegin = &IntegerBuffer[0];
169
170 // Get the spelling of the token, which eliminates trigraphs, etc.
171 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
172 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
173 Tok.getLocation(), PP);
174 if (Literal.hadError)
175 return ExprResult(true);
176
Chris Lattner1de66eb2007-08-26 03:42:43 +0000177 Expr *Res;
178
179 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000180 QualType Ty;
181 const llvm::fltSemantics *Format;
182 uint64_t Size; unsigned Align;
183
184 if (Literal.isFloat) {
185 Ty = Context.FloatTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000186 Context.Target.getFloatInfo(Size, Align, Format,
187 Context.getFullLoc(Tok.getLocation()));
188
Chris Lattner858eece2007-09-22 18:29:59 +0000189 } else if (Literal.isLong) {
190 Ty = Context.LongDoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000191 Context.Target.getLongDoubleInfo(Size, Align, Format,
192 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000193 } else {
194 Ty = Context.DoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000195 Context.Target.getDoubleInfo(Size, Align, Format,
196 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000197 }
198
Ted Kremenekddedbe22007-11-29 00:56:49 +0000199 // isExact will be set by GetFloatValue().
200 bool isExact = false;
201
202 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
203 Ty, Tok.getLocation());
204
Chris Lattner1de66eb2007-08-26 03:42:43 +0000205 } else if (!Literal.isIntegerLiteral()) {
206 return ExprResult(true);
207 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000208 QualType t;
209
Neil Booth7421e9c2007-08-29 22:00:19 +0000210 // long long is a C99 feature.
211 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000212 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000213 Diag(Tok.getLocation(), diag::ext_longlong);
214
Chris Lattner4b009652007-07-25 00:24:17 +0000215 // Get the value in the widest-possible width.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000216 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
217 Context.getFullLoc(Tok.getLocation())), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000218
219 if (Literal.GetIntegerValue(ResultVal)) {
220 // If this value didn't fit into uintmax_t, warn and force to ull.
221 Diag(Tok.getLocation(), diag::warn_integer_too_large);
222 t = Context.UnsignedLongLongTy;
223 assert(Context.getTypeSize(t, Tok.getLocation()) ==
224 ResultVal.getBitWidth() && "long long is not intmax_t?");
225 } else {
226 // If this value fits into a ULL, try to figure out what else it fits into
227 // according to the rules of C99 6.4.4.1p5.
228
229 // Octal, Hexadecimal, and integers with a U suffix are allowed to
230 // be an unsigned int.
231 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
232
233 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000234 if (!Literal.isLong && !Literal.isLongLong) {
235 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000236 unsigned IntSize = static_cast<unsigned>(
237 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000238 // Does it fit in a unsigned int?
239 if (ResultVal.isIntN(IntSize)) {
240 // Does it fit in a signed int?
241 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
242 t = Context.IntTy;
243 else if (AllowUnsigned)
244 t = Context.UnsignedIntTy;
245 }
246
247 if (!t.isNull())
248 ResultVal.trunc(IntSize);
249 }
250
251 // Are long/unsigned long possibilities?
252 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000253 unsigned LongSize = static_cast<unsigned>(
254 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000255
256 // Does it fit in a unsigned long?
257 if (ResultVal.isIntN(LongSize)) {
258 // Does it fit in a signed long?
259 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
260 t = Context.LongTy;
261 else if (AllowUnsigned)
262 t = Context.UnsignedLongTy;
263 }
264 if (!t.isNull())
265 ResultVal.trunc(LongSize);
266 }
267
268 // Finally, check long long if needed.
269 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000270 unsigned LongLongSize = static_cast<unsigned>(
271 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000272
273 // Does it fit in a unsigned long long?
274 if (ResultVal.isIntN(LongLongSize)) {
275 // Does it fit in a signed long long?
276 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
277 t = Context.LongLongTy;
278 else if (AllowUnsigned)
279 t = Context.UnsignedLongLongTy;
280 }
281 }
282
283 // If we still couldn't decide a type, we probably have something that
284 // does not fit in a signed long long, but has no U suffix.
285 if (t.isNull()) {
286 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
287 t = Context.UnsignedLongLongTy;
288 }
289 }
290
Chris Lattner1de66eb2007-08-26 03:42:43 +0000291 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000292 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000293
294 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
295 if (Literal.isImaginary)
296 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
297
298 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000299}
300
Steve Naroff87d58b42007-09-16 03:34:24 +0000301Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000302 ExprTy *Val) {
303 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000304 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000305 return new ParenExpr(L, R, e);
306}
307
308/// The UsualUnaryConversions() function is *not* called by this routine.
309/// See C99 6.3.2.1p[2-4] for more details.
310QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
311 SourceLocation OpLoc, bool isSizeof) {
312 // C99 6.5.3.4p1:
313 if (isa<FunctionType>(exprType) && isSizeof)
314 // alignof(function) is allowed.
315 Diag(OpLoc, diag::ext_sizeof_function_type);
316 else if (exprType->isVoidType())
317 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
318 else if (exprType->isIncompleteType()) {
319 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
320 diag::err_alignof_incomplete_type,
321 exprType.getAsString());
322 return QualType(); // error
323 }
324 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
325 return Context.getSizeType();
326}
327
328Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000329ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000330 SourceLocation LPLoc, TypeTy *Ty,
331 SourceLocation RPLoc) {
332 // If error parsing type, ignore.
333 if (Ty == 0) return true;
334
335 // Verify that this is a valid expression.
336 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
337
338 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
339
340 if (resultType.isNull())
341 return true;
342 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
343}
344
Chris Lattner5110ad52007-08-24 21:41:10 +0000345QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000346 DefaultFunctionArrayConversion(V);
347
Chris Lattnera16e42d2007-08-26 05:39:26 +0000348 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000349 if (const ComplexType *CT = V->getType()->getAsComplexType())
350 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000351
352 // Otherwise they pass through real integer and floating point types here.
353 if (V->getType()->isArithmeticType())
354 return V->getType();
355
356 // Reject anything else.
357 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
358 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000359}
360
361
Chris Lattner4b009652007-07-25 00:24:17 +0000362
Steve Naroff87d58b42007-09-16 03:34:24 +0000363Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000364 tok::TokenKind Kind,
365 ExprTy *Input) {
366 UnaryOperator::Opcode Opc;
367 switch (Kind) {
368 default: assert(0 && "Unknown unary op!");
369 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
370 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
371 }
372 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
373 if (result.isNull())
374 return true;
375 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
376}
377
378Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000379ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000380 ExprTy *Idx, SourceLocation RLoc) {
381 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
382
383 // Perform default conversions.
384 DefaultFunctionArrayConversion(LHSExp);
385 DefaultFunctionArrayConversion(RHSExp);
386
387 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
388
389 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000390 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000391 // in the subscript position. As a result, we need to derive the array base
392 // and index from the expression types.
393 Expr *BaseExpr, *IndexExpr;
394 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000395 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000396 BaseExpr = LHSExp;
397 IndexExpr = RHSExp;
398 // FIXME: need to deal with const...
399 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000400 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000401 // Handle the uncommon case of "123[Ptr]".
402 BaseExpr = RHSExp;
403 IndexExpr = LHSExp;
404 // FIXME: need to deal with const...
405 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000406 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
407 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000408 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000409
410 // Component access limited to variables (reject vec4.rg[1]).
411 if (!isa<DeclRefExpr>(BaseExpr))
412 return Diag(LLoc, diag::err_ocuvector_component_access,
413 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000414 // FIXME: need to deal with const...
415 ResultType = VTy->getElementType();
416 } else {
417 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
418 RHSExp->getSourceRange());
419 }
420 // C99 6.5.2.1p1
421 if (!IndexExpr->getType()->isIntegerType())
422 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
423 IndexExpr->getSourceRange());
424
425 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
426 // the following check catches trying to index a pointer to a function (e.g.
427 // void (*)(int)). Functions are not objects in C99.
428 if (!ResultType->isObjectType())
429 return Diag(BaseExpr->getLocStart(),
430 diag::err_typecheck_subscript_not_object,
431 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
432
433 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
434}
435
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000436QualType Sema::
437CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
438 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000439 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000440
441 // The vector accessor can't exceed the number of elements.
442 const char *compStr = CompName.getName();
443 if (strlen(compStr) > vecType->getNumElements()) {
444 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
445 baseType.getAsString(), SourceRange(CompLoc));
446 return QualType();
447 }
448 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000449 if (vecType->getPointAccessorIdx(*compStr) != -1) {
450 do
451 compStr++;
452 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
453 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
454 do
455 compStr++;
456 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
457 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
458 do
459 compStr++;
460 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
461 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000462
463 if (*compStr) {
464 // We didn't get to the end of the string. This means the component names
465 // didn't come from the same set *or* we encountered an illegal name.
466 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
467 std::string(compStr,compStr+1), SourceRange(CompLoc));
468 return QualType();
469 }
470 // Each component accessor can't exceed the vector type.
471 compStr = CompName.getName();
472 while (*compStr) {
473 if (vecType->isAccessorWithinNumElements(*compStr))
474 compStr++;
475 else
476 break;
477 }
478 if (*compStr) {
479 // We didn't get to the end of the string. This means a component accessor
480 // exceeds the number of elements in the vector.
481 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
482 baseType.getAsString(), SourceRange(CompLoc));
483 return QualType();
484 }
485 // The component accessor looks fine - now we need to compute the actual type.
486 // The vector type is implied by the component accessor. For example,
487 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
488 unsigned CompSize = strlen(CompName.getName());
489 if (CompSize == 1)
490 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000491
492 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
493 // Now look up the TypeDefDecl from the vector type. Without this,
494 // diagostics look bad. We want OCU vector types to appear built-in.
495 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
496 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
497 return Context.getTypedefType(OCUVectorDecls[i]);
498 }
499 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000500}
501
Chris Lattner4b009652007-07-25 00:24:17 +0000502Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000503ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000504 tok::TokenKind OpKind, SourceLocation MemberLoc,
505 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000506 Expr *BaseExpr = static_cast<Expr *>(Base);
507 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000508
509 // Perform default conversions.
510 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000511
Steve Naroff2cb66382007-07-26 03:11:44 +0000512 QualType BaseType = BaseExpr->getType();
513 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000514
Chris Lattner4b009652007-07-25 00:24:17 +0000515 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000516 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000517 BaseType = PT->getPointeeType();
518 else
519 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
520 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000521 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000522 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000523 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000524 RecordDecl *RDecl = RTy->getDecl();
525 if (RTy->isIncompleteType())
526 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
527 BaseExpr->getSourceRange());
528 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000529 FieldDecl *MemberDecl = RDecl->getMember(&Member);
530 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000531 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
532 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000533 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
534 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000535 // Component access limited to variables (reject vec4.rg.g).
536 if (!isa<DeclRefExpr>(BaseExpr))
537 return Diag(OpLoc, diag::err_ocuvector_component_access,
538 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000539 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
540 if (ret.isNull())
541 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000542 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000543 } else if (BaseType->isObjCInterfaceType()) {
544 ObjCInterfaceDecl *IFace;
545 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
546 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000547 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000548 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
549 ObjCInterfaceDecl *clsDeclared;
550 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000551 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
552 OpKind==tok::arrow);
553 }
554 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
555 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000556}
557
Steve Naroff87d58b42007-09-16 03:34:24 +0000558/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000559/// This provides the location of the left/right parens and a list of comma
560/// locations.
561Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000562ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000563 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000564 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
565 Expr *Fn = static_cast<Expr *>(fn);
566 Expr **Args = reinterpret_cast<Expr**>(args);
567 assert(Fn && "no function call expression");
568
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000569 // Make the call expr early, before semantic checks. This guarantees cleanup
570 // of arguments and function on error.
571 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
572 Context.BoolTy, RParenLoc));
573
574 // Promote the function operand.
575 TheCall->setCallee(UsualUnaryConversions(Fn));
576
Chris Lattner4b009652007-07-25 00:24:17 +0000577 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
578 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000579 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000580 if (PT == 0)
581 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
582 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000583 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
584 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000585 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
586 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000587
588 // We know the result type of the call, set it.
589 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000590
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000591 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000592 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
593 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000594 unsigned NumArgsInProto = Proto->getNumArgs();
595 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000596
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000597 // If too few arguments are available, don't make the call.
598 if (NumArgs < NumArgsInProto)
599 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
600 Fn->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000601
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000602 // If too many are passed and not variadic, error on the extras and drop
603 // them.
604 if (NumArgs > NumArgsInProto) {
605 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000606 Diag(Args[NumArgsInProto]->getLocStart(),
607 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
608 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000609 Args[NumArgs-1]->getLocEnd()));
610 // This deletes the extra arguments.
611 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000612 }
613 NumArgsToCheck = NumArgsInProto;
614 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000615
Chris Lattner4b009652007-07-25 00:24:17 +0000616 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000617 for (unsigned i = 0; i != NumArgsToCheck; i++) {
618 Expr *Arg = Args[i];
Chris Lattner005ed752008-01-04 18:04:52 +0000619 QualType ProtoArgType = Proto->getArgType(i);
620 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000621
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000622 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000623 AssignConvertType ConvTy =
624 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000625 TheCall->setArg(i, Arg);
626
Chris Lattner005ed752008-01-04 18:04:52 +0000627 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
628 ArgType, Arg, "passing"))
629 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000630 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000631
632 // If this is a variadic call, handle args passed through "...".
633 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000634 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000635 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
636 Expr *Arg = Args[i];
637 DefaultArgumentPromotion(Arg);
638 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000639 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000640 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000641 } else {
642 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
643
Steve Naroffdb65e052007-08-28 23:30:39 +0000644 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000645 for (unsigned i = 0; i != NumArgs; i++) {
646 Expr *Arg = Args[i];
647 DefaultArgumentPromotion(Arg);
648 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000649 }
Chris Lattner4b009652007-07-25 00:24:17 +0000650 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000651
Chris Lattner2e64c072007-08-10 20:18:51 +0000652 // Do special checking on direct calls to functions.
653 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
654 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
655 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000656 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000657 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000658
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000659 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000660}
661
662Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000663ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000664 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000665 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000666 QualType literalType = QualType::getFromOpaquePtr(Ty);
667 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000668 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000669 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000670
Steve Naroffcb69fb72007-12-10 22:44:33 +0000671 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Narofff0b23542008-01-10 22:15:12 +0000672 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000673 return true;
Steve Narofff0b23542008-01-10 22:15:12 +0000674
675 if (!CurFunctionDecl && !CurMethodDecl) { // 6.5.2.5p3
676 if (CheckForConstantInitializer(literalExpr, literalType))
677 return true;
678 }
Chris Lattner386ab8a2008-01-02 21:46:24 +0000679 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000680}
681
682Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000683ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000684 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000685 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000686
Steve Naroff0acc9c92007-09-15 18:49:24 +0000687 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000688 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000689
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000690 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
691 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
692 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000693}
694
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000695bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000696 assert(VectorTy->isVectorType() && "Not a vector type!");
697
698 if (Ty->isVectorType() || Ty->isIntegerType()) {
699 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
700 Context.getTypeSize(Ty, SourceLocation()))
701 return Diag(R.getBegin(),
702 Ty->isVectorType() ?
703 diag::err_invalid_conversion_between_vectors :
704 diag::err_invalid_conversion_between_vector_and_integer,
705 VectorTy.getAsString().c_str(),
706 Ty.getAsString().c_str(), R);
707 } else
708 return Diag(R.getBegin(),
709 diag::err_invalid_conversion_between_vector_and_scalar,
710 VectorTy.getAsString().c_str(),
711 Ty.getAsString().c_str(), R);
712
713 return false;
714}
715
Chris Lattner4b009652007-07-25 00:24:17 +0000716Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000717ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000718 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000719 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000720
721 Expr *castExpr = static_cast<Expr*>(Op);
722 QualType castType = QualType::getFromOpaquePtr(Ty);
723
Steve Naroff68adb482007-08-31 00:32:44 +0000724 UsualUnaryConversions(castExpr);
725
Chris Lattner4b009652007-07-25 00:24:17 +0000726 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
727 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000728 if (!castType->isVoidType()) { // Cast to void allows any expr type.
729 if (!castType->isScalarType())
730 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
731 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000732 if (!castExpr->getType()->isScalarType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000733 return Diag(castExpr->getLocStart(),
734 diag::err_typecheck_expect_scalar_operand,
735 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000736
737 if (castExpr->getType()->isVectorType()) {
738 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
739 castExpr->getType(), castType))
740 return true;
741 } else if (castType->isVectorType()) {
742 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
743 castType, castExpr->getType()))
744 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000745 }
Chris Lattner4b009652007-07-25 00:24:17 +0000746 }
747 return new CastExpr(castType, castExpr, LParenLoc);
748}
749
Steve Naroff144667e2007-10-18 05:13:08 +0000750// promoteExprToType - a helper function to ensure we create exactly one
751// ImplicitCastExpr.
752static void promoteExprToType(Expr *&expr, QualType type) {
753 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
754 impCast->setType(type);
755 else
756 expr = new ImplicitCastExpr(type, expr);
757 return;
758}
759
Chris Lattner98a425c2007-11-26 01:40:58 +0000760/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
761/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000762inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
763 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
764 UsualUnaryConversions(cond);
765 UsualUnaryConversions(lex);
766 UsualUnaryConversions(rex);
767 QualType condT = cond->getType();
768 QualType lexT = lex->getType();
769 QualType rexT = rex->getType();
770
771 // first, check the condition.
772 if (!condT->isScalarType()) { // C99 6.5.15p2
773 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
774 condT.getAsString());
775 return QualType();
776 }
Chris Lattner992ae932008-01-06 22:42:25 +0000777
778 // Now check the two expressions.
779
780 // If both operands have arithmetic type, do the usual arithmetic conversions
781 // to find a common type: C99 6.5.15p3,5.
782 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000783 UsualArithmeticConversions(lex, rex);
784 return lex->getType();
785 }
Chris Lattner992ae932008-01-06 22:42:25 +0000786
787 // If both operands are the same structure or union type, the result is that
788 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000789 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000790 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000791 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000792 // "If both the operands have structure or union type, the result has
793 // that type." This implies that CV qualifiers are dropped.
794 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000795 }
Chris Lattner992ae932008-01-06 22:42:25 +0000796
797 // C99 6.5.15p5: "If both operands have void type, the result has void type."
798 if (lexT->isVoidType() && rexT->isVoidType())
799 return lexT.getUnqualifiedType();
Steve Naroff12ebf272008-01-08 01:11:38 +0000800
801 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
802 // the type of the other operand."
803 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
804 promoteExprToType(rex, lexT); // promote the null to a pointer.
805 return lexT;
806 }
807 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
808 promoteExprToType(lex, rexT); // promote the null to a pointer.
809 return rexT;
810 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000811 // Handle the case where both operands are pointers before we handle null
812 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000813 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
814 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
815 // get the "pointed to" types
816 QualType lhptee = LHSPT->getPointeeType();
817 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000818
Chris Lattner71225142007-07-31 21:27:01 +0000819 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
820 if (lhptee->isVoidType() &&
821 (rhptee->isObjectType() || rhptee->isIncompleteType()))
822 return lexT;
823 if (rhptee->isVoidType() &&
824 (lhptee->isObjectType() || lhptee->isIncompleteType()))
825 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000826
Steve Naroff85f0dc52007-10-15 20:41:53 +0000827 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
828 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000829 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
830 lexT.getAsString(), rexT.getAsString(),
831 lex->getSourceRange(), rex->getSourceRange());
832 return lexT; // FIXME: this is an _ext - is this return o.k?
833 }
834 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000835 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
836 // differently qualified versions of compatible types, the result type is
837 // a pointer to an appropriately qualified version of the *composite*
838 // type.
Chris Lattner0ac51632008-01-06 22:50:31 +0000839 // FIXME: Need to return the composite type.
840 return lexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000841 }
Chris Lattner4b009652007-07-25 00:24:17 +0000842 }
Chris Lattner71225142007-07-31 21:27:01 +0000843
Chris Lattner992ae932008-01-06 22:42:25 +0000844 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000845 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
846 lexT.getAsString(), rexT.getAsString(),
847 lex->getSourceRange(), rex->getSourceRange());
848 return QualType();
849}
850
Steve Naroff87d58b42007-09-16 03:34:24 +0000851/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000852/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000853Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000854 SourceLocation ColonLoc,
855 ExprTy *Cond, ExprTy *LHS,
856 ExprTy *RHS) {
857 Expr *CondExpr = (Expr *) Cond;
858 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000859
860 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
861 // was the condition.
862 bool isLHSNull = LHSExpr == 0;
863 if (isLHSNull)
864 LHSExpr = CondExpr;
865
Chris Lattner4b009652007-07-25 00:24:17 +0000866 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
867 RHSExpr, QuestionLoc);
868 if (result.isNull())
869 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000870 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
871 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000872}
873
Steve Naroffdb65e052007-08-28 23:30:39 +0000874/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
875/// do not have a prototype. Integer promotions are performed on each
876/// argument, and arguments that have type float are promoted to double.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000877void Sema::DefaultArgumentPromotion(Expr *&Expr) {
878 QualType Ty = Expr->getType();
879 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000880
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000881 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
882 promoteExprToType(Expr, Context.IntTy);
883 if (Ty == Context.FloatTy)
884 promoteExprToType(Expr, Context.DoubleTy);
Steve Naroffdb65e052007-08-28 23:30:39 +0000885}
886
Chris Lattner4b009652007-07-25 00:24:17 +0000887/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
888void Sema::DefaultFunctionArrayConversion(Expr *&e) {
889 QualType t = e->getType();
890 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
891
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000892 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000893 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
894 t = e->getType();
895 }
896 if (t->isFunctionType())
897 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000898 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000899 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
900}
901
902/// UsualUnaryConversion - Performs various conversions that are common to most
903/// operators (C99 6.3). The conversions of array and function types are
904/// sometimes surpressed. For example, the array->pointer conversion doesn't
905/// apply if the array is an argument to the sizeof or address (&) operators.
906/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000907Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
908 QualType Ty = Expr->getType();
909 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000910
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000911 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
912 promoteExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
913 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000914 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000915 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
916 promoteExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000917 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000918 DefaultFunctionArrayConversion(Expr);
919
920 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000921}
922
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000923/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000924/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
925/// routine returns the first non-arithmetic type found. The client is
926/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000927QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
928 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000929 if (!isCompAssign) {
930 UsualUnaryConversions(lhsExpr);
931 UsualUnaryConversions(rhsExpr);
932 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000933 // For conversion purposes, we ignore any qualifiers.
934 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000935 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
936 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000937
938 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000939 if (lhs == rhs)
940 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000941
942 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
943 // The caller can deal with this (e.g. pointer + int).
944 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000945 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000946
947 // At this point, we have two different arithmetic types.
948
949 // Handle complex types first (C99 6.3.1.8p1).
950 if (lhs->isComplexType() || rhs->isComplexType()) {
951 // if we have an integer operand, the result is the complex type.
952 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000953 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
954 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000955 }
956 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000957 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
958 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000959 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000960 // This handles complex/complex, complex/float, or float/complex.
961 // When both operands are complex, the shorter operand is converted to the
962 // type of the longer, and that is the type of the result. This corresponds
963 // to what is done when combining two real floating-point operands.
964 // The fun begins when size promotion occur across type domains.
965 // From H&S 6.3.4: When one operand is complex and the other is a real
966 // floating-point type, the less precise type is converted, within it's
967 // real or complex domain, to the precision of the other type. For example,
968 // when combining a "long double" with a "double _Complex", the
969 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000970 int result = Context.compareFloatingType(lhs, rhs);
971
972 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000973 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
974 if (!isCompAssign)
975 promoteExprToType(rhsExpr, rhs);
976 } else if (result < 0) { // The right side is bigger, convert lhs.
977 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
978 if (!isCompAssign)
979 promoteExprToType(lhsExpr, lhs);
980 }
981 // At this point, lhs and rhs have the same rank/size. Now, make sure the
982 // domains match. This is a requirement for our implementation, C99
983 // does not require this promotion.
984 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
985 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000986 if (!isCompAssign)
987 promoteExprToType(lhsExpr, rhs);
988 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000989 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000990 if (!isCompAssign)
991 promoteExprToType(rhsExpr, lhs);
992 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000993 }
Chris Lattner4b009652007-07-25 00:24:17 +0000994 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000995 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000996 }
997 // Now handle "real" floating types (i.e. float, double, long double).
998 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
999 // if we have an integer operand, the result is the real floating type.
1000 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001001 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1002 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001003 }
1004 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001005 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1006 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001007 }
1008 // We have two real floating types, float/complex combos were handled above.
1009 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001010 int result = Context.compareFloatingType(lhs, rhs);
1011
1012 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001013 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1014 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001015 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001016 if (result < 0) { // convert the lhs
1017 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1018 return rhs;
1019 }
1020 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001021 }
1022 // Finally, we have two differing integer types.
1023 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001024 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1025 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001026 }
Steve Naroff8f708362007-08-24 19:07:16 +00001027 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1028 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001029}
1030
1031// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1032// being closely modeled after the C99 spec:-). The odd characteristic of this
1033// routine is it effectively iqnores the qualifiers on the top level pointee.
1034// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1035// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001036Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001037Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1038 QualType lhptee, rhptee;
1039
1040 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001041 lhptee = lhsType->getAsPointerType()->getPointeeType();
1042 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001043
1044 // make sure we operate on the canonical type
1045 lhptee = lhptee.getCanonicalType();
1046 rhptee = rhptee.getCanonicalType();
1047
Chris Lattner005ed752008-01-04 18:04:52 +00001048 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001049
1050 // C99 6.5.16.1p1: This following citation is common to constraints
1051 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1052 // qualifiers of the type *pointed to* by the right;
1053 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1054 rhptee.getQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001055 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001056
1057 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1058 // incomplete type and the other is a pointer to a qualified or unqualified
1059 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001060 if (lhptee->isVoidType()) {
1061 if (rhptee->isObjectType() || rhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001062 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001063
1064 // As an extension, we allow cast to/from void* to function pointer.
1065 if (rhptee->isFunctionType())
1066 return FunctionVoidPointer;
1067 }
1068
1069 if (rhptee->isVoidType()) {
1070 if (lhptee->isObjectType() || lhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001071 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001072
1073 // As an extension, we allow cast to/from void* to function pointer.
1074 if (lhptee->isFunctionType())
1075 return FunctionVoidPointer;
1076 }
1077
Chris Lattner4b009652007-07-25 00:24:17 +00001078 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1079 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001080 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1081 rhptee.getUnqualifiedType()))
1082 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001083 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001084}
1085
1086/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1087/// has code to accommodate several GCC extensions when type checking
1088/// pointers. Here are some objectionable examples that GCC considers warnings:
1089///
1090/// int a, *pint;
1091/// short *pshort;
1092/// struct foo *pfoo;
1093///
1094/// pint = pshort; // warning: assignment from incompatible pointer type
1095/// a = pint; // warning: assignment makes integer from pointer without a cast
1096/// pint = a; // warning: assignment makes pointer from integer without a cast
1097/// pint = pfoo; // warning: assignment from incompatible pointer type
1098///
1099/// As a result, the code for dealing with pointers is more complex than the
1100/// C99 spec dictates.
1101/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1102///
Chris Lattner005ed752008-01-04 18:04:52 +00001103Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001104Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001105 // Get canonical types. We're not formatting these types, just comparing
1106 // them.
1107 lhsType = lhsType.getCanonicalType();
1108 rhsType = rhsType.getCanonicalType();
1109
1110 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001111 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001112
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001113 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001114 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001115 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001116 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001117 }
Chris Lattner1853da22008-01-04 23:18:45 +00001118
Ted Kremenek42730c52008-01-07 19:49:32 +00001119 if (lhsType->isObjCQualifiedIdType()
1120 || rhsType->isObjCQualifiedIdType()) {
1121 if (Context.ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001122 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001123 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001124 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001125
1126 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1127 // For OCUVector, allow vector splats; float -> <n x float>
1128 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1129 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1130 return Compatible;
1131 }
1132
1133 // If LHS and RHS are both vectors of integer or both vectors of floating
1134 // point types, and the total vector length is the same, allow the
1135 // conversion. This is a bitcast; no bits are changed but the result type
1136 // is different.
1137 if (getLangOptions().LaxVectorConversions &&
1138 lhsType->isVectorType() && rhsType->isVectorType()) {
1139 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1140 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
1141 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1142 Context.getTypeSize(rhsType, SourceLocation()))
Nate Begemanec2d1062007-12-30 02:59:45 +00001143 return Compatible;
1144 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001145 }
1146 return Incompatible;
1147 }
1148
1149 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001150 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001151
1152 if (lhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001153 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001154 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001155
1156 if (rhsType->isPointerType())
1157 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001158 return Incompatible;
1159 }
1160
1161 if (rhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001162 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1163 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001164 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001165
1166 if (lhsType->isPointerType())
1167 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001168 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001169 }
1170
1171 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001172 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001173 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001174 }
1175 return Incompatible;
1176}
1177
Chris Lattner005ed752008-01-04 18:04:52 +00001178Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001179Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001180 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1181 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001182 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001183 && rExpr->isNullPointerConstant(Context)) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001184 promoteExprToType(rExpr, lhsType);
1185 return Compatible;
1186 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001187 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001188 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001189 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001190 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001191 //
1192 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1193 // are better understood.
1194 if (!lhsType->isReferenceType())
1195 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001196
Chris Lattner005ed752008-01-04 18:04:52 +00001197 Sema::AssignConvertType result =
1198 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001199
1200 // C99 6.5.16.1p2: The value of the right operand is converted to the
1201 // type of the assignment expression.
1202 if (rExpr->getType() != lhsType)
1203 promoteExprToType(rExpr, lhsType);
1204 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001205}
1206
Chris Lattner005ed752008-01-04 18:04:52 +00001207Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001208Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1209 return CheckAssignmentConstraints(lhsType, rhsType);
1210}
1211
Chris Lattner2c8bff72007-12-12 05:47:28 +00001212QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001213 Diag(loc, diag::err_typecheck_invalid_operands,
1214 lex->getType().getAsString(), rex->getType().getAsString(),
1215 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001216 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001217}
1218
1219inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1220 Expr *&rex) {
1221 QualType lhsType = lex->getType(), rhsType = rex->getType();
1222
1223 // make sure the vector types are identical.
1224 if (lhsType == rhsType)
1225 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001226
1227 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1228 // promote the rhs to the vector type.
1229 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1230 if (V->getElementType().getCanonicalType().getTypePtr()
1231 == rhsType.getCanonicalType().getTypePtr()) {
1232 promoteExprToType(rex, lhsType);
1233 return lhsType;
1234 }
1235 }
1236
1237 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1238 // promote the lhs to the vector type.
1239 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1240 if (V->getElementType().getCanonicalType().getTypePtr()
1241 == lhsType.getCanonicalType().getTypePtr()) {
1242 promoteExprToType(lex, rhsType);
1243 return rhsType;
1244 }
1245 }
1246
Chris Lattner4b009652007-07-25 00:24:17 +00001247 // You cannot convert between vector values of different size.
1248 Diag(loc, diag::err_typecheck_vector_not_convertable,
1249 lex->getType().getAsString(), rex->getType().getAsString(),
1250 lex->getSourceRange(), rex->getSourceRange());
1251 return QualType();
1252}
1253
1254inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001255 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001256{
1257 QualType lhsType = lex->getType(), rhsType = rex->getType();
1258
1259 if (lhsType->isVectorType() || rhsType->isVectorType())
1260 return CheckVectorOperands(loc, lex, rex);
1261
Steve Naroff8f708362007-08-24 19:07:16 +00001262 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001263
Chris Lattner4b009652007-07-25 00:24:17 +00001264 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001265 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001266 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001267}
1268
1269inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001270 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001271{
1272 QualType lhsType = lex->getType(), rhsType = rex->getType();
1273
Steve Naroff8f708362007-08-24 19:07:16 +00001274 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001275
Chris Lattner4b009652007-07-25 00:24:17 +00001276 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001277 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001278 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001279}
1280
1281inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001282 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001283{
1284 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1285 return CheckVectorOperands(loc, lex, rex);
1286
Steve Naroff8f708362007-08-24 19:07:16 +00001287 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001288
1289 // handle the common case first (both operands are arithmetic).
1290 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001291 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001292
1293 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1294 return lex->getType();
1295 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1296 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001297 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001298}
1299
1300inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001301 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001302{
1303 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1304 return CheckVectorOperands(loc, lex, rex);
1305
Steve Naroff8f708362007-08-24 19:07:16 +00001306 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001307
Chris Lattnerf6da2912007-12-09 21:53:25 +00001308 // Enforce type constraints: C99 6.5.6p3.
1309
1310 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001311 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001312 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001313
1314 // Either ptr - int or ptr - ptr.
1315 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1316 // The LHS must be an object type, not incomplete, function, etc.
1317 if (!LHSPTy->getPointeeType()->isObjectType()) {
1318 // Handle the GNU void* extension.
1319 if (LHSPTy->getPointeeType()->isVoidType()) {
1320 Diag(loc, diag::ext_gnu_void_ptr,
1321 lex->getSourceRange(), rex->getSourceRange());
1322 } else {
1323 Diag(loc, diag::err_typecheck_sub_ptr_object,
1324 lex->getType().getAsString(), lex->getSourceRange());
1325 return QualType();
1326 }
1327 }
1328
1329 // The result type of a pointer-int computation is the pointer type.
1330 if (rex->getType()->isIntegerType())
1331 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001332
Chris Lattnerf6da2912007-12-09 21:53:25 +00001333 // Handle pointer-pointer subtractions.
1334 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1335 // RHS must be an object type, unless void (GNU).
1336 if (!RHSPTy->getPointeeType()->isObjectType()) {
1337 // Handle the GNU void* extension.
1338 if (RHSPTy->getPointeeType()->isVoidType()) {
1339 if (!LHSPTy->getPointeeType()->isVoidType())
1340 Diag(loc, diag::ext_gnu_void_ptr,
1341 lex->getSourceRange(), rex->getSourceRange());
1342 } else {
1343 Diag(loc, diag::err_typecheck_sub_ptr_object,
1344 rex->getType().getAsString(), rex->getSourceRange());
1345 return QualType();
1346 }
1347 }
1348
1349 // Pointee types must be compatible.
1350 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1351 RHSPTy->getPointeeType())) {
1352 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1353 lex->getType().getAsString(), rex->getType().getAsString(),
1354 lex->getSourceRange(), rex->getSourceRange());
1355 return QualType();
1356 }
1357
1358 return Context.getPointerDiffType();
1359 }
1360 }
1361
Chris Lattner2c8bff72007-12-12 05:47:28 +00001362 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001363}
1364
1365inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattner2c8bff72007-12-12 05:47:28 +00001366 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1367 // C99 6.5.7p2: Each of the operands shall have integer type.
1368 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1369 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001370
Chris Lattner2c8bff72007-12-12 05:47:28 +00001371 // Shifts don't perform usual arithmetic conversions, they just do integer
1372 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001373 if (!isCompAssign)
1374 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001375 UsualUnaryConversions(rex);
1376
1377 // "The type of the result is that of the promoted left operand."
1378 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001379}
1380
Chris Lattner254f3bc2007-08-26 01:18:55 +00001381inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1382 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001383{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001384 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001385 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1386 UsualArithmeticConversions(lex, rex);
1387 else {
1388 UsualUnaryConversions(lex);
1389 UsualUnaryConversions(rex);
1390 }
Chris Lattner4b009652007-07-25 00:24:17 +00001391 QualType lType = lex->getType();
1392 QualType rType = rex->getType();
1393
Ted Kremenek486509e2007-10-29 17:13:39 +00001394 // For non-floating point types, check for self-comparisons of the form
1395 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1396 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001397 if (!lType->isFloatingType()) {
1398 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1399 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1400 if (DRL->getDecl() == DRR->getDecl())
1401 Diag(loc, diag::warn_selfcomparison);
1402 }
1403
Chris Lattner254f3bc2007-08-26 01:18:55 +00001404 if (isRelational) {
1405 if (lType->isRealType() && rType->isRealType())
1406 return Context.IntTy;
1407 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001408 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001409 if (lType->isFloatingType()) {
1410 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001411 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001412 }
1413
Chris Lattner254f3bc2007-08-26 01:18:55 +00001414 if (lType->isArithmeticType() && rType->isArithmeticType())
1415 return Context.IntTy;
1416 }
Chris Lattner4b009652007-07-25 00:24:17 +00001417
Chris Lattner22be8422007-08-26 01:10:14 +00001418 bool LHSIsNull = lex->isNullPointerConstant(Context);
1419 bool RHSIsNull = rex->isNullPointerConstant(Context);
1420
Chris Lattner254f3bc2007-08-26 01:18:55 +00001421 // All of the following pointer related warnings are GCC extensions, except
1422 // when handling null pointer constants. One day, we can consider making them
1423 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001424 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001425
1426 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1427 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1428 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001429 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1430 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001431 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1432 lType.getAsString(), rType.getAsString(),
1433 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001434 }
Chris Lattner22be8422007-08-26 01:10:14 +00001435 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001436 return Context.IntTy;
1437 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001438 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
1439 && Context.ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001440 promoteExprToType(rex, lType);
1441 return Context.IntTy;
1442 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001443 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001444 if (!RHSIsNull)
Steve Naroff4462cb02007-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 Lattner22be8422007-08-26 01:10:14 +00001448 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001449 return Context.IntTy;
1450 }
1451 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001452 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001453 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1454 lType.getAsString(), rType.getAsString(),
1455 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001456 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001457 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001458 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001459 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001460}
1461
Chris Lattner4b009652007-07-25 00:24:17 +00001462inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001463 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001464{
1465 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1466 return CheckVectorOperands(loc, lex, rex);
1467
Steve Naroff8f708362007-08-24 19:07:16 +00001468 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001469
1470 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001471 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001472 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001473}
1474
1475inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1476 Expr *&lex, Expr *&rex, SourceLocation loc)
1477{
1478 UsualUnaryConversions(lex);
1479 UsualUnaryConversions(rex);
1480
1481 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1482 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001483 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001484}
1485
1486inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001487 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001488{
1489 QualType lhsType = lex->getType();
1490 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001491 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1492
1493 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001494 case Expr::MLV_Valid:
1495 break;
1496 case Expr::MLV_ConstQualified:
1497 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1498 return QualType();
1499 case Expr::MLV_ArrayType:
1500 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1501 lhsType.getAsString(), lex->getSourceRange());
1502 return QualType();
1503 case Expr::MLV_NotObjectType:
1504 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1505 lhsType.getAsString(), lex->getSourceRange());
1506 return QualType();
1507 case Expr::MLV_InvalidExpression:
1508 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1509 lex->getSourceRange());
1510 return QualType();
1511 case Expr::MLV_IncompleteType:
1512 case Expr::MLV_IncompleteVoidType:
1513 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1514 lhsType.getAsString(), lex->getSourceRange());
1515 return QualType();
1516 case Expr::MLV_DuplicateVectorComponents:
1517 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1518 lex->getSourceRange());
1519 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001520 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001521
Chris Lattner005ed752008-01-04 18:04:52 +00001522 AssignConvertType ConvTy;
1523 if (compoundType.isNull())
1524 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1525 else
1526 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1527
1528 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1529 rex, "assigning"))
1530 return QualType();
1531
Chris Lattner4b009652007-07-25 00:24:17 +00001532 // C99 6.5.16p3: The type of an assignment expression is the type of the
1533 // left operand unless the left operand has qualified type, in which case
1534 // it is the unqualified version of the type of the left operand.
1535 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1536 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001537 // C++ 5.17p1: the type of the assignment expression is that of its left
1538 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001539 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001540}
1541
1542inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1543 Expr *&lex, Expr *&rex, SourceLocation loc) {
1544 UsualUnaryConversions(rex);
1545 return rex->getType();
1546}
1547
1548/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1549/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1550QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1551 QualType resType = op->getType();
1552 assert(!resType.isNull() && "no type for increment/decrement expression");
1553
Steve Naroffd30e1932007-08-24 17:20:07 +00001554 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001555 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001556 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1557 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1558 resType.getAsString(), op->getSourceRange());
1559 return QualType();
1560 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001561 } else if (!resType->isRealType()) {
1562 if (resType->isComplexType())
1563 // C99 does not support ++/-- on complex types.
1564 Diag(OpLoc, diag::ext_integer_increment_complex,
1565 resType.getAsString(), op->getSourceRange());
1566 else {
1567 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1568 resType.getAsString(), op->getSourceRange());
1569 return QualType();
1570 }
Chris Lattner4b009652007-07-25 00:24:17 +00001571 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001572 // At this point, we know we have a real, complex or pointer type.
1573 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001574 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1575 if (mlval != Expr::MLV_Valid) {
1576 // FIXME: emit a more precise diagnostic...
1577 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1578 op->getSourceRange());
1579 return QualType();
1580 }
1581 return resType;
1582}
1583
1584/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1585/// This routine allows us to typecheck complex/recursive expressions
1586/// where the declaration is needed for type checking. Here are some
1587/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1588static Decl *getPrimaryDeclaration(Expr *e) {
1589 switch (e->getStmtClass()) {
1590 case Stmt::DeclRefExprClass:
1591 return cast<DeclRefExpr>(e)->getDecl();
1592 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001593 // Fields cannot be declared with a 'register' storage class.
1594 // &X->f is always ok, even if X is declared register.
1595 if (cast<MemberExpr>(e)->isArrow())
1596 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001597 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1598 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001599 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001600 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001601 case Stmt::UnaryOperatorClass:
1602 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1603 case Stmt::ParenExprClass:
1604 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001605 case Stmt::ImplicitCastExprClass:
1606 // &X[4] when X is an array, has an implicit cast from array to pointer.
1607 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001608 default:
1609 return 0;
1610 }
1611}
1612
1613/// CheckAddressOfOperand - The operand of & must be either a function
1614/// designator or an lvalue designating an object. If it is an lvalue, the
1615/// object cannot be declared with storage class register or be a bit field.
1616/// Note: The usual conversions are *not* applied to the operand of the &
1617/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1618QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1619 Decl *dcl = getPrimaryDeclaration(op);
1620 Expr::isLvalueResult lval = op->isLvalue();
1621
1622 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001623 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1624 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001625 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1626 op->getSourceRange());
1627 return QualType();
1628 }
1629 } else if (dcl) {
1630 // We have an lvalue with a decl. Make sure the decl is not declared
1631 // with the register storage-class specifier.
1632 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1633 if (vd->getStorageClass() == VarDecl::Register) {
1634 Diag(OpLoc, diag::err_typecheck_address_of_register,
1635 op->getSourceRange());
1636 return QualType();
1637 }
1638 } else
1639 assert(0 && "Unknown/unexpected decl type");
1640
1641 // FIXME: add check for bitfields!
1642 }
1643 // If the operand has type "type", the result has type "pointer to type".
1644 return Context.getPointerType(op->getType());
1645}
1646
1647QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1648 UsualUnaryConversions(op);
1649 QualType qType = op->getType();
1650
Chris Lattner7931f4a2007-07-31 16:53:04 +00001651 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001652 QualType ptype = PT->getPointeeType();
1653 // C99 6.5.3.2p4. "if it points to an object,...".
1654 if (ptype->isIncompleteType()) { // An incomplete type is not an object
Chris Lattnerfabcc642008-01-06 22:21:46 +00001655 // GCC compat: special case 'void *' (treat as extension, not error).
Chris Lattner4b009652007-07-25 00:24:17 +00001656 if (ptype->isVoidType()) {
Chris Lattnerfabcc642008-01-06 22:21:46 +00001657 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001658 } else {
1659 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1660 ptype.getAsString(), op->getSourceRange());
1661 return QualType();
1662 }
1663 }
1664 return ptype;
1665 }
1666 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1667 qType.getAsString(), op->getSourceRange());
1668 return QualType();
1669}
1670
1671static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1672 tok::TokenKind Kind) {
1673 BinaryOperator::Opcode Opc;
1674 switch (Kind) {
1675 default: assert(0 && "Unknown binop!");
1676 case tok::star: Opc = BinaryOperator::Mul; break;
1677 case tok::slash: Opc = BinaryOperator::Div; break;
1678 case tok::percent: Opc = BinaryOperator::Rem; break;
1679 case tok::plus: Opc = BinaryOperator::Add; break;
1680 case tok::minus: Opc = BinaryOperator::Sub; break;
1681 case tok::lessless: Opc = BinaryOperator::Shl; break;
1682 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1683 case tok::lessequal: Opc = BinaryOperator::LE; break;
1684 case tok::less: Opc = BinaryOperator::LT; break;
1685 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1686 case tok::greater: Opc = BinaryOperator::GT; break;
1687 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1688 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1689 case tok::amp: Opc = BinaryOperator::And; break;
1690 case tok::caret: Opc = BinaryOperator::Xor; break;
1691 case tok::pipe: Opc = BinaryOperator::Or; break;
1692 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1693 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1694 case tok::equal: Opc = BinaryOperator::Assign; break;
1695 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1696 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1697 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1698 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1699 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1700 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1701 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1702 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1703 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1704 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1705 case tok::comma: Opc = BinaryOperator::Comma; break;
1706 }
1707 return Opc;
1708}
1709
1710static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1711 tok::TokenKind Kind) {
1712 UnaryOperator::Opcode Opc;
1713 switch (Kind) {
1714 default: assert(0 && "Unknown unary op!");
1715 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1716 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1717 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1718 case tok::star: Opc = UnaryOperator::Deref; break;
1719 case tok::plus: Opc = UnaryOperator::Plus; break;
1720 case tok::minus: Opc = UnaryOperator::Minus; break;
1721 case tok::tilde: Opc = UnaryOperator::Not; break;
1722 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1723 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1724 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1725 case tok::kw___real: Opc = UnaryOperator::Real; break;
1726 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1727 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1728 }
1729 return Opc;
1730}
1731
1732// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001733Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001734 ExprTy *LHS, ExprTy *RHS) {
1735 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1736 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1737
Steve Naroff87d58b42007-09-16 03:34:24 +00001738 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1739 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001740
1741 QualType ResultTy; // Result type of the binary operator.
1742 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1743
1744 switch (Opc) {
1745 default:
1746 assert(0 && "Unknown binary expr!");
1747 case BinaryOperator::Assign:
1748 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1749 break;
1750 case BinaryOperator::Mul:
1751 case BinaryOperator::Div:
1752 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1753 break;
1754 case BinaryOperator::Rem:
1755 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1756 break;
1757 case BinaryOperator::Add:
1758 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1759 break;
1760 case BinaryOperator::Sub:
1761 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1762 break;
1763 case BinaryOperator::Shl:
1764 case BinaryOperator::Shr:
1765 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1766 break;
1767 case BinaryOperator::LE:
1768 case BinaryOperator::LT:
1769 case BinaryOperator::GE:
1770 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001771 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001772 break;
1773 case BinaryOperator::EQ:
1774 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001775 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001776 break;
1777 case BinaryOperator::And:
1778 case BinaryOperator::Xor:
1779 case BinaryOperator::Or:
1780 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1781 break;
1782 case BinaryOperator::LAnd:
1783 case BinaryOperator::LOr:
1784 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1785 break;
1786 case BinaryOperator::MulAssign:
1787 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001788 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001789 if (!CompTy.isNull())
1790 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1791 break;
1792 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001793 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001794 if (!CompTy.isNull())
1795 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1796 break;
1797 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001798 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001799 if (!CompTy.isNull())
1800 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1801 break;
1802 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001803 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001804 if (!CompTy.isNull())
1805 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1806 break;
1807 case BinaryOperator::ShlAssign:
1808 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001809 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001810 if (!CompTy.isNull())
1811 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1812 break;
1813 case BinaryOperator::AndAssign:
1814 case BinaryOperator::XorAssign:
1815 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001816 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001817 if (!CompTy.isNull())
1818 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1819 break;
1820 case BinaryOperator::Comma:
1821 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1822 break;
1823 }
1824 if (ResultTy.isNull())
1825 return true;
1826 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001827 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001828 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001829 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001830}
1831
1832// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001833Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001834 ExprTy *input) {
1835 Expr *Input = (Expr*)input;
1836 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1837 QualType resultType;
1838 switch (Opc) {
1839 default:
1840 assert(0 && "Unimplemented unary expr!");
1841 case UnaryOperator::PreInc:
1842 case UnaryOperator::PreDec:
1843 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1844 break;
1845 case UnaryOperator::AddrOf:
1846 resultType = CheckAddressOfOperand(Input, OpLoc);
1847 break;
1848 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001849 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001850 resultType = CheckIndirectionOperand(Input, OpLoc);
1851 break;
1852 case UnaryOperator::Plus:
1853 case UnaryOperator::Minus:
1854 UsualUnaryConversions(Input);
1855 resultType = Input->getType();
1856 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1857 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1858 resultType.getAsString());
1859 break;
1860 case UnaryOperator::Not: // bitwise complement
1861 UsualUnaryConversions(Input);
1862 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001863 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1864 if (!resultType->isIntegerType()) {
1865 if (resultType->isComplexType())
1866 // C99 does not support '~' for complex conjugation.
1867 Diag(OpLoc, diag::ext_integer_complement_complex,
1868 resultType.getAsString());
1869 else
1870 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1871 resultType.getAsString());
1872 }
Chris Lattner4b009652007-07-25 00:24:17 +00001873 break;
1874 case UnaryOperator::LNot: // logical negation
1875 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1876 DefaultFunctionArrayConversion(Input);
1877 resultType = Input->getType();
1878 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1879 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1880 resultType.getAsString());
1881 // LNot always has type int. C99 6.5.3.3p5.
1882 resultType = Context.IntTy;
1883 break;
1884 case UnaryOperator::SizeOf:
1885 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1886 break;
1887 case UnaryOperator::AlignOf:
1888 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1889 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001890 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001891 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001892 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001893 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001894 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001895 resultType = Input->getType();
1896 break;
1897 }
1898 if (resultType.isNull())
1899 return true;
1900 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1901}
1902
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001903/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1904Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001905 SourceLocation LabLoc,
1906 IdentifierInfo *LabelII) {
1907 // Look up the record for this label identifier.
1908 LabelStmt *&LabelDecl = LabelMap[LabelII];
1909
1910 // If we haven't seen this label yet, create a forward reference.
1911 if (LabelDecl == 0)
1912 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1913
1914 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001915 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1916 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001917}
1918
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001919Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001920 SourceLocation RPLoc) { // "({..})"
1921 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1922 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1923 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1924
1925 // FIXME: there are a variety of strange constraints to enforce here, for
1926 // example, it is not possible to goto into a stmt expression apparently.
1927 // More semantic analysis is needed.
1928
1929 // FIXME: the last statement in the compount stmt has its value used. We
1930 // should not warn about it being unused.
1931
1932 // If there are sub stmts in the compound stmt, take the type of the last one
1933 // as the type of the stmtexpr.
1934 QualType Ty = Context.VoidTy;
1935
1936 if (!Compound->body_empty())
1937 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1938 Ty = LastExpr->getType();
1939
1940 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1941}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001942
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001943Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001944 SourceLocation TypeLoc,
1945 TypeTy *argty,
1946 OffsetOfComponent *CompPtr,
1947 unsigned NumComponents,
1948 SourceLocation RPLoc) {
1949 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1950 assert(!ArgTy.isNull() && "Missing type argument!");
1951
1952 // We must have at least one component that refers to the type, and the first
1953 // one is known to be a field designator. Verify that the ArgTy represents
1954 // a struct/union/class.
1955 if (!ArgTy->isRecordType())
1956 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1957
1958 // Otherwise, create a compound literal expression as the base, and
1959 // iteratively process the offsetof designators.
Chris Lattner386ab8a2008-01-02 21:46:24 +00001960 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001961
Chris Lattnerb37522e2007-08-31 21:49:13 +00001962 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1963 // GCC extension, diagnose them.
1964 if (NumComponents != 1)
1965 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1966 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1967
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001968 for (unsigned i = 0; i != NumComponents; ++i) {
1969 const OffsetOfComponent &OC = CompPtr[i];
1970 if (OC.isBrackets) {
1971 // Offset of an array sub-field. TODO: Should we allow vector elements?
1972 const ArrayType *AT = Res->getType()->getAsArrayType();
1973 if (!AT) {
1974 delete Res;
1975 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1976 Res->getType().getAsString());
1977 }
1978
Chris Lattner2af6a802007-08-30 17:59:59 +00001979 // FIXME: C++: Verify that operator[] isn't overloaded.
1980
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001981 // C99 6.5.2.1p1
1982 Expr *Idx = static_cast<Expr*>(OC.U.E);
1983 if (!Idx->getType()->isIntegerType())
1984 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1985 Idx->getSourceRange());
1986
1987 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1988 continue;
1989 }
1990
1991 const RecordType *RC = Res->getType()->getAsRecordType();
1992 if (!RC) {
1993 delete Res;
1994 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1995 Res->getType().getAsString());
1996 }
1997
1998 // Get the decl corresponding to this.
1999 RecordDecl *RD = RC->getDecl();
2000 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2001 if (!MemberDecl)
2002 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2003 OC.U.IdentInfo->getName(),
2004 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002005
2006 // FIXME: C++: Verify that MemberDecl isn't a static field.
2007 // FIXME: Verify that MemberDecl isn't a bitfield.
2008
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002009 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
2010 }
2011
2012 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2013 BuiltinLoc);
2014}
2015
2016
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002017Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002018 TypeTy *arg1, TypeTy *arg2,
2019 SourceLocation RPLoc) {
2020 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2021 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2022
2023 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2024
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002025 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002026}
2027
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002028Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002029 ExprTy *expr1, ExprTy *expr2,
2030 SourceLocation RPLoc) {
2031 Expr *CondExpr = static_cast<Expr*>(cond);
2032 Expr *LHSExpr = static_cast<Expr*>(expr1);
2033 Expr *RHSExpr = static_cast<Expr*>(expr2);
2034
2035 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2036
2037 // The conditional expression is required to be a constant expression.
2038 llvm::APSInt condEval(32);
2039 SourceLocation ExpLoc;
2040 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2041 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2042 CondExpr->getSourceRange());
2043
2044 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2045 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2046 RHSExpr->getType();
2047 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2048}
2049
Anders Carlsson36760332007-10-15 20:28:48 +00002050Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2051 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002052 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002053 Expr *E = static_cast<Expr*>(expr);
2054 QualType T = QualType::getFromOpaquePtr(type);
2055
2056 InitBuiltinVaListType();
2057
Chris Lattner005ed752008-01-04 18:04:52 +00002058 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2059 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002060 return Diag(E->getLocStart(),
2061 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2062 E->getType().getAsString(),
2063 E->getSourceRange());
2064
2065 // FIXME: Warn if a non-POD type is passed in.
2066
2067 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2068}
2069
Chris Lattner005ed752008-01-04 18:04:52 +00002070bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2071 SourceLocation Loc,
2072 QualType DstType, QualType SrcType,
2073 Expr *SrcExpr, const char *Flavor) {
2074 // Decode the result (notice that AST's are still created for extensions).
2075 bool isInvalid = false;
2076 unsigned DiagKind;
2077 switch (ConvTy) {
2078 default: assert(0 && "Unknown conversion type");
2079 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002080 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002081 DiagKind = diag::ext_typecheck_convert_pointer_int;
2082 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002083 case IntToPointer:
2084 DiagKind = diag::ext_typecheck_convert_int_pointer;
2085 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002086 case IncompatiblePointer:
2087 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2088 break;
2089 case FunctionVoidPointer:
2090 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2091 break;
2092 case CompatiblePointerDiscardsQualifiers:
2093 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2094 break;
2095 case Incompatible:
2096 DiagKind = diag::err_typecheck_convert_incompatible;
2097 isInvalid = true;
2098 break;
2099 }
2100
2101 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2102 SrcExpr->getSourceRange());
2103 return isInvalid;
2104}
2105