blob: 436510f763c06ad6938aac21b8abc6842d17d625 [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) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000118 default: assert(0 && "Unknown simple primary expr!");
119 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
120 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
121 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000122 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000123
124 // Verify that this is in a function context.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000125 if (CurFunctionDecl == 0 && CurMethodDecl == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000126 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000127
Chris Lattner7e637512008-01-12 08:14:25 +0000128 // Pre-defined identifiers are of type char[x], where x is the length of the
129 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000130 unsigned Length;
131 if (CurFunctionDecl)
132 Length = CurFunctionDecl->getIdentifier()->getLength();
133 else
134 Length = CurMethodDecl->getSelector().getName().size();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000135
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000136 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000137 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000138 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000139 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000140}
141
Steve Naroff87d58b42007-09-16 03:34:24 +0000142Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000143 llvm::SmallString<16> CharBuffer;
144 CharBuffer.resize(Tok.getLength());
145 const char *ThisTokBegin = &CharBuffer[0];
146 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
147
148 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
149 Tok.getLocation(), PP);
150 if (Literal.hadError())
151 return ExprResult(true);
152 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
153 Tok.getLocation());
154}
155
Steve Naroff87d58b42007-09-16 03:34:24 +0000156Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000157 // fast path for a single digit (which is quite common). A single digit
158 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
159 if (Tok.getLength() == 1) {
160 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
161
Chris Lattner3496d522007-09-04 02:45:27 +0000162 unsigned IntSize = static_cast<unsigned>(
163 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000164 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
165 Context.IntTy,
166 Tok.getLocation()));
167 }
168 llvm::SmallString<512> IntegerBuffer;
169 IntegerBuffer.resize(Tok.getLength());
170 const char *ThisTokBegin = &IntegerBuffer[0];
171
172 // Get the spelling of the token, which eliminates trigraphs, etc.
173 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
174 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
175 Tok.getLocation(), PP);
176 if (Literal.hadError)
177 return ExprResult(true);
178
Chris Lattner1de66eb2007-08-26 03:42:43 +0000179 Expr *Res;
180
181 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000182 QualType Ty;
183 const llvm::fltSemantics *Format;
184 uint64_t Size; unsigned Align;
185
186 if (Literal.isFloat) {
187 Ty = Context.FloatTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000188 Context.Target.getFloatInfo(Size, Align, Format,
189 Context.getFullLoc(Tok.getLocation()));
190
Chris Lattner858eece2007-09-22 18:29:59 +0000191 } else if (Literal.isLong) {
192 Ty = Context.LongDoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000193 Context.Target.getLongDoubleInfo(Size, Align, Format,
194 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000195 } else {
196 Ty = Context.DoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000197 Context.Target.getDoubleInfo(Size, Align, Format,
198 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000199 }
200
Ted Kremenekddedbe22007-11-29 00:56:49 +0000201 // isExact will be set by GetFloatValue().
202 bool isExact = false;
203
204 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
205 Ty, Tok.getLocation());
206
Chris Lattner1de66eb2007-08-26 03:42:43 +0000207 } else if (!Literal.isIntegerLiteral()) {
208 return ExprResult(true);
209 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000210 QualType t;
211
Neil Booth7421e9c2007-08-29 22:00:19 +0000212 // long long is a C99 feature.
213 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000214 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000215 Diag(Tok.getLocation(), diag::ext_longlong);
216
Chris Lattner4b009652007-07-25 00:24:17 +0000217 // Get the value in the widest-possible width.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000218 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
219 Context.getFullLoc(Tok.getLocation())), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000220
221 if (Literal.GetIntegerValue(ResultVal)) {
222 // If this value didn't fit into uintmax_t, warn and force to ull.
223 Diag(Tok.getLocation(), diag::warn_integer_too_large);
224 t = Context.UnsignedLongLongTy;
225 assert(Context.getTypeSize(t, Tok.getLocation()) ==
226 ResultVal.getBitWidth() && "long long is not intmax_t?");
227 } else {
228 // If this value fits into a ULL, try to figure out what else it fits into
229 // according to the rules of C99 6.4.4.1p5.
230
231 // Octal, Hexadecimal, and integers with a U suffix are allowed to
232 // be an unsigned int.
233 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
234
235 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000236 if (!Literal.isLong && !Literal.isLongLong) {
237 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000238 unsigned IntSize = static_cast<unsigned>(
239 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000240 // Does it fit in a unsigned int?
241 if (ResultVal.isIntN(IntSize)) {
242 // Does it fit in a signed int?
243 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
244 t = Context.IntTy;
245 else if (AllowUnsigned)
246 t = Context.UnsignedIntTy;
247 }
248
249 if (!t.isNull())
250 ResultVal.trunc(IntSize);
251 }
252
253 // Are long/unsigned long possibilities?
254 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000255 unsigned LongSize = static_cast<unsigned>(
256 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000257
258 // Does it fit in a unsigned long?
259 if (ResultVal.isIntN(LongSize)) {
260 // Does it fit in a signed long?
261 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
262 t = Context.LongTy;
263 else if (AllowUnsigned)
264 t = Context.UnsignedLongTy;
265 }
266 if (!t.isNull())
267 ResultVal.trunc(LongSize);
268 }
269
270 // Finally, check long long if needed.
271 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000272 unsigned LongLongSize = static_cast<unsigned>(
273 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000274
275 // Does it fit in a unsigned long long?
276 if (ResultVal.isIntN(LongLongSize)) {
277 // Does it fit in a signed long long?
278 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
279 t = Context.LongLongTy;
280 else if (AllowUnsigned)
281 t = Context.UnsignedLongLongTy;
282 }
283 }
284
285 // If we still couldn't decide a type, we probably have something that
286 // does not fit in a signed long long, but has no U suffix.
287 if (t.isNull()) {
288 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
289 t = Context.UnsignedLongLongTy;
290 }
291 }
292
Chris Lattner1de66eb2007-08-26 03:42:43 +0000293 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000294 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000295
296 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
297 if (Literal.isImaginary)
298 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
299
300 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000301}
302
Steve Naroff87d58b42007-09-16 03:34:24 +0000303Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000304 ExprTy *Val) {
305 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000306 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000307 return new ParenExpr(L, R, e);
308}
309
310/// The UsualUnaryConversions() function is *not* called by this routine.
311/// See C99 6.3.2.1p[2-4] for more details.
312QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
313 SourceLocation OpLoc, bool isSizeof) {
314 // C99 6.5.3.4p1:
315 if (isa<FunctionType>(exprType) && isSizeof)
316 // alignof(function) is allowed.
317 Diag(OpLoc, diag::ext_sizeof_function_type);
318 else if (exprType->isVoidType())
319 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
320 else if (exprType->isIncompleteType()) {
321 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
322 diag::err_alignof_incomplete_type,
323 exprType.getAsString());
324 return QualType(); // error
325 }
326 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
327 return Context.getSizeType();
328}
329
330Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000331ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000332 SourceLocation LPLoc, TypeTy *Ty,
333 SourceLocation RPLoc) {
334 // If error parsing type, ignore.
335 if (Ty == 0) return true;
336
337 // Verify that this is a valid expression.
338 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
339
340 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
341
342 if (resultType.isNull())
343 return true;
344 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
345}
346
Chris Lattner5110ad52007-08-24 21:41:10 +0000347QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000348 DefaultFunctionArrayConversion(V);
349
Chris Lattnera16e42d2007-08-26 05:39:26 +0000350 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000351 if (const ComplexType *CT = V->getType()->getAsComplexType())
352 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000353
354 // Otherwise they pass through real integer and floating point types here.
355 if (V->getType()->isArithmeticType())
356 return V->getType();
357
358 // Reject anything else.
359 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
360 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000361}
362
363
Chris Lattner4b009652007-07-25 00:24:17 +0000364
Steve Naroff87d58b42007-09-16 03:34:24 +0000365Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000366 tok::TokenKind Kind,
367 ExprTy *Input) {
368 UnaryOperator::Opcode Opc;
369 switch (Kind) {
370 default: assert(0 && "Unknown unary op!");
371 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
372 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
373 }
374 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
375 if (result.isNull())
376 return true;
377 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
378}
379
380Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000381ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000382 ExprTy *Idx, SourceLocation RLoc) {
383 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
384
385 // Perform default conversions.
386 DefaultFunctionArrayConversion(LHSExp);
387 DefaultFunctionArrayConversion(RHSExp);
388
389 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
390
391 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000392 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000393 // in the subscript position. As a result, we need to derive the array base
394 // and index from the expression types.
395 Expr *BaseExpr, *IndexExpr;
396 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000397 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000398 BaseExpr = LHSExp;
399 IndexExpr = RHSExp;
400 // FIXME: need to deal with const...
401 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000402 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000403 // Handle the uncommon case of "123[Ptr]".
404 BaseExpr = RHSExp;
405 IndexExpr = LHSExp;
406 // FIXME: need to deal with const...
407 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000408 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
409 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000410 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000411
412 // Component access limited to variables (reject vec4.rg[1]).
413 if (!isa<DeclRefExpr>(BaseExpr))
414 return Diag(LLoc, diag::err_ocuvector_component_access,
415 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000416 // FIXME: need to deal with const...
417 ResultType = VTy->getElementType();
418 } else {
419 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
420 RHSExp->getSourceRange());
421 }
422 // C99 6.5.2.1p1
423 if (!IndexExpr->getType()->isIntegerType())
424 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
425 IndexExpr->getSourceRange());
426
427 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
428 // the following check catches trying to index a pointer to a function (e.g.
429 // void (*)(int)). Functions are not objects in C99.
430 if (!ResultType->isObjectType())
431 return Diag(BaseExpr->getLocStart(),
432 diag::err_typecheck_subscript_not_object,
433 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
434
435 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
436}
437
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000438QualType Sema::
439CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
440 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000441 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000442
443 // The vector accessor can't exceed the number of elements.
444 const char *compStr = CompName.getName();
445 if (strlen(compStr) > vecType->getNumElements()) {
446 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
447 baseType.getAsString(), SourceRange(CompLoc));
448 return QualType();
449 }
450 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000451 if (vecType->getPointAccessorIdx(*compStr) != -1) {
452 do
453 compStr++;
454 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
455 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
456 do
457 compStr++;
458 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
459 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
460 do
461 compStr++;
462 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
463 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000464
465 if (*compStr) {
466 // We didn't get to the end of the string. This means the component names
467 // didn't come from the same set *or* we encountered an illegal name.
468 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
469 std::string(compStr,compStr+1), SourceRange(CompLoc));
470 return QualType();
471 }
472 // Each component accessor can't exceed the vector type.
473 compStr = CompName.getName();
474 while (*compStr) {
475 if (vecType->isAccessorWithinNumElements(*compStr))
476 compStr++;
477 else
478 break;
479 }
480 if (*compStr) {
481 // We didn't get to the end of the string. This means a component accessor
482 // exceeds the number of elements in the vector.
483 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
484 baseType.getAsString(), SourceRange(CompLoc));
485 return QualType();
486 }
487 // The component accessor looks fine - now we need to compute the actual type.
488 // The vector type is implied by the component accessor. For example,
489 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
490 unsigned CompSize = strlen(CompName.getName());
491 if (CompSize == 1)
492 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000493
494 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
495 // Now look up the TypeDefDecl from the vector type. Without this,
496 // diagostics look bad. We want OCU vector types to appear built-in.
497 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
498 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
499 return Context.getTypedefType(OCUVectorDecls[i]);
500 }
501 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000502}
503
Chris Lattner4b009652007-07-25 00:24:17 +0000504Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000505ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000506 tok::TokenKind OpKind, SourceLocation MemberLoc,
507 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000508 Expr *BaseExpr = static_cast<Expr *>(Base);
509 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000510
511 // Perform default conversions.
512 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000513
Steve Naroff2cb66382007-07-26 03:11:44 +0000514 QualType BaseType = BaseExpr->getType();
515 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000516
Chris Lattner4b009652007-07-25 00:24:17 +0000517 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000518 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000519 BaseType = PT->getPointeeType();
520 else
521 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
522 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000523 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000524 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000525 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000526 RecordDecl *RDecl = RTy->getDecl();
527 if (RTy->isIncompleteType())
528 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
529 BaseExpr->getSourceRange());
530 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000531 FieldDecl *MemberDecl = RDecl->getMember(&Member);
532 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000533 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
534 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000535 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
536 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000537 // Component access limited to variables (reject vec4.rg.g).
538 if (!isa<DeclRefExpr>(BaseExpr))
539 return Diag(OpLoc, diag::err_ocuvector_component_access,
540 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000541 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
542 if (ret.isNull())
543 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000544 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000545 } else if (BaseType->isObjCInterfaceType()) {
546 ObjCInterfaceDecl *IFace;
547 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
548 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000549 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000550 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
551 ObjCInterfaceDecl *clsDeclared;
552 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000553 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
554 OpKind==tok::arrow);
555 }
556 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
557 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000558}
559
Steve Naroff87d58b42007-09-16 03:34:24 +0000560/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000561/// This provides the location of the left/right parens and a list of comma
562/// locations.
563Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000564ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000565 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000566 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
567 Expr *Fn = static_cast<Expr *>(fn);
568 Expr **Args = reinterpret_cast<Expr**>(args);
569 assert(Fn && "no function call expression");
570
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000571 // Make the call expr early, before semantic checks. This guarantees cleanup
572 // of arguments and function on error.
573 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
574 Context.BoolTy, RParenLoc));
575
576 // Promote the function operand.
577 TheCall->setCallee(UsualUnaryConversions(Fn));
578
Chris Lattner4b009652007-07-25 00:24:17 +0000579 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
580 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000581 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000582 if (PT == 0)
583 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
584 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000585 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
586 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000587 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
588 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000589
590 // We know the result type of the call, set it.
591 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000592
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000593 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000594 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
595 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000596 unsigned NumArgsInProto = Proto->getNumArgs();
597 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000598
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000599 // If too few arguments are available, don't make the call.
600 if (NumArgs < NumArgsInProto)
601 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
602 Fn->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000603
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000604 // If too many are passed and not variadic, error on the extras and drop
605 // them.
606 if (NumArgs > NumArgsInProto) {
607 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000608 Diag(Args[NumArgsInProto]->getLocStart(),
609 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
610 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000611 Args[NumArgs-1]->getLocEnd()));
612 // This deletes the extra arguments.
613 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000614 }
615 NumArgsToCheck = NumArgsInProto;
616 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000617
Chris Lattner4b009652007-07-25 00:24:17 +0000618 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000619 for (unsigned i = 0; i != NumArgsToCheck; i++) {
620 Expr *Arg = Args[i];
Chris Lattner005ed752008-01-04 18:04:52 +0000621 QualType ProtoArgType = Proto->getArgType(i);
622 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000623
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000624 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000625 AssignConvertType ConvTy =
626 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000627 TheCall->setArg(i, Arg);
628
Chris Lattner005ed752008-01-04 18:04:52 +0000629 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
630 ArgType, Arg, "passing"))
631 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000632 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000633
634 // If this is a variadic call, handle args passed through "...".
635 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000636 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000637 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
638 Expr *Arg = Args[i];
639 DefaultArgumentPromotion(Arg);
640 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000641 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000642 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000643 } else {
644 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
645
Steve Naroffdb65e052007-08-28 23:30:39 +0000646 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000647 for (unsigned i = 0; i != NumArgs; i++) {
648 Expr *Arg = Args[i];
649 DefaultArgumentPromotion(Arg);
650 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000651 }
Chris Lattner4b009652007-07-25 00:24:17 +0000652 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000653
Chris Lattner2e64c072007-08-10 20:18:51 +0000654 // Do special checking on direct calls to functions.
655 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
656 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
657 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000658 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000659 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000660
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000661 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000662}
663
664Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000665ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000666 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000667 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000668 QualType literalType = QualType::getFromOpaquePtr(Ty);
669 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000670 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000671 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000672
Steve Naroffcb69fb72007-12-10 22:44:33 +0000673 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Narofff0b23542008-01-10 22:15:12 +0000674 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000675 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000676
677 bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
678 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000679 if (CheckForConstantInitializer(literalExpr, literalType))
680 return true;
681 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000682 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000683}
684
685Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000686ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000687 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000688 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000689
Steve Naroff0acc9c92007-09-15 18:49:24 +0000690 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000691 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000692
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000693 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
694 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
695 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000696}
697
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000698bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000699 assert(VectorTy->isVectorType() && "Not a vector type!");
700
701 if (Ty->isVectorType() || Ty->isIntegerType()) {
702 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
703 Context.getTypeSize(Ty, SourceLocation()))
704 return Diag(R.getBegin(),
705 Ty->isVectorType() ?
706 diag::err_invalid_conversion_between_vectors :
707 diag::err_invalid_conversion_between_vector_and_integer,
708 VectorTy.getAsString().c_str(),
709 Ty.getAsString().c_str(), R);
710 } else
711 return Diag(R.getBegin(),
712 diag::err_invalid_conversion_between_vector_and_scalar,
713 VectorTy.getAsString().c_str(),
714 Ty.getAsString().c_str(), R);
715
716 return false;
717}
718
Chris Lattner4b009652007-07-25 00:24:17 +0000719Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000720ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000721 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000722 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000723
724 Expr *castExpr = static_cast<Expr*>(Op);
725 QualType castType = QualType::getFromOpaquePtr(Ty);
726
Steve Naroff68adb482007-08-31 00:32:44 +0000727 UsualUnaryConversions(castExpr);
728
Chris Lattner4b009652007-07-25 00:24:17 +0000729 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
730 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000731 if (!castType->isVoidType()) { // Cast to void allows any expr type.
732 if (!castType->isScalarType())
733 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
734 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000735 if (!castExpr->getType()->isScalarType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000736 return Diag(castExpr->getLocStart(),
737 diag::err_typecheck_expect_scalar_operand,
738 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000739
740 if (castExpr->getType()->isVectorType()) {
741 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
742 castExpr->getType(), castType))
743 return true;
744 } else if (castType->isVectorType()) {
745 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
746 castType, castExpr->getType()))
747 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000748 }
Chris Lattner4b009652007-07-25 00:24:17 +0000749 }
750 return new CastExpr(castType, castExpr, LParenLoc);
751}
752
Steve Naroff144667e2007-10-18 05:13:08 +0000753// promoteExprToType - a helper function to ensure we create exactly one
754// ImplicitCastExpr.
755static void promoteExprToType(Expr *&expr, QualType type) {
756 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
757 impCast->setType(type);
758 else
759 expr = new ImplicitCastExpr(type, expr);
760 return;
761}
762
Chris Lattner98a425c2007-11-26 01:40:58 +0000763/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
764/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000765inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
766 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
767 UsualUnaryConversions(cond);
768 UsualUnaryConversions(lex);
769 UsualUnaryConversions(rex);
770 QualType condT = cond->getType();
771 QualType lexT = lex->getType();
772 QualType rexT = rex->getType();
773
774 // first, check the condition.
775 if (!condT->isScalarType()) { // C99 6.5.15p2
776 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
777 condT.getAsString());
778 return QualType();
779 }
Chris Lattner992ae932008-01-06 22:42:25 +0000780
781 // Now check the two expressions.
782
783 // If both operands have arithmetic type, do the usual arithmetic conversions
784 // to find a common type: C99 6.5.15p3,5.
785 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000786 UsualArithmeticConversions(lex, rex);
787 return lex->getType();
788 }
Chris Lattner992ae932008-01-06 22:42:25 +0000789
790 // If both operands are the same structure or union type, the result is that
791 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000792 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000793 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000794 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000795 // "If both the operands have structure or union type, the result has
796 // that type." This implies that CV qualifiers are dropped.
797 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000798 }
Chris Lattner992ae932008-01-06 22:42:25 +0000799
800 // C99 6.5.15p5: "If both operands have void type, the result has void type."
801 if (lexT->isVoidType() && rexT->isVoidType())
802 return lexT.getUnqualifiedType();
Steve Naroff12ebf272008-01-08 01:11:38 +0000803
804 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
805 // the type of the other operand."
806 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
807 promoteExprToType(rex, lexT); // promote the null to a pointer.
808 return lexT;
809 }
810 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
811 promoteExprToType(lex, rexT); // promote the null to a pointer.
812 return rexT;
813 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000814 // Handle the case where both operands are pointers before we handle null
815 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000816 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
817 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
818 // get the "pointed to" types
819 QualType lhptee = LHSPT->getPointeeType();
820 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000821
Chris Lattner71225142007-07-31 21:27:01 +0000822 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
823 if (lhptee->isVoidType() &&
824 (rhptee->isObjectType() || rhptee->isIncompleteType()))
825 return lexT;
826 if (rhptee->isVoidType() &&
827 (lhptee->isObjectType() || lhptee->isIncompleteType()))
828 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000829
Steve Naroff85f0dc52007-10-15 20:41:53 +0000830 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
831 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000832 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
833 lexT.getAsString(), rexT.getAsString(),
834 lex->getSourceRange(), rex->getSourceRange());
835 return lexT; // FIXME: this is an _ext - is this return o.k?
836 }
837 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000838 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
839 // differently qualified versions of compatible types, the result type is
840 // a pointer to an appropriately qualified version of the *composite*
841 // type.
Chris Lattner0ac51632008-01-06 22:50:31 +0000842 // FIXME: Need to return the composite type.
843 return lexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000844 }
Chris Lattner4b009652007-07-25 00:24:17 +0000845 }
Chris Lattner71225142007-07-31 21:27:01 +0000846
Chris Lattner992ae932008-01-06 22:42:25 +0000847 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000848 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
849 lexT.getAsString(), rexT.getAsString(),
850 lex->getSourceRange(), rex->getSourceRange());
851 return QualType();
852}
853
Steve Naroff87d58b42007-09-16 03:34:24 +0000854/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000855/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000856Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000857 SourceLocation ColonLoc,
858 ExprTy *Cond, ExprTy *LHS,
859 ExprTy *RHS) {
860 Expr *CondExpr = (Expr *) Cond;
861 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000862
863 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
864 // was the condition.
865 bool isLHSNull = LHSExpr == 0;
866 if (isLHSNull)
867 LHSExpr = CondExpr;
868
Chris Lattner4b009652007-07-25 00:24:17 +0000869 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
870 RHSExpr, QuestionLoc);
871 if (result.isNull())
872 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000873 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
874 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000875}
876
Steve Naroffdb65e052007-08-28 23:30:39 +0000877/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
878/// do not have a prototype. Integer promotions are performed on each
879/// argument, and arguments that have type float are promoted to double.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000880void Sema::DefaultArgumentPromotion(Expr *&Expr) {
881 QualType Ty = Expr->getType();
882 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000883
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000884 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
885 promoteExprToType(Expr, Context.IntTy);
886 if (Ty == Context.FloatTy)
887 promoteExprToType(Expr, Context.DoubleTy);
Steve Naroffdb65e052007-08-28 23:30:39 +0000888}
889
Chris Lattner4b009652007-07-25 00:24:17 +0000890/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
891void Sema::DefaultFunctionArrayConversion(Expr *&e) {
892 QualType t = e->getType();
893 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
894
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000895 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000896 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
897 t = e->getType();
898 }
899 if (t->isFunctionType())
900 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000901 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000902 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
903}
904
905/// UsualUnaryConversion - Performs various conversions that are common to most
906/// operators (C99 6.3). The conversions of array and function types are
907/// sometimes surpressed. For example, the array->pointer conversion doesn't
908/// apply if the array is an argument to the sizeof or address (&) operators.
909/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000910Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
911 QualType Ty = Expr->getType();
912 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000913
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000914 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
915 promoteExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
916 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000917 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000918 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
919 promoteExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000920 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000921 DefaultFunctionArrayConversion(Expr);
922
923 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000924}
925
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000926/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000927/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
928/// routine returns the first non-arithmetic type found. The client is
929/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000930QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
931 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000932 if (!isCompAssign) {
933 UsualUnaryConversions(lhsExpr);
934 UsualUnaryConversions(rhsExpr);
935 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000936 // For conversion purposes, we ignore any qualifiers.
937 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000938 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
939 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000940
941 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000942 if (lhs == rhs)
943 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000944
945 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
946 // The caller can deal with this (e.g. pointer + int).
947 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000948 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000949
950 // At this point, we have two different arithmetic types.
951
952 // Handle complex types first (C99 6.3.1.8p1).
953 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff36e35e62008-01-15 01:41:59 +0000954 // Handle GCC complex int extension first.
955 // FIXME: need to verify these conversion rules are consistent with GCC.
956 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
957 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
958
959 if (lhsComplexInt && rhsComplexInt) {
960 if (Context.maxIntegerType(lhsComplexInt->getElementType(),
961 rhsComplexInt->getElementType()) == lhs) {
962 if (!isCompAssign) promoteExprToType(rhsExpr, lhs); // convert the rhs
963 return lhs;
964 }
965 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
966 return rhs;
967 } else if (lhsComplexInt && rhs->isIntegerType()) {
968 // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000969 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
970 return lhs;
Steve Naroff36e35e62008-01-15 01:41:59 +0000971 } else if (rhsComplexInt && lhs->isIntegerType()) {
972 // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000973 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
974 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000975 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000976 // This handles complex/complex, complex/float, or float/complex.
977 // When both operands are complex, the shorter operand is converted to the
978 // type of the longer, and that is the type of the result. This corresponds
979 // to what is done when combining two real floating-point operands.
980 // The fun begins when size promotion occur across type domains.
981 // From H&S 6.3.4: When one operand is complex and the other is a real
982 // floating-point type, the less precise type is converted, within it's
983 // real or complex domain, to the precision of the other type. For example,
984 // when combining a "long double" with a "double _Complex", the
985 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000986 int result = Context.compareFloatingType(lhs, rhs);
987
988 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000989 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
990 if (!isCompAssign)
991 promoteExprToType(rhsExpr, rhs);
992 } else if (result < 0) { // The right side is bigger, convert lhs.
993 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
994 if (!isCompAssign)
995 promoteExprToType(lhsExpr, lhs);
996 }
997 // At this point, lhs and rhs have the same rank/size. Now, make sure the
998 // domains match. This is a requirement for our implementation, C99
999 // does not require this promotion.
1000 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1001 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001002 if (!isCompAssign)
1003 promoteExprToType(lhsExpr, rhs);
1004 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001005 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001006 if (!isCompAssign)
1007 promoteExprToType(rhsExpr, lhs);
1008 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001009 }
Chris Lattner4b009652007-07-25 00:24:17 +00001010 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001011 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001012 }
1013 // Now handle "real" floating types (i.e. float, double, long double).
1014 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1015 // if we have an integer operand, the result is the real floating type.
1016 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001017 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1018 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001019 }
1020 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001021 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1022 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001023 }
1024 // We have two real floating types, float/complex combos were handled above.
1025 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001026 int result = Context.compareFloatingType(lhs, rhs);
1027
1028 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001029 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1030 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001031 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001032 if (result < 0) { // convert the lhs
1033 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1034 return rhs;
1035 }
1036 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001037 }
1038 // Finally, we have two differing integer types.
1039 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001040 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1041 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001042 }
Steve Naroff8f708362007-08-24 19:07:16 +00001043 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1044 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001045}
1046
1047// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1048// being closely modeled after the C99 spec:-). The odd characteristic of this
1049// routine is it effectively iqnores the qualifiers on the top level pointee.
1050// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1051// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001052Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001053Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1054 QualType lhptee, rhptee;
1055
1056 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001057 lhptee = lhsType->getAsPointerType()->getPointeeType();
1058 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001059
1060 // make sure we operate on the canonical type
1061 lhptee = lhptee.getCanonicalType();
1062 rhptee = rhptee.getCanonicalType();
1063
Chris Lattner005ed752008-01-04 18:04:52 +00001064 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001065
1066 // C99 6.5.16.1p1: This following citation is common to constraints
1067 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1068 // qualifiers of the type *pointed to* by the right;
1069 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1070 rhptee.getQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001071 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001072
1073 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1074 // incomplete type and the other is a pointer to a qualified or unqualified
1075 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001076 if (lhptee->isVoidType()) {
1077 if (rhptee->isObjectType() || rhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001078 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001079
1080 // As an extension, we allow cast to/from void* to function pointer.
1081 if (rhptee->isFunctionType())
1082 return FunctionVoidPointer;
1083 }
1084
1085 if (rhptee->isVoidType()) {
1086 if (lhptee->isObjectType() || lhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001087 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001088
1089 // As an extension, we allow cast to/from void* to function pointer.
1090 if (lhptee->isFunctionType())
1091 return FunctionVoidPointer;
1092 }
1093
Chris Lattner4b009652007-07-25 00:24:17 +00001094 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1095 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001096 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1097 rhptee.getUnqualifiedType()))
1098 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001099 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001100}
1101
1102/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1103/// has code to accommodate several GCC extensions when type checking
1104/// pointers. Here are some objectionable examples that GCC considers warnings:
1105///
1106/// int a, *pint;
1107/// short *pshort;
1108/// struct foo *pfoo;
1109///
1110/// pint = pshort; // warning: assignment from incompatible pointer type
1111/// a = pint; // warning: assignment makes integer from pointer without a cast
1112/// pint = a; // warning: assignment makes pointer from integer without a cast
1113/// pint = pfoo; // warning: assignment from incompatible pointer type
1114///
1115/// As a result, the code for dealing with pointers is more complex than the
1116/// C99 spec dictates.
1117/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1118///
Chris Lattner005ed752008-01-04 18:04:52 +00001119Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001120Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001121 // Get canonical types. We're not formatting these types, just comparing
1122 // them.
1123 lhsType = lhsType.getCanonicalType();
1124 rhsType = rhsType.getCanonicalType();
1125
1126 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001127 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001128
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001129 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001130 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001131 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001132 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001133 }
Chris Lattner1853da22008-01-04 23:18:45 +00001134
Ted Kremenek42730c52008-01-07 19:49:32 +00001135 if (lhsType->isObjCQualifiedIdType()
1136 || rhsType->isObjCQualifiedIdType()) {
1137 if (Context.ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001138 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001139 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001140 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001141
1142 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1143 // For OCUVector, allow vector splats; float -> <n x float>
1144 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1145 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1146 return Compatible;
1147 }
1148
1149 // If LHS and RHS are both vectors of integer or both vectors of floating
1150 // point types, and the total vector length is the same, allow the
1151 // conversion. This is a bitcast; no bits are changed but the result type
1152 // is different.
1153 if (getLangOptions().LaxVectorConversions &&
1154 lhsType->isVectorType() && rhsType->isVectorType()) {
1155 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1156 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
1157 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1158 Context.getTypeSize(rhsType, SourceLocation()))
Nate Begemanec2d1062007-12-30 02:59:45 +00001159 return Compatible;
1160 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001161 }
1162 return Incompatible;
1163 }
1164
1165 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001166 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001167
1168 if (lhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001169 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001170 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001171
1172 if (rhsType->isPointerType())
1173 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001174 return Incompatible;
1175 }
1176
1177 if (rhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001178 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1179 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001180 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001181
1182 if (lhsType->isPointerType())
1183 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001184 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001185 }
1186
1187 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001188 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001189 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001190 }
1191 return Incompatible;
1192}
1193
Chris Lattner005ed752008-01-04 18:04:52 +00001194Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001195Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001196 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1197 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001198 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001199 && rExpr->isNullPointerConstant(Context)) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001200 promoteExprToType(rExpr, lhsType);
1201 return Compatible;
1202 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001203 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001204 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001205 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001206 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001207 //
1208 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1209 // are better understood.
1210 if (!lhsType->isReferenceType())
1211 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001212
Chris Lattner005ed752008-01-04 18:04:52 +00001213 Sema::AssignConvertType result =
1214 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001215
1216 // C99 6.5.16.1p2: The value of the right operand is converted to the
1217 // type of the assignment expression.
1218 if (rExpr->getType() != lhsType)
1219 promoteExprToType(rExpr, lhsType);
1220 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001221}
1222
Chris Lattner005ed752008-01-04 18:04:52 +00001223Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001224Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1225 return CheckAssignmentConstraints(lhsType, rhsType);
1226}
1227
Chris Lattner2c8bff72007-12-12 05:47:28 +00001228QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001229 Diag(loc, diag::err_typecheck_invalid_operands,
1230 lex->getType().getAsString(), rex->getType().getAsString(),
1231 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001232 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001233}
1234
1235inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1236 Expr *&rex) {
1237 QualType lhsType = lex->getType(), rhsType = rex->getType();
1238
1239 // make sure the vector types are identical.
1240 if (lhsType == rhsType)
1241 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001242
1243 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1244 // promote the rhs to the vector type.
1245 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1246 if (V->getElementType().getCanonicalType().getTypePtr()
1247 == rhsType.getCanonicalType().getTypePtr()) {
1248 promoteExprToType(rex, lhsType);
1249 return lhsType;
1250 }
1251 }
1252
1253 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1254 // promote the lhs to the vector type.
1255 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1256 if (V->getElementType().getCanonicalType().getTypePtr()
1257 == lhsType.getCanonicalType().getTypePtr()) {
1258 promoteExprToType(lex, rhsType);
1259 return rhsType;
1260 }
1261 }
1262
Chris Lattner4b009652007-07-25 00:24:17 +00001263 // You cannot convert between vector values of different size.
1264 Diag(loc, diag::err_typecheck_vector_not_convertable,
1265 lex->getType().getAsString(), rex->getType().getAsString(),
1266 lex->getSourceRange(), rex->getSourceRange());
1267 return QualType();
1268}
1269
1270inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001271 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001272{
1273 QualType lhsType = lex->getType(), rhsType = rex->getType();
1274
1275 if (lhsType->isVectorType() || rhsType->isVectorType())
1276 return CheckVectorOperands(loc, lex, rex);
1277
Steve Naroff8f708362007-08-24 19:07:16 +00001278 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001279
Chris Lattner4b009652007-07-25 00:24:17 +00001280 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001281 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001282 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001283}
1284
1285inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001286 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001287{
1288 QualType lhsType = lex->getType(), rhsType = rex->getType();
1289
Steve Naroff8f708362007-08-24 19:07:16 +00001290 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001291
Chris Lattner4b009652007-07-25 00:24:17 +00001292 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001293 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001294 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001295}
1296
1297inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001298 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001299{
1300 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1301 return CheckVectorOperands(loc, lex, rex);
1302
Steve Naroff8f708362007-08-24 19:07:16 +00001303 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001304
1305 // handle the common case first (both operands are arithmetic).
1306 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001307 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001308
1309 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1310 return lex->getType();
1311 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1312 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001313 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001314}
1315
1316inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001317 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001318{
1319 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1320 return CheckVectorOperands(loc, lex, rex);
1321
Steve Naroff8f708362007-08-24 19:07:16 +00001322 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001323
Chris Lattnerf6da2912007-12-09 21:53:25 +00001324 // Enforce type constraints: C99 6.5.6p3.
1325
1326 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001327 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001328 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001329
1330 // Either ptr - int or ptr - ptr.
1331 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1332 // The LHS must be an object type, not incomplete, function, etc.
1333 if (!LHSPTy->getPointeeType()->isObjectType()) {
1334 // Handle the GNU void* extension.
1335 if (LHSPTy->getPointeeType()->isVoidType()) {
1336 Diag(loc, diag::ext_gnu_void_ptr,
1337 lex->getSourceRange(), rex->getSourceRange());
1338 } else {
1339 Diag(loc, diag::err_typecheck_sub_ptr_object,
1340 lex->getType().getAsString(), lex->getSourceRange());
1341 return QualType();
1342 }
1343 }
1344
1345 // The result type of a pointer-int computation is the pointer type.
1346 if (rex->getType()->isIntegerType())
1347 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001348
Chris Lattnerf6da2912007-12-09 21:53:25 +00001349 // Handle pointer-pointer subtractions.
1350 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1351 // RHS must be an object type, unless void (GNU).
1352 if (!RHSPTy->getPointeeType()->isObjectType()) {
1353 // Handle the GNU void* extension.
1354 if (RHSPTy->getPointeeType()->isVoidType()) {
1355 if (!LHSPTy->getPointeeType()->isVoidType())
1356 Diag(loc, diag::ext_gnu_void_ptr,
1357 lex->getSourceRange(), rex->getSourceRange());
1358 } else {
1359 Diag(loc, diag::err_typecheck_sub_ptr_object,
1360 rex->getType().getAsString(), rex->getSourceRange());
1361 return QualType();
1362 }
1363 }
1364
1365 // Pointee types must be compatible.
1366 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1367 RHSPTy->getPointeeType())) {
1368 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1369 lex->getType().getAsString(), rex->getType().getAsString(),
1370 lex->getSourceRange(), rex->getSourceRange());
1371 return QualType();
1372 }
1373
1374 return Context.getPointerDiffType();
1375 }
1376 }
1377
Chris Lattner2c8bff72007-12-12 05:47:28 +00001378 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001379}
1380
1381inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattner2c8bff72007-12-12 05:47:28 +00001382 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1383 // C99 6.5.7p2: Each of the operands shall have integer type.
1384 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1385 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001386
Chris Lattner2c8bff72007-12-12 05:47:28 +00001387 // Shifts don't perform usual arithmetic conversions, they just do integer
1388 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001389 if (!isCompAssign)
1390 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001391 UsualUnaryConversions(rex);
1392
1393 // "The type of the result is that of the promoted left operand."
1394 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001395}
1396
Chris Lattner254f3bc2007-08-26 01:18:55 +00001397inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1398 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001399{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001400 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001401 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1402 UsualArithmeticConversions(lex, rex);
1403 else {
1404 UsualUnaryConversions(lex);
1405 UsualUnaryConversions(rex);
1406 }
Chris Lattner4b009652007-07-25 00:24:17 +00001407 QualType lType = lex->getType();
1408 QualType rType = rex->getType();
1409
Ted Kremenek486509e2007-10-29 17:13:39 +00001410 // For non-floating point types, check for self-comparisons of the form
1411 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1412 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001413 if (!lType->isFloatingType()) {
1414 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1415 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1416 if (DRL->getDecl() == DRR->getDecl())
1417 Diag(loc, diag::warn_selfcomparison);
1418 }
1419
Chris Lattner254f3bc2007-08-26 01:18:55 +00001420 if (isRelational) {
1421 if (lType->isRealType() && rType->isRealType())
1422 return Context.IntTy;
1423 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001424 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001425 if (lType->isFloatingType()) {
1426 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001427 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001428 }
1429
Chris Lattner254f3bc2007-08-26 01:18:55 +00001430 if (lType->isArithmeticType() && rType->isArithmeticType())
1431 return Context.IntTy;
1432 }
Chris Lattner4b009652007-07-25 00:24:17 +00001433
Chris Lattner22be8422007-08-26 01:10:14 +00001434 bool LHSIsNull = lex->isNullPointerConstant(Context);
1435 bool RHSIsNull = rex->isNullPointerConstant(Context);
1436
Chris Lattner254f3bc2007-08-26 01:18:55 +00001437 // All of the following pointer related warnings are GCC extensions, except
1438 // when handling null pointer constants. One day, we can consider making them
1439 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001440 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001441
1442 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1443 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1444 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001445 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1446 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001447 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1448 lType.getAsString(), rType.getAsString(),
1449 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001450 }
Chris Lattner22be8422007-08-26 01:10:14 +00001451 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001452 return Context.IntTy;
1453 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001454 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
1455 && Context.ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001456 promoteExprToType(rex, lType);
1457 return Context.IntTy;
1458 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001459 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001460 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001461 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1462 lType.getAsString(), rType.getAsString(),
1463 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001464 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001465 return Context.IntTy;
1466 }
1467 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001468 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001469 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1470 lType.getAsString(), rType.getAsString(),
1471 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001472 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001473 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001474 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001475 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001476}
1477
Chris Lattner4b009652007-07-25 00:24:17 +00001478inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001479 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001480{
1481 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1482 return CheckVectorOperands(loc, lex, rex);
1483
Steve Naroff8f708362007-08-24 19:07:16 +00001484 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001485
1486 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001487 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001488 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001489}
1490
1491inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1492 Expr *&lex, Expr *&rex, SourceLocation loc)
1493{
1494 UsualUnaryConversions(lex);
1495 UsualUnaryConversions(rex);
1496
1497 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1498 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001499 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001500}
1501
1502inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001503 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001504{
1505 QualType lhsType = lex->getType();
1506 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001507 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1508
1509 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001510 case Expr::MLV_Valid:
1511 break;
1512 case Expr::MLV_ConstQualified:
1513 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1514 return QualType();
1515 case Expr::MLV_ArrayType:
1516 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1517 lhsType.getAsString(), lex->getSourceRange());
1518 return QualType();
1519 case Expr::MLV_NotObjectType:
1520 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1521 lhsType.getAsString(), lex->getSourceRange());
1522 return QualType();
1523 case Expr::MLV_InvalidExpression:
1524 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1525 lex->getSourceRange());
1526 return QualType();
1527 case Expr::MLV_IncompleteType:
1528 case Expr::MLV_IncompleteVoidType:
1529 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1530 lhsType.getAsString(), lex->getSourceRange());
1531 return QualType();
1532 case Expr::MLV_DuplicateVectorComponents:
1533 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1534 lex->getSourceRange());
1535 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001536 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001537
Chris Lattner005ed752008-01-04 18:04:52 +00001538 AssignConvertType ConvTy;
1539 if (compoundType.isNull())
1540 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1541 else
1542 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1543
1544 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1545 rex, "assigning"))
1546 return QualType();
1547
Chris Lattner4b009652007-07-25 00:24:17 +00001548 // C99 6.5.16p3: The type of an assignment expression is the type of the
1549 // left operand unless the left operand has qualified type, in which case
1550 // it is the unqualified version of the type of the left operand.
1551 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1552 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001553 // C++ 5.17p1: the type of the assignment expression is that of its left
1554 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001555 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001556}
1557
1558inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1559 Expr *&lex, Expr *&rex, SourceLocation loc) {
1560 UsualUnaryConversions(rex);
1561 return rex->getType();
1562}
1563
1564/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1565/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1566QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1567 QualType resType = op->getType();
1568 assert(!resType.isNull() && "no type for increment/decrement expression");
1569
Steve Naroffd30e1932007-08-24 17:20:07 +00001570 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001571 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001572 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1573 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1574 resType.getAsString(), op->getSourceRange());
1575 return QualType();
1576 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001577 } else if (!resType->isRealType()) {
1578 if (resType->isComplexType())
1579 // C99 does not support ++/-- on complex types.
1580 Diag(OpLoc, diag::ext_integer_increment_complex,
1581 resType.getAsString(), op->getSourceRange());
1582 else {
1583 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1584 resType.getAsString(), op->getSourceRange());
1585 return QualType();
1586 }
Chris Lattner4b009652007-07-25 00:24:17 +00001587 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001588 // At this point, we know we have a real, complex or pointer type.
1589 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001590 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1591 if (mlval != Expr::MLV_Valid) {
1592 // FIXME: emit a more precise diagnostic...
1593 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1594 op->getSourceRange());
1595 return QualType();
1596 }
1597 return resType;
1598}
1599
1600/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1601/// This routine allows us to typecheck complex/recursive expressions
1602/// where the declaration is needed for type checking. Here are some
1603/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1604static Decl *getPrimaryDeclaration(Expr *e) {
1605 switch (e->getStmtClass()) {
1606 case Stmt::DeclRefExprClass:
1607 return cast<DeclRefExpr>(e)->getDecl();
1608 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001609 // Fields cannot be declared with a 'register' storage class.
1610 // &X->f is always ok, even if X is declared register.
1611 if (cast<MemberExpr>(e)->isArrow())
1612 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001613 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1614 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001615 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001616 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001617 case Stmt::UnaryOperatorClass:
1618 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1619 case Stmt::ParenExprClass:
1620 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001621 case Stmt::ImplicitCastExprClass:
1622 // &X[4] when X is an array, has an implicit cast from array to pointer.
1623 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001624 default:
1625 return 0;
1626 }
1627}
1628
1629/// CheckAddressOfOperand - The operand of & must be either a function
1630/// designator or an lvalue designating an object. If it is an lvalue, the
1631/// object cannot be declared with storage class register or be a bit field.
1632/// Note: The usual conversions are *not* applied to the operand of the &
1633/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1634QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001635 if (getLangOptions().C99) {
1636 // Implement C99-only parts of addressof rules.
1637 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1638 if (uOp->getOpcode() == UnaryOperator::Deref)
1639 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1640 // (assuming the deref expression is valid).
1641 return uOp->getSubExpr()->getType();
1642 }
1643 // Technically, there should be a check for array subscript
1644 // expressions here, but the result of one is always an lvalue anyway.
1645 }
Chris Lattner4b009652007-07-25 00:24:17 +00001646 Decl *dcl = getPrimaryDeclaration(op);
1647 Expr::isLvalueResult lval = op->isLvalue();
1648
1649 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001650 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1651 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001652 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1653 op->getSourceRange());
1654 return QualType();
1655 }
1656 } else if (dcl) {
1657 // We have an lvalue with a decl. Make sure the decl is not declared
1658 // with the register storage-class specifier.
1659 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1660 if (vd->getStorageClass() == VarDecl::Register) {
1661 Diag(OpLoc, diag::err_typecheck_address_of_register,
1662 op->getSourceRange());
1663 return QualType();
1664 }
1665 } else
1666 assert(0 && "Unknown/unexpected decl type");
1667
1668 // FIXME: add check for bitfields!
1669 }
1670 // If the operand has type "type", the result has type "pointer to type".
1671 return Context.getPointerType(op->getType());
1672}
1673
1674QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1675 UsualUnaryConversions(op);
1676 QualType qType = op->getType();
1677
Chris Lattner7931f4a2007-07-31 16:53:04 +00001678 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001679 // Note that per both C89 and C99, this is always legal, even
1680 // if ptype is an incomplete type or void.
1681 // It would be possible to warn about dereferencing a
1682 // void pointer, but it's completely well-defined,
1683 // and such a warning is unlikely to catch any mistakes.
1684 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001685 }
1686 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1687 qType.getAsString(), op->getSourceRange());
1688 return QualType();
1689}
1690
1691static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1692 tok::TokenKind Kind) {
1693 BinaryOperator::Opcode Opc;
1694 switch (Kind) {
1695 default: assert(0 && "Unknown binop!");
1696 case tok::star: Opc = BinaryOperator::Mul; break;
1697 case tok::slash: Opc = BinaryOperator::Div; break;
1698 case tok::percent: Opc = BinaryOperator::Rem; break;
1699 case tok::plus: Opc = BinaryOperator::Add; break;
1700 case tok::minus: Opc = BinaryOperator::Sub; break;
1701 case tok::lessless: Opc = BinaryOperator::Shl; break;
1702 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1703 case tok::lessequal: Opc = BinaryOperator::LE; break;
1704 case tok::less: Opc = BinaryOperator::LT; break;
1705 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1706 case tok::greater: Opc = BinaryOperator::GT; break;
1707 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1708 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1709 case tok::amp: Opc = BinaryOperator::And; break;
1710 case tok::caret: Opc = BinaryOperator::Xor; break;
1711 case tok::pipe: Opc = BinaryOperator::Or; break;
1712 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1713 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1714 case tok::equal: Opc = BinaryOperator::Assign; break;
1715 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1716 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1717 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1718 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1719 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1720 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1721 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1722 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1723 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1724 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1725 case tok::comma: Opc = BinaryOperator::Comma; break;
1726 }
1727 return Opc;
1728}
1729
1730static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1731 tok::TokenKind Kind) {
1732 UnaryOperator::Opcode Opc;
1733 switch (Kind) {
1734 default: assert(0 && "Unknown unary op!");
1735 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1736 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1737 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1738 case tok::star: Opc = UnaryOperator::Deref; break;
1739 case tok::plus: Opc = UnaryOperator::Plus; break;
1740 case tok::minus: Opc = UnaryOperator::Minus; break;
1741 case tok::tilde: Opc = UnaryOperator::Not; break;
1742 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1743 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1744 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1745 case tok::kw___real: Opc = UnaryOperator::Real; break;
1746 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1747 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1748 }
1749 return Opc;
1750}
1751
1752// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001753Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001754 ExprTy *LHS, ExprTy *RHS) {
1755 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1756 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1757
Steve Naroff87d58b42007-09-16 03:34:24 +00001758 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1759 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001760
1761 QualType ResultTy; // Result type of the binary operator.
1762 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1763
1764 switch (Opc) {
1765 default:
1766 assert(0 && "Unknown binary expr!");
1767 case BinaryOperator::Assign:
1768 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1769 break;
1770 case BinaryOperator::Mul:
1771 case BinaryOperator::Div:
1772 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1773 break;
1774 case BinaryOperator::Rem:
1775 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1776 break;
1777 case BinaryOperator::Add:
1778 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1779 break;
1780 case BinaryOperator::Sub:
1781 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1782 break;
1783 case BinaryOperator::Shl:
1784 case BinaryOperator::Shr:
1785 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1786 break;
1787 case BinaryOperator::LE:
1788 case BinaryOperator::LT:
1789 case BinaryOperator::GE:
1790 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001791 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001792 break;
1793 case BinaryOperator::EQ:
1794 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001795 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001796 break;
1797 case BinaryOperator::And:
1798 case BinaryOperator::Xor:
1799 case BinaryOperator::Or:
1800 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1801 break;
1802 case BinaryOperator::LAnd:
1803 case BinaryOperator::LOr:
1804 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1805 break;
1806 case BinaryOperator::MulAssign:
1807 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001808 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001809 if (!CompTy.isNull())
1810 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1811 break;
1812 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001813 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001814 if (!CompTy.isNull())
1815 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1816 break;
1817 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001818 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001819 if (!CompTy.isNull())
1820 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1821 break;
1822 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001823 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001824 if (!CompTy.isNull())
1825 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1826 break;
1827 case BinaryOperator::ShlAssign:
1828 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001829 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001830 if (!CompTy.isNull())
1831 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1832 break;
1833 case BinaryOperator::AndAssign:
1834 case BinaryOperator::XorAssign:
1835 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001836 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001837 if (!CompTy.isNull())
1838 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1839 break;
1840 case BinaryOperator::Comma:
1841 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1842 break;
1843 }
1844 if (ResultTy.isNull())
1845 return true;
1846 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001847 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001848 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001849 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001850}
1851
1852// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001853Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001854 ExprTy *input) {
1855 Expr *Input = (Expr*)input;
1856 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1857 QualType resultType;
1858 switch (Opc) {
1859 default:
1860 assert(0 && "Unimplemented unary expr!");
1861 case UnaryOperator::PreInc:
1862 case UnaryOperator::PreDec:
1863 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1864 break;
1865 case UnaryOperator::AddrOf:
1866 resultType = CheckAddressOfOperand(Input, OpLoc);
1867 break;
1868 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001869 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001870 resultType = CheckIndirectionOperand(Input, OpLoc);
1871 break;
1872 case UnaryOperator::Plus:
1873 case UnaryOperator::Minus:
1874 UsualUnaryConversions(Input);
1875 resultType = Input->getType();
1876 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1877 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1878 resultType.getAsString());
1879 break;
1880 case UnaryOperator::Not: // bitwise complement
1881 UsualUnaryConversions(Input);
1882 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001883 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1884 if (!resultType->isIntegerType()) {
1885 if (resultType->isComplexType())
1886 // C99 does not support '~' for complex conjugation.
1887 Diag(OpLoc, diag::ext_integer_complement_complex,
1888 resultType.getAsString());
1889 else
1890 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1891 resultType.getAsString());
1892 }
Chris Lattner4b009652007-07-25 00:24:17 +00001893 break;
1894 case UnaryOperator::LNot: // logical negation
1895 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1896 DefaultFunctionArrayConversion(Input);
1897 resultType = Input->getType();
1898 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1899 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1900 resultType.getAsString());
1901 // LNot always has type int. C99 6.5.3.3p5.
1902 resultType = Context.IntTy;
1903 break;
1904 case UnaryOperator::SizeOf:
1905 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1906 break;
1907 case UnaryOperator::AlignOf:
1908 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1909 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001910 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001911 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001912 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001913 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001914 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001915 resultType = Input->getType();
1916 break;
1917 }
1918 if (resultType.isNull())
1919 return true;
1920 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1921}
1922
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001923/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1924Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001925 SourceLocation LabLoc,
1926 IdentifierInfo *LabelII) {
1927 // Look up the record for this label identifier.
1928 LabelStmt *&LabelDecl = LabelMap[LabelII];
1929
1930 // If we haven't seen this label yet, create a forward reference.
1931 if (LabelDecl == 0)
1932 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1933
1934 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001935 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1936 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001937}
1938
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001939Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001940 SourceLocation RPLoc) { // "({..})"
1941 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1942 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1943 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1944
1945 // FIXME: there are a variety of strange constraints to enforce here, for
1946 // example, it is not possible to goto into a stmt expression apparently.
1947 // More semantic analysis is needed.
1948
1949 // FIXME: the last statement in the compount stmt has its value used. We
1950 // should not warn about it being unused.
1951
1952 // If there are sub stmts in the compound stmt, take the type of the last one
1953 // as the type of the stmtexpr.
1954 QualType Ty = Context.VoidTy;
1955
1956 if (!Compound->body_empty())
1957 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1958 Ty = LastExpr->getType();
1959
1960 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1961}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001962
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001963Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001964 SourceLocation TypeLoc,
1965 TypeTy *argty,
1966 OffsetOfComponent *CompPtr,
1967 unsigned NumComponents,
1968 SourceLocation RPLoc) {
1969 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1970 assert(!ArgTy.isNull() && "Missing type argument!");
1971
1972 // We must have at least one component that refers to the type, and the first
1973 // one is known to be a field designator. Verify that the ArgTy represents
1974 // a struct/union/class.
1975 if (!ArgTy->isRecordType())
1976 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1977
1978 // Otherwise, create a compound literal expression as the base, and
1979 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00001980 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001981
Chris Lattnerb37522e2007-08-31 21:49:13 +00001982 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1983 // GCC extension, diagnose them.
1984 if (NumComponents != 1)
1985 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1986 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1987
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001988 for (unsigned i = 0; i != NumComponents; ++i) {
1989 const OffsetOfComponent &OC = CompPtr[i];
1990 if (OC.isBrackets) {
1991 // Offset of an array sub-field. TODO: Should we allow vector elements?
1992 const ArrayType *AT = Res->getType()->getAsArrayType();
1993 if (!AT) {
1994 delete Res;
1995 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1996 Res->getType().getAsString());
1997 }
1998
Chris Lattner2af6a802007-08-30 17:59:59 +00001999 // FIXME: C++: Verify that operator[] isn't overloaded.
2000
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002001 // C99 6.5.2.1p1
2002 Expr *Idx = static_cast<Expr*>(OC.U.E);
2003 if (!Idx->getType()->isIntegerType())
2004 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2005 Idx->getSourceRange());
2006
2007 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2008 continue;
2009 }
2010
2011 const RecordType *RC = Res->getType()->getAsRecordType();
2012 if (!RC) {
2013 delete Res;
2014 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2015 Res->getType().getAsString());
2016 }
2017
2018 // Get the decl corresponding to this.
2019 RecordDecl *RD = RC->getDecl();
2020 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2021 if (!MemberDecl)
2022 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2023 OC.U.IdentInfo->getName(),
2024 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002025
2026 // FIXME: C++: Verify that MemberDecl isn't a static field.
2027 // FIXME: Verify that MemberDecl isn't a bitfield.
2028
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002029 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
2030 }
2031
2032 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2033 BuiltinLoc);
2034}
2035
2036
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002037Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002038 TypeTy *arg1, TypeTy *arg2,
2039 SourceLocation RPLoc) {
2040 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2041 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2042
2043 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2044
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002045 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002046}
2047
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002048Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002049 ExprTy *expr1, ExprTy *expr2,
2050 SourceLocation RPLoc) {
2051 Expr *CondExpr = static_cast<Expr*>(cond);
2052 Expr *LHSExpr = static_cast<Expr*>(expr1);
2053 Expr *RHSExpr = static_cast<Expr*>(expr2);
2054
2055 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2056
2057 // The conditional expression is required to be a constant expression.
2058 llvm::APSInt condEval(32);
2059 SourceLocation ExpLoc;
2060 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2061 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2062 CondExpr->getSourceRange());
2063
2064 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2065 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2066 RHSExpr->getType();
2067 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2068}
2069
Anders Carlsson36760332007-10-15 20:28:48 +00002070Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2071 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002072 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002073 Expr *E = static_cast<Expr*>(expr);
2074 QualType T = QualType::getFromOpaquePtr(type);
2075
2076 InitBuiltinVaListType();
2077
Chris Lattner005ed752008-01-04 18:04:52 +00002078 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2079 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002080 return Diag(E->getLocStart(),
2081 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2082 E->getType().getAsString(),
2083 E->getSourceRange());
2084
2085 // FIXME: Warn if a non-POD type is passed in.
2086
2087 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2088}
2089
Chris Lattner005ed752008-01-04 18:04:52 +00002090bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2091 SourceLocation Loc,
2092 QualType DstType, QualType SrcType,
2093 Expr *SrcExpr, const char *Flavor) {
2094 // Decode the result (notice that AST's are still created for extensions).
2095 bool isInvalid = false;
2096 unsigned DiagKind;
2097 switch (ConvTy) {
2098 default: assert(0 && "Unknown conversion type");
2099 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002100 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002101 DiagKind = diag::ext_typecheck_convert_pointer_int;
2102 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002103 case IntToPointer:
2104 DiagKind = diag::ext_typecheck_convert_int_pointer;
2105 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002106 case IncompatiblePointer:
2107 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2108 break;
2109 case FunctionVoidPointer:
2110 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2111 break;
2112 case CompatiblePointerDiscardsQualifiers:
2113 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2114 break;
2115 case Incompatible:
2116 DiagKind = diag::err_typecheck_convert_incompatible;
2117 isInvalid = true;
2118 break;
2119 }
2120
2121 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2122 SrcExpr->getSourceRange());
2123 return isInvalid;
2124}
2125