blob: 3d60866c015c9ac643fc1b0a0f70483b83b19ca6 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000015#include "SemaUtil.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000018#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000023#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Steve Naroff87d58b42007-09-16 03:34:24 +000028/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000029/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000035Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000036 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +000045
46 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000047 if (Literal.Pascal && Literal.GetStringLength() > 256)
48 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
49 SourceRange(StringToks[0].getLocation(),
50 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000051
Chris Lattnera6dcce32008-02-11 00:02:17 +000052 QualType StrTy = Context.CharTy;
53 // FIXME: handle wchar_t
54 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
55
56 // Get an array type for the string, according to C99 6.4.5. This includes
57 // the nul terminator character as well as the string length for pascal
58 // strings.
59 StrTy = Context.getConstantArrayType(StrTy,
60 llvm::APInt(32, Literal.GetStringLength()+1),
61 ArrayType::Normal, 0);
62
Chris Lattner4b009652007-07-25 00:24:17 +000063 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
64 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +000065 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000066 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000067 StringToks[NumStringToks-1].getLocation());
68}
69
70
Steve Naroff0acc9c92007-09-15 18:49:24 +000071/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000072/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
73/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000074Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000075 IdentifierInfo &II,
76 bool HasTrailingLParen) {
77 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000078 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000079 if (D == 0) {
80 // Otherwise, this could be an implicitly declared function reference (legal
81 // in C90, extension in C99).
82 if (HasTrailingLParen &&
83 // Not in C++.
84 !getLangOptions().CPlusPlus)
85 D = ImplicitlyDefineFunction(Loc, II, S);
86 else {
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000087 if (CurMethodDecl) {
Ted Kremenek42730c52008-01-07 19:49:32 +000088 ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
89 ObjCInterfaceDecl *clsDeclared;
90 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
Steve Naroff6b759ce2007-11-15 02:58:25 +000091 IdentifierInfo &II = Context.Idents.get("self");
92 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
93 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
94 static_cast<Expr*>(SelfExpr.Val), true, true);
95 }
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000096 }
Chris Lattner4b009652007-07-25 00:24:17 +000097 // If this name wasn't predeclared and if this is not a function call,
98 // diagnose the problem.
99 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
100 }
101 }
Steve Naroff91b03f72007-08-28 03:03:08 +0000102 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +0000103 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000104 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000105 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000106 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000107 }
Chris Lattner4b009652007-07-25 00:24:17 +0000108 if (isa<TypedefDecl>(D))
109 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000110 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000111 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000112
113 assert(0 && "Invalid decl");
114 abort();
115}
116
Steve Naroff87d58b42007-09-16 03:34:24 +0000117Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000118 tok::TokenKind Kind) {
119 PreDefinedExpr::IdentType IT;
120
121 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000122 default: assert(0 && "Unknown simple primary expr!");
123 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
124 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
125 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000126 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000127
128 // Verify that this is in a function context.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000129 if (CurFunctionDecl == 0 && CurMethodDecl == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000130 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000131
Chris Lattner7e637512008-01-12 08:14:25 +0000132 // Pre-defined identifiers are of type char[x], where x is the length of the
133 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000134 unsigned Length;
135 if (CurFunctionDecl)
136 Length = CurFunctionDecl->getIdentifier()->getLength();
137 else
Fariborz Jahaniandcecd5c2008-01-17 17:37:26 +0000138 Length = CurMethodDecl->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000139
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000140 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000141 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000142 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000143 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000144}
145
Steve Naroff87d58b42007-09-16 03:34:24 +0000146Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000147 llvm::SmallString<16> CharBuffer;
148 CharBuffer.resize(Tok.getLength());
149 const char *ThisTokBegin = &CharBuffer[0];
150 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
151
152 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
153 Tok.getLocation(), PP);
154 if (Literal.hadError())
155 return ExprResult(true);
156 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
157 Tok.getLocation());
158}
159
Steve Naroff87d58b42007-09-16 03:34:24 +0000160Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000161 // fast path for a single digit (which is quite common). A single digit
162 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
163 if (Tok.getLength() == 1) {
164 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
165
Chris Lattner3496d522007-09-04 02:45:27 +0000166 unsigned IntSize = static_cast<unsigned>(
167 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000168 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
169 Context.IntTy,
170 Tok.getLocation()));
171 }
172 llvm::SmallString<512> IntegerBuffer;
173 IntegerBuffer.resize(Tok.getLength());
174 const char *ThisTokBegin = &IntegerBuffer[0];
175
176 // Get the spelling of the token, which eliminates trigraphs, etc.
177 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
178 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
179 Tok.getLocation(), PP);
180 if (Literal.hadError)
181 return ExprResult(true);
182
Chris Lattner1de66eb2007-08-26 03:42:43 +0000183 Expr *Res;
184
185 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000186 QualType Ty;
187 const llvm::fltSemantics *Format;
188 uint64_t Size; unsigned Align;
189
190 if (Literal.isFloat) {
191 Ty = Context.FloatTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000192 Context.Target.getFloatInfo(Size, Align, Format,
193 Context.getFullLoc(Tok.getLocation()));
194
Chris Lattner858eece2007-09-22 18:29:59 +0000195 } else if (Literal.isLong) {
196 Ty = Context.LongDoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000197 Context.Target.getLongDoubleInfo(Size, Align, Format,
198 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000199 } else {
200 Ty = Context.DoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000201 Context.Target.getDoubleInfo(Size, Align, Format,
202 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000203 }
204
Ted Kremenekddedbe22007-11-29 00:56:49 +0000205 // isExact will be set by GetFloatValue().
206 bool isExact = false;
207
208 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
209 Ty, Tok.getLocation());
210
Chris Lattner1de66eb2007-08-26 03:42:43 +0000211 } else if (!Literal.isIntegerLiteral()) {
212 return ExprResult(true);
213 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000214 QualType t;
215
Neil Booth7421e9c2007-08-29 22:00:19 +0000216 // long long is a C99 feature.
217 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000218 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000219 Diag(Tok.getLocation(), diag::ext_longlong);
220
Chris Lattner4b009652007-07-25 00:24:17 +0000221 // Get the value in the widest-possible width.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000222 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
223 Context.getFullLoc(Tok.getLocation())), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000224
225 if (Literal.GetIntegerValue(ResultVal)) {
226 // If this value didn't fit into uintmax_t, warn and force to ull.
227 Diag(Tok.getLocation(), diag::warn_integer_too_large);
228 t = Context.UnsignedLongLongTy;
229 assert(Context.getTypeSize(t, Tok.getLocation()) ==
230 ResultVal.getBitWidth() && "long long is not intmax_t?");
231 } else {
232 // If this value fits into a ULL, try to figure out what else it fits into
233 // according to the rules of C99 6.4.4.1p5.
234
235 // Octal, Hexadecimal, and integers with a U suffix are allowed to
236 // be an unsigned int.
237 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
238
239 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000240 if (!Literal.isLong && !Literal.isLongLong) {
241 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000242 unsigned IntSize = static_cast<unsigned>(
243 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000244 // Does it fit in a unsigned int?
245 if (ResultVal.isIntN(IntSize)) {
246 // Does it fit in a signed int?
247 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
248 t = Context.IntTy;
249 else if (AllowUnsigned)
250 t = Context.UnsignedIntTy;
251 }
252
253 if (!t.isNull())
254 ResultVal.trunc(IntSize);
255 }
256
257 // Are long/unsigned long possibilities?
258 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000259 unsigned LongSize = static_cast<unsigned>(
260 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000261
262 // Does it fit in a unsigned long?
263 if (ResultVal.isIntN(LongSize)) {
264 // Does it fit in a signed long?
265 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
266 t = Context.LongTy;
267 else if (AllowUnsigned)
268 t = Context.UnsignedLongTy;
269 }
270 if (!t.isNull())
271 ResultVal.trunc(LongSize);
272 }
273
274 // Finally, check long long if needed.
275 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000276 unsigned LongLongSize = static_cast<unsigned>(
277 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000278
279 // Does it fit in a unsigned long long?
280 if (ResultVal.isIntN(LongLongSize)) {
281 // Does it fit in a signed long long?
282 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
283 t = Context.LongLongTy;
284 else if (AllowUnsigned)
285 t = Context.UnsignedLongLongTy;
286 }
287 }
288
289 // If we still couldn't decide a type, we probably have something that
290 // does not fit in a signed long long, but has no U suffix.
291 if (t.isNull()) {
292 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
293 t = Context.UnsignedLongLongTy;
294 }
295 }
296
Chris Lattner1de66eb2007-08-26 03:42:43 +0000297 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000298 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000299
300 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
301 if (Literal.isImaginary)
302 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
303
304 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000305}
306
Steve Naroff87d58b42007-09-16 03:34:24 +0000307Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000308 ExprTy *Val) {
309 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000310 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000311 return new ParenExpr(L, R, e);
312}
313
314/// The UsualUnaryConversions() function is *not* called by this routine.
315/// See C99 6.3.2.1p[2-4] for more details.
316QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
317 SourceLocation OpLoc, bool isSizeof) {
318 // C99 6.5.3.4p1:
319 if (isa<FunctionType>(exprType) && isSizeof)
320 // alignof(function) is allowed.
321 Diag(OpLoc, diag::ext_sizeof_function_type);
322 else if (exprType->isVoidType())
323 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
324 else if (exprType->isIncompleteType()) {
325 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
326 diag::err_alignof_incomplete_type,
327 exprType.getAsString());
328 return QualType(); // error
329 }
330 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
331 return Context.getSizeType();
332}
333
334Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000335ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000336 SourceLocation LPLoc, TypeTy *Ty,
337 SourceLocation RPLoc) {
338 // If error parsing type, ignore.
339 if (Ty == 0) return true;
340
341 // Verify that this is a valid expression.
342 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
343
344 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
345
346 if (resultType.isNull())
347 return true;
348 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
349}
350
Chris Lattner5110ad52007-08-24 21:41:10 +0000351QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000352 DefaultFunctionArrayConversion(V);
353
Chris Lattnera16e42d2007-08-26 05:39:26 +0000354 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000355 if (const ComplexType *CT = V->getType()->getAsComplexType())
356 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000357
358 // Otherwise they pass through real integer and floating point types here.
359 if (V->getType()->isArithmeticType())
360 return V->getType();
361
362 // Reject anything else.
363 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
364 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000365}
366
367
Chris Lattner4b009652007-07-25 00:24:17 +0000368
Steve Naroff87d58b42007-09-16 03:34:24 +0000369Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000370 tok::TokenKind Kind,
371 ExprTy *Input) {
372 UnaryOperator::Opcode Opc;
373 switch (Kind) {
374 default: assert(0 && "Unknown unary op!");
375 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
376 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
377 }
378 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
379 if (result.isNull())
380 return true;
381 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
382}
383
384Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000385ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000386 ExprTy *Idx, SourceLocation RLoc) {
387 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
388
389 // Perform default conversions.
390 DefaultFunctionArrayConversion(LHSExp);
391 DefaultFunctionArrayConversion(RHSExp);
392
393 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
394
395 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000396 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000397 // in the subscript position. As a result, we need to derive the array base
398 // and index from the expression types.
399 Expr *BaseExpr, *IndexExpr;
400 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000401 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000402 BaseExpr = LHSExp;
403 IndexExpr = RHSExp;
404 // FIXME: need to deal with const...
405 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000406 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000407 // Handle the uncommon case of "123[Ptr]".
408 BaseExpr = RHSExp;
409 IndexExpr = LHSExp;
410 // FIXME: need to deal with const...
411 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000412 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
413 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000414 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000415
416 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman506806b2008-02-19 01:11:03 +0000417 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
Steve Naroff89345522007-08-03 22:40:33 +0000418 return Diag(LLoc, diag::err_ocuvector_component_access,
419 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000420 // FIXME: need to deal with const...
421 ResultType = VTy->getElementType();
422 } else {
423 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
424 RHSExp->getSourceRange());
425 }
426 // C99 6.5.2.1p1
427 if (!IndexExpr->getType()->isIntegerType())
428 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
429 IndexExpr->getSourceRange());
430
431 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
432 // the following check catches trying to index a pointer to a function (e.g.
433 // void (*)(int)). Functions are not objects in C99.
434 if (!ResultType->isObjectType())
435 return Diag(BaseExpr->getLocStart(),
436 diag::err_typecheck_subscript_not_object,
437 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
438
439 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
440}
441
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000442QualType Sema::
443CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
444 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000445 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000446
447 // The vector accessor can't exceed the number of elements.
448 const char *compStr = CompName.getName();
449 if (strlen(compStr) > vecType->getNumElements()) {
450 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
451 baseType.getAsString(), SourceRange(CompLoc));
452 return QualType();
453 }
454 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000455 if (vecType->getPointAccessorIdx(*compStr) != -1) {
456 do
457 compStr++;
458 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
459 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
460 do
461 compStr++;
462 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
463 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
464 do
465 compStr++;
466 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
467 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000468
469 if (*compStr) {
470 // We didn't get to the end of the string. This means the component names
471 // didn't come from the same set *or* we encountered an illegal name.
472 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
473 std::string(compStr,compStr+1), SourceRange(CompLoc));
474 return QualType();
475 }
476 // Each component accessor can't exceed the vector type.
477 compStr = CompName.getName();
478 while (*compStr) {
479 if (vecType->isAccessorWithinNumElements(*compStr))
480 compStr++;
481 else
482 break;
483 }
484 if (*compStr) {
485 // We didn't get to the end of the string. This means a component accessor
486 // exceeds the number of elements in the vector.
487 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
488 baseType.getAsString(), SourceRange(CompLoc));
489 return QualType();
490 }
491 // The component accessor looks fine - now we need to compute the actual type.
492 // The vector type is implied by the component accessor. For example,
493 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
494 unsigned CompSize = strlen(CompName.getName());
495 if (CompSize == 1)
496 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000497
498 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
499 // Now look up the TypeDefDecl from the vector type. Without this,
500 // diagostics look bad. We want OCU vector types to appear built-in.
501 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
502 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
503 return Context.getTypedefType(OCUVectorDecls[i]);
504 }
505 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000506}
507
Chris Lattner4b009652007-07-25 00:24:17 +0000508Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000509ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000510 tok::TokenKind OpKind, SourceLocation MemberLoc,
511 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000512 Expr *BaseExpr = static_cast<Expr *>(Base);
513 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000514
515 // Perform default conversions.
516 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000517
Steve Naroff2cb66382007-07-26 03:11:44 +0000518 QualType BaseType = BaseExpr->getType();
519 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000520
Chris Lattner4b009652007-07-25 00:24:17 +0000521 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000522 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000523 BaseType = PT->getPointeeType();
524 else
525 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
526 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000527 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000528 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000529 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000530 RecordDecl *RDecl = RTy->getDecl();
531 if (RTy->isIncompleteType())
532 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
533 BaseExpr->getSourceRange());
534 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000535 FieldDecl *MemberDecl = RDecl->getMember(&Member);
536 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000537 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
538 SourceRange(MemberLoc));
Eli Friedman76b49832008-02-06 22:48:16 +0000539
540 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000541 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000542 QualType MemberType = MemberDecl->getType();
543 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000544 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000545 MemberType = MemberType.getQualifiedType(combinedQualifiers);
546
547 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
548 MemberLoc, MemberType);
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000549 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000550 // Component access limited to variables (reject vec4.rg.g).
551 if (!isa<DeclRefExpr>(BaseExpr))
552 return Diag(OpLoc, diag::err_ocuvector_component_access,
553 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000554 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
555 if (ret.isNull())
556 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000557 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000558 } else if (BaseType->isObjCInterfaceType()) {
559 ObjCInterfaceDecl *IFace;
560 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
561 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000562 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000563 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
564 ObjCInterfaceDecl *clsDeclared;
565 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000566 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
567 OpKind==tok::arrow);
568 }
569 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
570 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000571}
572
Steve Naroff87d58b42007-09-16 03:34:24 +0000573/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000574/// This provides the location of the left/right parens and a list of comma
575/// locations.
576Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000577ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000578 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000579 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
580 Expr *Fn = static_cast<Expr *>(fn);
581 Expr **Args = reinterpret_cast<Expr**>(args);
582 assert(Fn && "no function call expression");
583
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000584 // Make the call expr early, before semantic checks. This guarantees cleanup
585 // of arguments and function on error.
586 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
587 Context.BoolTy, RParenLoc));
588
589 // Promote the function operand.
590 TheCall->setCallee(UsualUnaryConversions(Fn));
591
Chris Lattner4b009652007-07-25 00:24:17 +0000592 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
593 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000594 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000595 if (PT == 0)
596 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
597 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000598 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
599 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000600 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
601 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000602
603 // We know the result type of the call, set it.
604 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000605
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000606 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000607 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
608 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000609 unsigned NumArgsInProto = Proto->getNumArgs();
610 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000611
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000612 // If too few arguments are available, don't make the call.
613 if (NumArgs < NumArgsInProto)
614 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
615 Fn->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000616
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000617 // If too many are passed and not variadic, error on the extras and drop
618 // them.
619 if (NumArgs > NumArgsInProto) {
620 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000621 Diag(Args[NumArgsInProto]->getLocStart(),
622 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
623 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000624 Args[NumArgs-1]->getLocEnd()));
625 // This deletes the extra arguments.
626 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000627 }
628 NumArgsToCheck = NumArgsInProto;
629 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000630
Chris Lattner4b009652007-07-25 00:24:17 +0000631 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000632 for (unsigned i = 0; i != NumArgsToCheck; i++) {
633 Expr *Arg = Args[i];
Chris Lattner005ed752008-01-04 18:04:52 +0000634 QualType ProtoArgType = Proto->getArgType(i);
635 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000636
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000637 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000638 AssignConvertType ConvTy =
639 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000640 TheCall->setArg(i, Arg);
641
Chris Lattner005ed752008-01-04 18:04:52 +0000642 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
643 ArgType, Arg, "passing"))
644 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000645 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000646
647 // If this is a variadic call, handle args passed through "...".
648 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000649 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000650 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
651 Expr *Arg = Args[i];
652 DefaultArgumentPromotion(Arg);
653 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000654 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000655 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000656 } else {
657 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
658
Steve Naroffdb65e052007-08-28 23:30:39 +0000659 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000660 for (unsigned i = 0; i != NumArgs; i++) {
661 Expr *Arg = Args[i];
662 DefaultArgumentPromotion(Arg);
663 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000664 }
Chris Lattner4b009652007-07-25 00:24:17 +0000665 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000666
Chris Lattner2e64c072007-08-10 20:18:51 +0000667 // Do special checking on direct calls to functions.
668 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
669 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
670 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000671 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000672 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000673
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000674 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000675}
676
677Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000678ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000679 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000680 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000681 QualType literalType = QualType::getFromOpaquePtr(Ty);
682 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000683 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000684 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000685
Steve Naroffcb69fb72007-12-10 22:44:33 +0000686 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Narofff0b23542008-01-10 22:15:12 +0000687 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000688 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000689
690 bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
691 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000692 if (CheckForConstantInitializer(literalExpr, literalType))
693 return true;
694 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000695 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000696}
697
698Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000699ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000700 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000701 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000702
Steve Naroff0acc9c92007-09-15 18:49:24 +0000703 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000704 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000705
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000706 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
707 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
708 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000709}
710
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000711bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000712 assert(VectorTy->isVectorType() && "Not a vector type!");
713
714 if (Ty->isVectorType() || Ty->isIntegerType()) {
715 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
716 Context.getTypeSize(Ty, SourceLocation()))
717 return Diag(R.getBegin(),
718 Ty->isVectorType() ?
719 diag::err_invalid_conversion_between_vectors :
720 diag::err_invalid_conversion_between_vector_and_integer,
721 VectorTy.getAsString().c_str(),
722 Ty.getAsString().c_str(), R);
723 } else
724 return Diag(R.getBegin(),
725 diag::err_invalid_conversion_between_vector_and_scalar,
726 VectorTy.getAsString().c_str(),
727 Ty.getAsString().c_str(), R);
728
729 return false;
730}
731
Chris Lattner4b009652007-07-25 00:24:17 +0000732Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000733ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000734 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000735 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000736
737 Expr *castExpr = static_cast<Expr*>(Op);
738 QualType castType = QualType::getFromOpaquePtr(Ty);
739
Steve Naroff68adb482007-08-31 00:32:44 +0000740 UsualUnaryConversions(castExpr);
741
Chris Lattner4b009652007-07-25 00:24:17 +0000742 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
743 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000744 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Narofff459ee52008-01-24 22:55:05 +0000745 if (!castType->isScalarType() && !castType->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000746 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
747 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Steve Narofff459ee52008-01-24 22:55:05 +0000748 if (!castExpr->getType()->isScalarType() &&
749 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000750 return Diag(castExpr->getLocStart(),
751 diag::err_typecheck_expect_scalar_operand,
752 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000753
754 if (castExpr->getType()->isVectorType()) {
755 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
756 castExpr->getType(), castType))
757 return true;
758 } else if (castType->isVectorType()) {
759 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
760 castType, castExpr->getType()))
761 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000762 }
Chris Lattner4b009652007-07-25 00:24:17 +0000763 }
764 return new CastExpr(castType, castExpr, LParenLoc);
765}
766
Chris Lattner98a425c2007-11-26 01:40:58 +0000767/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
768/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000769inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
770 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
771 UsualUnaryConversions(cond);
772 UsualUnaryConversions(lex);
773 UsualUnaryConversions(rex);
774 QualType condT = cond->getType();
775 QualType lexT = lex->getType();
776 QualType rexT = rex->getType();
777
778 // first, check the condition.
779 if (!condT->isScalarType()) { // C99 6.5.15p2
780 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
781 condT.getAsString());
782 return QualType();
783 }
Chris Lattner992ae932008-01-06 22:42:25 +0000784
785 // Now check the two expressions.
786
787 // If both operands have arithmetic type, do the usual arithmetic conversions
788 // to find a common type: C99 6.5.15p3,5.
789 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000790 UsualArithmeticConversions(lex, rex);
791 return lex->getType();
792 }
Chris Lattner992ae932008-01-06 22:42:25 +0000793
794 // If both operands are the same structure or union type, the result is that
795 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000796 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000797 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000798 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000799 // "If both the operands have structure or union type, the result has
800 // that type." This implies that CV qualifiers are dropped.
801 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000802 }
Chris Lattner992ae932008-01-06 22:42:25 +0000803
804 // C99 6.5.15p5: "If both operands have void type, the result has void type."
805 if (lexT->isVoidType() && rexT->isVoidType())
806 return lexT.getUnqualifiedType();
Steve Naroff12ebf272008-01-08 01:11:38 +0000807
808 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
809 // the type of the other operand."
810 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000811 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000812 return lexT;
813 }
814 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000815 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000816 return rexT;
817 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000818 // Handle the case where both operands are pointers before we handle null
819 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000820 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
821 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
822 // get the "pointed to" types
823 QualType lhptee = LHSPT->getPointeeType();
824 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000825
Chris Lattner71225142007-07-31 21:27:01 +0000826 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
827 if (lhptee->isVoidType() &&
Eli Friedmanca07c902008-02-10 22:59:36 +0000828 (rhptee->isObjectType() || rhptee->isIncompleteType())) {
Chris Lattner35fef522008-02-20 20:55:12 +0000829 // Figure out necessary qualifiers (C99 6.5.15p6)
830 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000831 QualType destType = Context.getPointerType(destPointee);
832 ImpCastExprToType(lex, destType); // add qualifiers if necessary
833 ImpCastExprToType(rex, destType); // promote to void*
834 return destType;
835 }
Chris Lattner71225142007-07-31 21:27:01 +0000836 if (rhptee->isVoidType() &&
Eli Friedmanca07c902008-02-10 22:59:36 +0000837 (lhptee->isObjectType() || lhptee->isIncompleteType())) {
Chris Lattner35fef522008-02-20 20:55:12 +0000838 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000839 QualType destType = Context.getPointerType(destPointee);
840 ImpCastExprToType(lex, destType); // add qualifiers if necessary
841 ImpCastExprToType(rex, destType); // promote to void*
842 return destType;
843 }
Chris Lattner4b009652007-07-25 00:24:17 +0000844
Steve Naroff85f0dc52007-10-15 20:41:53 +0000845 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
846 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +0000847 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +0000848 lexT.getAsString(), rexT.getAsString(),
849 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +0000850 // In this situation, we assume void* type. No especially good
851 // reason, but this is what gcc does, and we do have to pick
852 // to get a consistent AST.
853 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
854 ImpCastExprToType(lex, voidPtrTy);
855 ImpCastExprToType(rex, voidPtrTy);
856 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +0000857 }
858 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000859 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
860 // differently qualified versions of compatible types, the result type is
861 // a pointer to an appropriately qualified version of the *composite*
862 // type.
Chris Lattner0ac51632008-01-06 22:50:31 +0000863 // FIXME: Need to return the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +0000864 // FIXME: Need to add qualifiers
Chris Lattner0ac51632008-01-06 22:50:31 +0000865 return lexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000866 }
Chris Lattner4b009652007-07-25 00:24:17 +0000867 }
Chris Lattner71225142007-07-31 21:27:01 +0000868
Chris Lattner992ae932008-01-06 22:42:25 +0000869 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000870 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
871 lexT.getAsString(), rexT.getAsString(),
872 lex->getSourceRange(), rex->getSourceRange());
873 return QualType();
874}
875
Steve Naroff87d58b42007-09-16 03:34:24 +0000876/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000877/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000878Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000879 SourceLocation ColonLoc,
880 ExprTy *Cond, ExprTy *LHS,
881 ExprTy *RHS) {
882 Expr *CondExpr = (Expr *) Cond;
883 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000884
885 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
886 // was the condition.
887 bool isLHSNull = LHSExpr == 0;
888 if (isLHSNull)
889 LHSExpr = CondExpr;
890
Chris Lattner4b009652007-07-25 00:24:17 +0000891 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
892 RHSExpr, QuestionLoc);
893 if (result.isNull())
894 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000895 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
896 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000897}
898
Steve Naroffdb65e052007-08-28 23:30:39 +0000899/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +0000900/// do not have a prototype. Arguments that have type float are promoted to
901/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000902void Sema::DefaultArgumentPromotion(Expr *&Expr) {
903 QualType Ty = Expr->getType();
904 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000905
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000906 if (Ty == Context.FloatTy)
Chris Lattnere992d6c2008-01-16 19:17:22 +0000907 ImpCastExprToType(Expr, Context.DoubleTy);
Steve Naroffbbaed752008-01-29 02:42:22 +0000908 else
909 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +0000910}
911
Chris Lattner4b009652007-07-25 00:24:17 +0000912/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
913void Sema::DefaultFunctionArrayConversion(Expr *&e) {
914 QualType t = e->getType();
915 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
916
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000917 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000918 ImpCastExprToType(e, ref->getReferenceeType()); // C++ [expr]
Chris Lattner4b009652007-07-25 00:24:17 +0000919 t = e->getType();
920 }
921 if (t->isFunctionType())
Chris Lattnere992d6c2008-01-16 19:17:22 +0000922 ImpCastExprToType(e, Context.getPointerType(t));
Steve Naroffac26e9a2008-02-09 16:59:44 +0000923 else if (const ArrayType *ary = t->getAsArrayType()) {
Steve Naroff9ffeda12008-02-09 17:25:18 +0000924 // Make sure we don't lose qualifiers when dealing with typedefs. Example:
Steve Naroffac26e9a2008-02-09 16:59:44 +0000925 // typedef int arr[10];
926 // void test2() {
927 // const arr b;
928 // b[4] = 1;
929 // }
930 QualType ELT = ary->getElementType();
Chris Lattner35fef522008-02-20 20:55:12 +0000931 // FIXME: Handle ASQualType
932 ELT = ELT.getQualifiedType(t.getCVRQualifiers()|ELT.getCVRQualifiers());
Steve Naroffac26e9a2008-02-09 16:59:44 +0000933 ImpCastExprToType(e, Context.getPointerType(ELT));
934 }
Chris Lattner4b009652007-07-25 00:24:17 +0000935}
936
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000937/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +0000938/// operators (C99 6.3). The conversions of array and function types are
939/// sometimes surpressed. For example, the array->pointer conversion doesn't
940/// apply if the array is an argument to the sizeof or address (&) operators.
941/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000942Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
943 QualType Ty = Expr->getType();
944 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000945
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000946 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000947 ImpCastExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000948 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000949 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000950 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +0000951 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000952 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000953 DefaultFunctionArrayConversion(Expr);
954
955 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000956}
957
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000958/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000959/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
960/// routine returns the first non-arithmetic type found. The client is
961/// responsible for emitting appropriate error diagnostics.
Steve Naroffe8419ca2008-01-15 22:21:49 +0000962/// FIXME: verify the conversion rules for "complex int" are consistent with GCC.
Steve Naroff8f708362007-08-24 19:07:16 +0000963QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
964 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000965 if (!isCompAssign) {
966 UsualUnaryConversions(lhsExpr);
967 UsualUnaryConversions(rhsExpr);
968 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000969 // For conversion purposes, we ignore any qualifiers.
970 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000971 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
972 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000973
974 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000975 if (lhs == rhs)
976 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000977
978 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
979 // The caller can deal with this (e.g. pointer + int).
980 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000981 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000982
983 // At this point, we have two different arithmetic types.
984
985 // Handle complex types first (C99 6.3.1.8p1).
986 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +0000987 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +0000988 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +0000989 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +0000990 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +0000991 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +0000992 }
Steve Naroffe8419ca2008-01-15 22:21:49 +0000993 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +0000994 // convert the lhs to the rhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +0000995 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +0000996 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000997 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000998 // This handles complex/complex, complex/float, or float/complex.
999 // When both operands are complex, the shorter operand is converted to the
1000 // type of the longer, and that is the type of the result. This corresponds
1001 // to what is done when combining two real floating-point operands.
1002 // The fun begins when size promotion occur across type domains.
1003 // From H&S 6.3.4: When one operand is complex and the other is a real
1004 // floating-point type, the less precise type is converted, within it's
1005 // real or complex domain, to the precision of the other type. For example,
1006 // when combining a "long double" with a "double _Complex", the
1007 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +00001008 int result = Context.compareFloatingType(lhs, rhs);
1009
1010 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001011 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1012 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001013 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001014 } else if (result < 0) { // The right side is bigger, convert lhs.
1015 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1016 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001017 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001018 }
1019 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1020 // domains match. This is a requirement for our implementation, C99
1021 // does not require this promotion.
1022 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1023 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001024 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001025 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001026 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001027 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001028 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001029 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001030 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001031 }
Chris Lattner4b009652007-07-25 00:24:17 +00001032 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001033 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001034 }
1035 // Now handle "real" floating types (i.e. float, double, long double).
1036 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1037 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001038 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001039 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001040 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001041 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001042 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001043 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001044 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001045 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001046 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001047 }
1048 // We have two real floating types, float/complex combos were handled above.
1049 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001050 int result = Context.compareFloatingType(lhs, rhs);
1051
1052 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001053 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001054 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001055 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001056 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001057 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001058 return rhs;
1059 }
1060 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001061 }
Steve Naroff43001212008-01-15 19:36:10 +00001062 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1063 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001064 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001065 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001066
Eli Friedman50727042008-02-08 01:19:44 +00001067 if (lhsComplexInt && rhsComplexInt) {
1068 if (Context.maxIntegerType(lhsComplexInt->getElementType(),
Eli Friedman94075c02008-02-08 01:24:30 +00001069 rhsComplexInt->getElementType()) == lhs) {
1070 // convert the rhs
1071 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1072 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001073 }
1074 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001075 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001076 return rhs;
1077 } else if (lhsComplexInt && rhs->isIntegerType()) {
1078 // convert the rhs to the lhs complex type.
1079 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1080 return lhs;
1081 } else if (rhsComplexInt && lhs->isIntegerType()) {
1082 // convert the lhs to the rhs complex type.
1083 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1084 return rhs;
1085 }
Steve Naroff43001212008-01-15 19:36:10 +00001086 }
Chris Lattner4b009652007-07-25 00:24:17 +00001087 // Finally, we have two differing integer types.
1088 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001089 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001090 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001091 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001092 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff8f708362007-08-24 19:07:16 +00001093 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001094}
1095
1096// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1097// being closely modeled after the C99 spec:-). The odd characteristic of this
1098// routine is it effectively iqnores the qualifiers on the top level pointee.
1099// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1100// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001101Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001102Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1103 QualType lhptee, rhptee;
1104
1105 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001106 lhptee = lhsType->getAsPointerType()->getPointeeType();
1107 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001108
1109 // make sure we operate on the canonical type
1110 lhptee = lhptee.getCanonicalType();
1111 rhptee = rhptee.getCanonicalType();
1112
Chris Lattner005ed752008-01-04 18:04:52 +00001113 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001114
1115 // C99 6.5.16.1p1: This following citation is common to constraints
1116 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1117 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001118 // FIXME: Handle ASQualType
1119 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1120 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001121 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001122
1123 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1124 // incomplete type and the other is a pointer to a qualified or unqualified
1125 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001126 if (lhptee->isVoidType()) {
1127 if (rhptee->isObjectType() || rhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001128 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001129
1130 // As an extension, we allow cast to/from void* to function pointer.
1131 if (rhptee->isFunctionType())
1132 return FunctionVoidPointer;
1133 }
1134
1135 if (rhptee->isVoidType()) {
1136 if (lhptee->isObjectType() || lhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001137 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001138
1139 // As an extension, we allow cast to/from void* to function pointer.
1140 if (lhptee->isFunctionType())
1141 return FunctionVoidPointer;
1142 }
1143
Chris Lattner4b009652007-07-25 00:24:17 +00001144 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1145 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001146 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1147 rhptee.getUnqualifiedType()))
1148 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001149 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001150}
1151
1152/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1153/// has code to accommodate several GCC extensions when type checking
1154/// pointers. Here are some objectionable examples that GCC considers warnings:
1155///
1156/// int a, *pint;
1157/// short *pshort;
1158/// struct foo *pfoo;
1159///
1160/// pint = pshort; // warning: assignment from incompatible pointer type
1161/// a = pint; // warning: assignment makes integer from pointer without a cast
1162/// pint = a; // warning: assignment makes pointer from integer without a cast
1163/// pint = pfoo; // warning: assignment from incompatible pointer type
1164///
1165/// As a result, the code for dealing with pointers is more complex than the
1166/// C99 spec dictates.
1167/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1168///
Chris Lattner005ed752008-01-04 18:04:52 +00001169Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001170Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001171 // Get canonical types. We're not formatting these types, just comparing
1172 // them.
1173 lhsType = lhsType.getCanonicalType();
1174 rhsType = rhsType.getCanonicalType();
1175
1176 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001177 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001178
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001179 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001180 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001181 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001182 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001183 }
Chris Lattner1853da22008-01-04 23:18:45 +00001184
Ted Kremenek42730c52008-01-07 19:49:32 +00001185 if (lhsType->isObjCQualifiedIdType()
1186 || rhsType->isObjCQualifiedIdType()) {
1187 if (Context.ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001188 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001189 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001190 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001191
1192 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1193 // For OCUVector, allow vector splats; float -> <n x float>
1194 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1195 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1196 return Compatible;
1197 }
1198
1199 // If LHS and RHS are both vectors of integer or both vectors of floating
1200 // point types, and the total vector length is the same, allow the
1201 // conversion. This is a bitcast; no bits are changed but the result type
1202 // is different.
1203 if (getLangOptions().LaxVectorConversions &&
1204 lhsType->isVectorType() && rhsType->isVectorType()) {
1205 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1206 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
1207 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1208 Context.getTypeSize(rhsType, SourceLocation()))
Nate Begemanec2d1062007-12-30 02:59:45 +00001209 return Compatible;
1210 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001211 }
1212 return Incompatible;
1213 }
1214
1215 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001216 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001217
1218 if (lhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001219 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001220 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001221
1222 if (rhsType->isPointerType())
1223 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001224 return Incompatible;
1225 }
1226
1227 if (rhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001228 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1229 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001230 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001231
1232 if (lhsType->isPointerType())
1233 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001234 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001235 }
1236
1237 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001238 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001239 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001240 }
1241 return Incompatible;
1242}
1243
Chris Lattner005ed752008-01-04 18:04:52 +00001244Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001245Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001246 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1247 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001248 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001249 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001250 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001251 return Compatible;
1252 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001253 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001254 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001255 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001256 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001257 //
1258 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1259 // are better understood.
1260 if (!lhsType->isReferenceType())
1261 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001262
Chris Lattner005ed752008-01-04 18:04:52 +00001263 Sema::AssignConvertType result =
1264 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001265
1266 // C99 6.5.16.1p2: The value of the right operand is converted to the
1267 // type of the assignment expression.
1268 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001269 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001270 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001271}
1272
Chris Lattner005ed752008-01-04 18:04:52 +00001273Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001274Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1275 return CheckAssignmentConstraints(lhsType, rhsType);
1276}
1277
Chris Lattner2c8bff72007-12-12 05:47:28 +00001278QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001279 Diag(loc, diag::err_typecheck_invalid_operands,
1280 lex->getType().getAsString(), rex->getType().getAsString(),
1281 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001282 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001283}
1284
1285inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1286 Expr *&rex) {
1287 QualType lhsType = lex->getType(), rhsType = rex->getType();
1288
1289 // make sure the vector types are identical.
1290 if (lhsType == rhsType)
1291 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001292
1293 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1294 // promote the rhs to the vector type.
1295 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1296 if (V->getElementType().getCanonicalType().getTypePtr()
1297 == rhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001298 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001299 return lhsType;
1300 }
1301 }
1302
1303 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1304 // promote the lhs to the vector type.
1305 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1306 if (V->getElementType().getCanonicalType().getTypePtr()
1307 == lhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001308 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001309 return rhsType;
1310 }
1311 }
1312
Chris Lattner4b009652007-07-25 00:24:17 +00001313 // You cannot convert between vector values of different size.
1314 Diag(loc, diag::err_typecheck_vector_not_convertable,
1315 lex->getType().getAsString(), rex->getType().getAsString(),
1316 lex->getSourceRange(), rex->getSourceRange());
1317 return QualType();
1318}
1319
1320inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001321 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001322{
1323 QualType lhsType = lex->getType(), rhsType = rex->getType();
1324
1325 if (lhsType->isVectorType() || rhsType->isVectorType())
1326 return CheckVectorOperands(loc, lex, rex);
1327
Steve Naroff8f708362007-08-24 19:07:16 +00001328 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001329
Chris Lattner4b009652007-07-25 00:24:17 +00001330 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001331 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001332 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001333}
1334
1335inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001336 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001337{
1338 QualType lhsType = lex->getType(), rhsType = rex->getType();
1339
Steve Naroff8f708362007-08-24 19:07:16 +00001340 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001341
Chris Lattner4b009652007-07-25 00:24:17 +00001342 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001343 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001344 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001345}
1346
1347inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001348 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001349{
1350 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1351 return CheckVectorOperands(loc, lex, rex);
1352
Steve Naroff8f708362007-08-24 19:07:16 +00001353 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001354
1355 // handle the common case first (both operands are arithmetic).
1356 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001357 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001358
1359 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1360 return lex->getType();
1361 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1362 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001363 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001364}
1365
1366inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001367 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001368{
1369 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1370 return CheckVectorOperands(loc, lex, rex);
1371
Steve Naroff8f708362007-08-24 19:07:16 +00001372 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001373
Chris Lattnerf6da2912007-12-09 21:53:25 +00001374 // Enforce type constraints: C99 6.5.6p3.
1375
1376 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001377 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001378 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001379
1380 // Either ptr - int or ptr - ptr.
1381 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001382 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001383
Chris Lattnerf6da2912007-12-09 21:53:25 +00001384 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001385 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001386 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001387 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001388 Diag(loc, diag::ext_gnu_void_ptr,
1389 lex->getSourceRange(), rex->getSourceRange());
1390 } else {
1391 Diag(loc, diag::err_typecheck_sub_ptr_object,
1392 lex->getType().getAsString(), lex->getSourceRange());
1393 return QualType();
1394 }
1395 }
1396
1397 // The result type of a pointer-int computation is the pointer type.
1398 if (rex->getType()->isIntegerType())
1399 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001400
Chris Lattnerf6da2912007-12-09 21:53:25 +00001401 // Handle pointer-pointer subtractions.
1402 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001403 QualType rpointee = RHSPTy->getPointeeType();
1404
Chris Lattnerf6da2912007-12-09 21:53:25 +00001405 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001406 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001407 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001408 if (rpointee->isVoidType()) {
1409 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001410 Diag(loc, diag::ext_gnu_void_ptr,
1411 lex->getSourceRange(), rex->getSourceRange());
1412 } else {
1413 Diag(loc, diag::err_typecheck_sub_ptr_object,
1414 rex->getType().getAsString(), rex->getSourceRange());
1415 return QualType();
1416 }
1417 }
1418
1419 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001420 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1421 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001422 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1423 lex->getType().getAsString(), rex->getType().getAsString(),
1424 lex->getSourceRange(), rex->getSourceRange());
1425 return QualType();
1426 }
1427
1428 return Context.getPointerDiffType();
1429 }
1430 }
1431
Chris Lattner2c8bff72007-12-12 05:47:28 +00001432 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001433}
1434
1435inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattner2c8bff72007-12-12 05:47:28 +00001436 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1437 // C99 6.5.7p2: Each of the operands shall have integer type.
1438 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1439 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001440
Chris Lattner2c8bff72007-12-12 05:47:28 +00001441 // Shifts don't perform usual arithmetic conversions, they just do integer
1442 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001443 if (!isCompAssign)
1444 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001445 UsualUnaryConversions(rex);
1446
1447 // "The type of the result is that of the promoted left operand."
1448 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001449}
1450
Chris Lattner254f3bc2007-08-26 01:18:55 +00001451inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1452 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001453{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001454 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001455 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1456 UsualArithmeticConversions(lex, rex);
1457 else {
1458 UsualUnaryConversions(lex);
1459 UsualUnaryConversions(rex);
1460 }
Chris Lattner4b009652007-07-25 00:24:17 +00001461 QualType lType = lex->getType();
1462 QualType rType = rex->getType();
1463
Ted Kremenek486509e2007-10-29 17:13:39 +00001464 // For non-floating point types, check for self-comparisons of the form
1465 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1466 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001467 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001468 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1469 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001470 if (DRL->getDecl() == DRR->getDecl())
1471 Diag(loc, diag::warn_selfcomparison);
1472 }
1473
Chris Lattner254f3bc2007-08-26 01:18:55 +00001474 if (isRelational) {
1475 if (lType->isRealType() && rType->isRealType())
1476 return Context.IntTy;
1477 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001478 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001479 if (lType->isFloatingType()) {
1480 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001481 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001482 }
1483
Chris Lattner254f3bc2007-08-26 01:18:55 +00001484 if (lType->isArithmeticType() && rType->isArithmeticType())
1485 return Context.IntTy;
1486 }
Chris Lattner4b009652007-07-25 00:24:17 +00001487
Chris Lattner22be8422007-08-26 01:10:14 +00001488 bool LHSIsNull = lex->isNullPointerConstant(Context);
1489 bool RHSIsNull = rex->isNullPointerConstant(Context);
1490
Chris Lattner254f3bc2007-08-26 01:18:55 +00001491 // All of the following pointer related warnings are GCC extensions, except
1492 // when handling null pointer constants. One day, we can consider making them
1493 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001494 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Eli Friedman50727042008-02-08 01:19:44 +00001495 QualType lpointee = lType->getAsPointerType()->getPointeeType();
1496 QualType rpointee = rType->getAsPointerType()->getPointeeType();
1497
Steve Naroff3b435622007-11-13 14:57:38 +00001498 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Steve Naroff577f9722008-01-29 18:58:14 +00001499 !lpointee->isVoidType() && !lpointee->isVoidType() &&
1500 !Context.typesAreCompatible(lpointee.getUnqualifiedType(),
Eli Friedman50727042008-02-08 01:19:44 +00001501 rpointee.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001502 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1503 lType.getAsString(), rType.getAsString(),
1504 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001505 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001506 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001507 return Context.IntTy;
1508 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001509 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
1510 && Context.ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001511 ImpCastExprToType(rex, lType);
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001512 return Context.IntTy;
1513 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001514 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001515 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001516 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1517 lType.getAsString(), rType.getAsString(),
1518 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001519 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001520 return Context.IntTy;
1521 }
1522 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001523 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001524 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1525 lType.getAsString(), rType.getAsString(),
1526 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001527 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001528 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001529 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001530 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001531}
1532
Chris Lattner4b009652007-07-25 00:24:17 +00001533inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001534 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001535{
1536 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1537 return CheckVectorOperands(loc, lex, rex);
1538
Steve Naroff8f708362007-08-24 19:07:16 +00001539 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001540
1541 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001542 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001543 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001544}
1545
1546inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1547 Expr *&lex, Expr *&rex, SourceLocation loc)
1548{
1549 UsualUnaryConversions(lex);
1550 UsualUnaryConversions(rex);
1551
1552 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1553 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001554 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001555}
1556
1557inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001558 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001559{
1560 QualType lhsType = lex->getType();
1561 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001562 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1563
1564 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001565 case Expr::MLV_Valid:
1566 break;
1567 case Expr::MLV_ConstQualified:
1568 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1569 return QualType();
1570 case Expr::MLV_ArrayType:
1571 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1572 lhsType.getAsString(), lex->getSourceRange());
1573 return QualType();
1574 case Expr::MLV_NotObjectType:
1575 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1576 lhsType.getAsString(), lex->getSourceRange());
1577 return QualType();
1578 case Expr::MLV_InvalidExpression:
1579 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1580 lex->getSourceRange());
1581 return QualType();
1582 case Expr::MLV_IncompleteType:
1583 case Expr::MLV_IncompleteVoidType:
1584 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1585 lhsType.getAsString(), lex->getSourceRange());
1586 return QualType();
1587 case Expr::MLV_DuplicateVectorComponents:
1588 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1589 lex->getSourceRange());
1590 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001591 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001592
Chris Lattner005ed752008-01-04 18:04:52 +00001593 AssignConvertType ConvTy;
1594 if (compoundType.isNull())
1595 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1596 else
1597 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1598
1599 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1600 rex, "assigning"))
1601 return QualType();
1602
Chris Lattner4b009652007-07-25 00:24:17 +00001603 // C99 6.5.16p3: The type of an assignment expression is the type of the
1604 // left operand unless the left operand has qualified type, in which case
1605 // it is the unqualified version of the type of the left operand.
1606 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1607 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001608 // C++ 5.17p1: the type of the assignment expression is that of its left
1609 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001610 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001611}
1612
1613inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1614 Expr *&lex, Expr *&rex, SourceLocation loc) {
1615 UsualUnaryConversions(rex);
1616 return rex->getType();
1617}
1618
1619/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1620/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1621QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1622 QualType resType = op->getType();
1623 assert(!resType.isNull() && "no type for increment/decrement expression");
1624
Steve Naroffd30e1932007-08-24 17:20:07 +00001625 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001626 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001627 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1628 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1629 resType.getAsString(), op->getSourceRange());
1630 return QualType();
1631 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001632 } else if (!resType->isRealType()) {
1633 if (resType->isComplexType())
1634 // C99 does not support ++/-- on complex types.
1635 Diag(OpLoc, diag::ext_integer_increment_complex,
1636 resType.getAsString(), op->getSourceRange());
1637 else {
1638 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1639 resType.getAsString(), op->getSourceRange());
1640 return QualType();
1641 }
Chris Lattner4b009652007-07-25 00:24:17 +00001642 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001643 // At this point, we know we have a real, complex or pointer type.
1644 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001645 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1646 if (mlval != Expr::MLV_Valid) {
1647 // FIXME: emit a more precise diagnostic...
1648 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1649 op->getSourceRange());
1650 return QualType();
1651 }
1652 return resType;
1653}
1654
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001655/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001656/// This routine allows us to typecheck complex/recursive expressions
1657/// where the declaration is needed for type checking. Here are some
1658/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001659static ValueDecl *getPrimaryDecl(Expr *e) {
Chris Lattner4b009652007-07-25 00:24:17 +00001660 switch (e->getStmtClass()) {
1661 case Stmt::DeclRefExprClass:
1662 return cast<DeclRefExpr>(e)->getDecl();
1663 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001664 // Fields cannot be declared with a 'register' storage class.
1665 // &X->f is always ok, even if X is declared register.
1666 if (cast<MemberExpr>(e)->isArrow())
1667 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001668 return getPrimaryDecl(cast<MemberExpr>(e)->getBase());
1669 case Stmt::ArraySubscriptExprClass: {
1670 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1671
1672 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(e)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001673 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001674 return 0;
1675 else
1676 return VD;
1677 }
Chris Lattner4b009652007-07-25 00:24:17 +00001678 case Stmt::UnaryOperatorClass:
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001679 return getPrimaryDecl(cast<UnaryOperator>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001680 case Stmt::ParenExprClass:
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001681 return getPrimaryDecl(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001682 case Stmt::ImplicitCastExprClass:
1683 // &X[4] when X is an array, has an implicit cast from array to pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001684 return getPrimaryDecl(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001685 default:
1686 return 0;
1687 }
1688}
1689
1690/// CheckAddressOfOperand - The operand of & must be either a function
1691/// designator or an lvalue designating an object. If it is an lvalue, the
1692/// object cannot be declared with storage class register or be a bit field.
1693/// Note: The usual conversions are *not* applied to the operand of the &
1694/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1695QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001696 if (getLangOptions().C99) {
1697 // Implement C99-only parts of addressof rules.
1698 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1699 if (uOp->getOpcode() == UnaryOperator::Deref)
1700 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1701 // (assuming the deref expression is valid).
1702 return uOp->getSubExpr()->getType();
1703 }
1704 // Technically, there should be a check for array subscript
1705 // expressions here, but the result of one is always an lvalue anyway.
1706 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001707 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001708 Expr::isLvalueResult lval = op->isLvalue();
1709
1710 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001711 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1712 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001713 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1714 op->getSourceRange());
1715 return QualType();
1716 }
1717 } else if (dcl) {
1718 // We have an lvalue with a decl. Make sure the decl is not declared
1719 // with the register storage-class specifier.
1720 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1721 if (vd->getStorageClass() == VarDecl::Register) {
1722 Diag(OpLoc, diag::err_typecheck_address_of_register,
1723 op->getSourceRange());
1724 return QualType();
1725 }
1726 } else
1727 assert(0 && "Unknown/unexpected decl type");
1728
1729 // FIXME: add check for bitfields!
1730 }
1731 // If the operand has type "type", the result has type "pointer to type".
1732 return Context.getPointerType(op->getType());
1733}
1734
1735QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1736 UsualUnaryConversions(op);
1737 QualType qType = op->getType();
1738
Chris Lattner7931f4a2007-07-31 16:53:04 +00001739 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001740 // Note that per both C89 and C99, this is always legal, even
1741 // if ptype is an incomplete type or void.
1742 // It would be possible to warn about dereferencing a
1743 // void pointer, but it's completely well-defined,
1744 // and such a warning is unlikely to catch any mistakes.
1745 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001746 }
1747 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1748 qType.getAsString(), op->getSourceRange());
1749 return QualType();
1750}
1751
1752static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1753 tok::TokenKind Kind) {
1754 BinaryOperator::Opcode Opc;
1755 switch (Kind) {
1756 default: assert(0 && "Unknown binop!");
1757 case tok::star: Opc = BinaryOperator::Mul; break;
1758 case tok::slash: Opc = BinaryOperator::Div; break;
1759 case tok::percent: Opc = BinaryOperator::Rem; break;
1760 case tok::plus: Opc = BinaryOperator::Add; break;
1761 case tok::minus: Opc = BinaryOperator::Sub; break;
1762 case tok::lessless: Opc = BinaryOperator::Shl; break;
1763 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1764 case tok::lessequal: Opc = BinaryOperator::LE; break;
1765 case tok::less: Opc = BinaryOperator::LT; break;
1766 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1767 case tok::greater: Opc = BinaryOperator::GT; break;
1768 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1769 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1770 case tok::amp: Opc = BinaryOperator::And; break;
1771 case tok::caret: Opc = BinaryOperator::Xor; break;
1772 case tok::pipe: Opc = BinaryOperator::Or; break;
1773 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1774 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1775 case tok::equal: Opc = BinaryOperator::Assign; break;
1776 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1777 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1778 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1779 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1780 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1781 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1782 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1783 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1784 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1785 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1786 case tok::comma: Opc = BinaryOperator::Comma; break;
1787 }
1788 return Opc;
1789}
1790
1791static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1792 tok::TokenKind Kind) {
1793 UnaryOperator::Opcode Opc;
1794 switch (Kind) {
1795 default: assert(0 && "Unknown unary op!");
1796 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1797 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1798 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1799 case tok::star: Opc = UnaryOperator::Deref; break;
1800 case tok::plus: Opc = UnaryOperator::Plus; break;
1801 case tok::minus: Opc = UnaryOperator::Minus; break;
1802 case tok::tilde: Opc = UnaryOperator::Not; break;
1803 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1804 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1805 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1806 case tok::kw___real: Opc = UnaryOperator::Real; break;
1807 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1808 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1809 }
1810 return Opc;
1811}
1812
1813// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001814Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001815 ExprTy *LHS, ExprTy *RHS) {
1816 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1817 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1818
Steve Naroff87d58b42007-09-16 03:34:24 +00001819 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1820 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001821
1822 QualType ResultTy; // Result type of the binary operator.
1823 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1824
1825 switch (Opc) {
1826 default:
1827 assert(0 && "Unknown binary expr!");
1828 case BinaryOperator::Assign:
1829 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1830 break;
1831 case BinaryOperator::Mul:
1832 case BinaryOperator::Div:
1833 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1834 break;
1835 case BinaryOperator::Rem:
1836 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1837 break;
1838 case BinaryOperator::Add:
1839 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1840 break;
1841 case BinaryOperator::Sub:
1842 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1843 break;
1844 case BinaryOperator::Shl:
1845 case BinaryOperator::Shr:
1846 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1847 break;
1848 case BinaryOperator::LE:
1849 case BinaryOperator::LT:
1850 case BinaryOperator::GE:
1851 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001852 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001853 break;
1854 case BinaryOperator::EQ:
1855 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001856 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001857 break;
1858 case BinaryOperator::And:
1859 case BinaryOperator::Xor:
1860 case BinaryOperator::Or:
1861 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1862 break;
1863 case BinaryOperator::LAnd:
1864 case BinaryOperator::LOr:
1865 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1866 break;
1867 case BinaryOperator::MulAssign:
1868 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001869 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001870 if (!CompTy.isNull())
1871 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1872 break;
1873 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001874 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001875 if (!CompTy.isNull())
1876 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1877 break;
1878 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001879 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001880 if (!CompTy.isNull())
1881 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1882 break;
1883 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001884 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001885 if (!CompTy.isNull())
1886 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1887 break;
1888 case BinaryOperator::ShlAssign:
1889 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001890 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001891 if (!CompTy.isNull())
1892 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1893 break;
1894 case BinaryOperator::AndAssign:
1895 case BinaryOperator::XorAssign:
1896 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001897 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001898 if (!CompTy.isNull())
1899 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1900 break;
1901 case BinaryOperator::Comma:
1902 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1903 break;
1904 }
1905 if (ResultTy.isNull())
1906 return true;
1907 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001908 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001909 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001910 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001911}
1912
1913// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001914Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001915 ExprTy *input) {
1916 Expr *Input = (Expr*)input;
1917 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1918 QualType resultType;
1919 switch (Opc) {
1920 default:
1921 assert(0 && "Unimplemented unary expr!");
1922 case UnaryOperator::PreInc:
1923 case UnaryOperator::PreDec:
1924 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1925 break;
1926 case UnaryOperator::AddrOf:
1927 resultType = CheckAddressOfOperand(Input, OpLoc);
1928 break;
1929 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001930 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001931 resultType = CheckIndirectionOperand(Input, OpLoc);
1932 break;
1933 case UnaryOperator::Plus:
1934 case UnaryOperator::Minus:
1935 UsualUnaryConversions(Input);
1936 resultType = Input->getType();
1937 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1938 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1939 resultType.getAsString());
1940 break;
1941 case UnaryOperator::Not: // bitwise complement
1942 UsualUnaryConversions(Input);
1943 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001944 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1945 if (!resultType->isIntegerType()) {
1946 if (resultType->isComplexType())
1947 // C99 does not support '~' for complex conjugation.
1948 Diag(OpLoc, diag::ext_integer_complement_complex,
1949 resultType.getAsString());
1950 else
1951 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1952 resultType.getAsString());
1953 }
Chris Lattner4b009652007-07-25 00:24:17 +00001954 break;
1955 case UnaryOperator::LNot: // logical negation
1956 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1957 DefaultFunctionArrayConversion(Input);
1958 resultType = Input->getType();
1959 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1960 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1961 resultType.getAsString());
1962 // LNot always has type int. C99 6.5.3.3p5.
1963 resultType = Context.IntTy;
1964 break;
1965 case UnaryOperator::SizeOf:
1966 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1967 break;
1968 case UnaryOperator::AlignOf:
1969 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1970 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001971 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001972 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001973 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001974 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001975 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001976 resultType = Input->getType();
1977 break;
1978 }
1979 if (resultType.isNull())
1980 return true;
1981 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1982}
1983
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001984/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1985Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001986 SourceLocation LabLoc,
1987 IdentifierInfo *LabelII) {
1988 // Look up the record for this label identifier.
1989 LabelStmt *&LabelDecl = LabelMap[LabelII];
1990
1991 // If we haven't seen this label yet, create a forward reference.
1992 if (LabelDecl == 0)
1993 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1994
1995 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001996 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1997 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001998}
1999
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002000Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002001 SourceLocation RPLoc) { // "({..})"
2002 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2003 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2004 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2005
2006 // FIXME: there are a variety of strange constraints to enforce here, for
2007 // example, it is not possible to goto into a stmt expression apparently.
2008 // More semantic analysis is needed.
2009
2010 // FIXME: the last statement in the compount stmt has its value used. We
2011 // should not warn about it being unused.
2012
2013 // If there are sub stmts in the compound stmt, take the type of the last one
2014 // as the type of the stmtexpr.
2015 QualType Ty = Context.VoidTy;
2016
2017 if (!Compound->body_empty())
2018 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2019 Ty = LastExpr->getType();
2020
2021 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2022}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002023
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002024Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002025 SourceLocation TypeLoc,
2026 TypeTy *argty,
2027 OffsetOfComponent *CompPtr,
2028 unsigned NumComponents,
2029 SourceLocation RPLoc) {
2030 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2031 assert(!ArgTy.isNull() && "Missing type argument!");
2032
2033 // We must have at least one component that refers to the type, and the first
2034 // one is known to be a field designator. Verify that the ArgTy represents
2035 // a struct/union/class.
2036 if (!ArgTy->isRecordType())
2037 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2038
2039 // Otherwise, create a compound literal expression as the base, and
2040 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002041 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002042
Chris Lattnerb37522e2007-08-31 21:49:13 +00002043 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2044 // GCC extension, diagnose them.
2045 if (NumComponents != 1)
2046 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2047 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2048
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002049 for (unsigned i = 0; i != NumComponents; ++i) {
2050 const OffsetOfComponent &OC = CompPtr[i];
2051 if (OC.isBrackets) {
2052 // Offset of an array sub-field. TODO: Should we allow vector elements?
2053 const ArrayType *AT = Res->getType()->getAsArrayType();
2054 if (!AT) {
2055 delete Res;
2056 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2057 Res->getType().getAsString());
2058 }
2059
Chris Lattner2af6a802007-08-30 17:59:59 +00002060 // FIXME: C++: Verify that operator[] isn't overloaded.
2061
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002062 // C99 6.5.2.1p1
2063 Expr *Idx = static_cast<Expr*>(OC.U.E);
2064 if (!Idx->getType()->isIntegerType())
2065 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2066 Idx->getSourceRange());
2067
2068 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2069 continue;
2070 }
2071
2072 const RecordType *RC = Res->getType()->getAsRecordType();
2073 if (!RC) {
2074 delete Res;
2075 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2076 Res->getType().getAsString());
2077 }
2078
2079 // Get the decl corresponding to this.
2080 RecordDecl *RD = RC->getDecl();
2081 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2082 if (!MemberDecl)
2083 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2084 OC.U.IdentInfo->getName(),
2085 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002086
2087 // FIXME: C++: Verify that MemberDecl isn't a static field.
2088 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002089 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2090 // matter here.
2091 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002092 }
2093
2094 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2095 BuiltinLoc);
2096}
2097
2098
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002099Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002100 TypeTy *arg1, TypeTy *arg2,
2101 SourceLocation RPLoc) {
2102 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2103 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2104
2105 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2106
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002107 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002108}
2109
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002110Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002111 ExprTy *expr1, ExprTy *expr2,
2112 SourceLocation RPLoc) {
2113 Expr *CondExpr = static_cast<Expr*>(cond);
2114 Expr *LHSExpr = static_cast<Expr*>(expr1);
2115 Expr *RHSExpr = static_cast<Expr*>(expr2);
2116
2117 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2118
2119 // The conditional expression is required to be a constant expression.
2120 llvm::APSInt condEval(32);
2121 SourceLocation ExpLoc;
2122 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2123 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2124 CondExpr->getSourceRange());
2125
2126 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2127 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2128 RHSExpr->getType();
2129 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2130}
2131
Nate Begemanbd881ef2008-01-30 20:50:20 +00002132/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002133/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002134/// The number of arguments has already been validated to match the number of
2135/// arguments in FnType.
2136static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002137 unsigned NumParams = FnType->getNumArgs();
2138 for (unsigned i = 0; i != NumParams; ++i)
Nate Begemanbd881ef2008-01-30 20:50:20 +00002139 if (Args[i]->getType().getCanonicalType() !=
2140 FnType->getArgType(i).getCanonicalType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002141 return false;
2142 return true;
2143}
2144
2145Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2146 SourceLocation *CommaLocs,
2147 SourceLocation BuiltinLoc,
2148 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002149 // __builtin_overload requires at least 2 arguments
2150 if (NumArgs < 2)
2151 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2152 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002153
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002154 // The first argument is required to be a constant expression. It tells us
2155 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002156 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002157 Expr *NParamsExpr = Args[0];
2158 llvm::APSInt constEval(32);
2159 SourceLocation ExpLoc;
2160 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2161 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2162 NParamsExpr->getSourceRange());
2163
2164 // Verify that the number of parameters is > 0
2165 unsigned NumParams = constEval.getZExtValue();
2166 if (NumParams == 0)
2167 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2168 NParamsExpr->getSourceRange());
2169 // Verify that we have at least 1 + NumParams arguments to the builtin.
2170 if ((NumParams + 1) > NumArgs)
2171 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2172 SourceRange(BuiltinLoc, RParenLoc));
2173
2174 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002175 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002176 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002177 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2178 // UsualUnaryConversions will convert the function DeclRefExpr into a
2179 // pointer to function.
2180 Expr *Fn = UsualUnaryConversions(Args[i]);
2181 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002182 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2183 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2184 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2185 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002186
2187 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2188 // parameters, and the number of parameters must match the value passed to
2189 // the builtin.
2190 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002191 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2192 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002193
2194 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002195 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002196 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002197 if (ExprsMatchFnType(Args+1, FnType)) {
2198 if (OE)
2199 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2200 OE->getFn()->getSourceRange());
2201 // Remember our match, and continue processing the remaining arguments
2202 // to catch any errors.
2203 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2204 BuiltinLoc, RParenLoc);
2205 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002206 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002207 // Return the newly created OverloadExpr node, if we succeded in matching
2208 // exactly one of the candidate functions.
2209 if (OE)
2210 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002211
2212 // If we didn't find a matching function Expr in the __builtin_overload list
2213 // the return an error.
2214 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002215 for (unsigned i = 0; i != NumParams; ++i) {
2216 if (i != 0) typeNames += ", ";
2217 typeNames += Args[i+1]->getType().getAsString();
2218 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002219
2220 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2221 SourceRange(BuiltinLoc, RParenLoc));
2222}
2223
Anders Carlsson36760332007-10-15 20:28:48 +00002224Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2225 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002226 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002227 Expr *E = static_cast<Expr*>(expr);
2228 QualType T = QualType::getFromOpaquePtr(type);
2229
2230 InitBuiltinVaListType();
2231
Chris Lattner005ed752008-01-04 18:04:52 +00002232 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2233 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002234 return Diag(E->getLocStart(),
2235 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2236 E->getType().getAsString(),
2237 E->getSourceRange());
2238
2239 // FIXME: Warn if a non-POD type is passed in.
2240
2241 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2242}
2243
Chris Lattner005ed752008-01-04 18:04:52 +00002244bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2245 SourceLocation Loc,
2246 QualType DstType, QualType SrcType,
2247 Expr *SrcExpr, const char *Flavor) {
2248 // Decode the result (notice that AST's are still created for extensions).
2249 bool isInvalid = false;
2250 unsigned DiagKind;
2251 switch (ConvTy) {
2252 default: assert(0 && "Unknown conversion type");
2253 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002254 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002255 DiagKind = diag::ext_typecheck_convert_pointer_int;
2256 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002257 case IntToPointer:
2258 DiagKind = diag::ext_typecheck_convert_int_pointer;
2259 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002260 case IncompatiblePointer:
2261 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2262 break;
2263 case FunctionVoidPointer:
2264 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2265 break;
2266 case CompatiblePointerDiscardsQualifiers:
2267 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2268 break;
2269 case Incompatible:
2270 DiagKind = diag::err_typecheck_convert_incompatible;
2271 isInvalid = true;
2272 break;
2273 }
2274
2275 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2276 SrcExpr->getSourceRange());
2277 return isInvalid;
2278}
2279