blob: d756345c1a8617d9996d62b9e7390310e411f3b1 [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)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000103 // check if referencing an identifier with __attribute__((deprecated)).
104 if (VD->getAttr<DeprecatedAttr>())
105 Diag(Loc, diag::warn_deprecated, VD->getName());
106
Steve Naroffcae537d2007-08-28 18:45:29 +0000107 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000108 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000109 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000110 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000111 }
Chris Lattner4b009652007-07-25 00:24:17 +0000112 if (isa<TypedefDecl>(D))
113 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000114 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000115 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000116
117 assert(0 && "Invalid decl");
118 abort();
119}
120
Steve Naroff87d58b42007-09-16 03:34:24 +0000121Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000122 tok::TokenKind Kind) {
123 PreDefinedExpr::IdentType IT;
124
125 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000126 default: assert(0 && "Unknown simple primary expr!");
127 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
128 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
129 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000130 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000131
132 // Verify that this is in a function context.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000133 if (CurFunctionDecl == 0 && CurMethodDecl == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000134 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000135
Chris Lattner7e637512008-01-12 08:14:25 +0000136 // Pre-defined identifiers are of type char[x], where x is the length of the
137 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000138 unsigned Length;
139 if (CurFunctionDecl)
140 Length = CurFunctionDecl->getIdentifier()->getLength();
141 else
Fariborz Jahaniandcecd5c2008-01-17 17:37:26 +0000142 Length = CurMethodDecl->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000143
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000144 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000145 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000146 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000147 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000148}
149
Steve Naroff87d58b42007-09-16 03:34:24 +0000150Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000151 llvm::SmallString<16> CharBuffer;
152 CharBuffer.resize(Tok.getLength());
153 const char *ThisTokBegin = &CharBuffer[0];
154 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
155
156 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
157 Tok.getLocation(), PP);
158 if (Literal.hadError())
159 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000160
161 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
162
163 return new CharacterLiteral(Literal.getValue(), type, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000164}
165
Steve Naroff87d58b42007-09-16 03:34:24 +0000166Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000167 // fast path for a single digit (which is quite common). A single digit
168 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
169 if (Tok.getLength() == 1) {
170 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
171
Chris Lattner8cd0e932008-03-05 18:54:05 +0000172 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000173 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
174 Context.IntTy,
175 Tok.getLocation()));
176 }
177 llvm::SmallString<512> IntegerBuffer;
178 IntegerBuffer.resize(Tok.getLength());
179 const char *ThisTokBegin = &IntegerBuffer[0];
180
181 // Get the spelling of the token, which eliminates trigraphs, etc.
182 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
183 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
184 Tok.getLocation(), PP);
185 if (Literal.hadError)
186 return ExprResult(true);
187
Chris Lattner1de66eb2007-08-26 03:42:43 +0000188 Expr *Res;
189
190 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000191 QualType Ty;
192 const llvm::fltSemantics *Format;
Chris Lattner858eece2007-09-22 18:29:59 +0000193
194 if (Literal.isFloat) {
195 Ty = Context.FloatTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000196 Format = Context.Target.getFloatFormat();
197 } else if (!Literal.isLong) {
Chris Lattner858eece2007-09-22 18:29:59 +0000198 Ty = Context.DoubleTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000199 Format = Context.Target.getDoubleFormat();
200 } else {
201 Ty = Context.LongDoubleTy;
202 Format = Context.Target.getLongDoubleFormat();
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.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000222 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000223
224 if (Literal.GetIntegerValue(ResultVal)) {
225 // If this value didn't fit into uintmax_t, warn and force to ull.
226 Diag(Tok.getLocation(), diag::warn_integer_too_large);
227 t = Context.UnsignedLongLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +0000228 assert(Context.getTypeSize(t) == ResultVal.getBitWidth() &&
229 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000230 } else {
231 // If this value fits into a ULL, try to figure out what else it fits into
232 // according to the rules of C99 6.4.4.1p5.
233
234 // Octal, Hexadecimal, and integers with a U suffix are allowed to
235 // be an unsigned int.
236 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
237
238 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000239 if (!Literal.isLong && !Literal.isLongLong) {
240 // Are int/unsigned possibilities?
Chris Lattner8cd0e932008-03-05 18:54:05 +0000241 unsigned IntSize =
242 static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000243 // Does it fit in a unsigned int?
244 if (ResultVal.isIntN(IntSize)) {
245 // Does it fit in a signed int?
246 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
247 t = Context.IntTy;
248 else if (AllowUnsigned)
249 t = Context.UnsignedIntTy;
250 }
251
252 if (!t.isNull())
253 ResultVal.trunc(IntSize);
254 }
255
256 // Are long/unsigned long possibilities?
257 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000258 unsigned LongSize =
259 static_cast<unsigned>(Context.getTypeSize(Context.LongTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000260
261 // Does it fit in a unsigned long?
262 if (ResultVal.isIntN(LongSize)) {
263 // Does it fit in a signed long?
264 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
265 t = Context.LongTy;
266 else if (AllowUnsigned)
267 t = Context.UnsignedLongTy;
268 }
269 if (!t.isNull())
270 ResultVal.trunc(LongSize);
271 }
272
273 // Finally, check long long if needed.
274 if (t.isNull()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000275 unsigned LongLongSize =
276 static_cast<unsigned>(Context.getTypeSize(Context.LongLongTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000277
278 // Does it fit in a unsigned long long?
279 if (ResultVal.isIntN(LongLongSize)) {
280 // Does it fit in a signed long long?
281 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
282 t = Context.LongLongTy;
283 else if (AllowUnsigned)
284 t = Context.UnsignedLongLongTy;
285 }
286 }
287
288 // If we still couldn't decide a type, we probably have something that
289 // does not fit in a signed long long, but has no U suffix.
290 if (t.isNull()) {
291 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
292 t = Context.UnsignedLongLongTy;
293 }
294 }
295
Chris Lattner1de66eb2007-08-26 03:42:43 +0000296 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000297 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000298
299 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
300 if (Literal.isImaginary)
301 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
302
303 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000304}
305
Steve Naroff87d58b42007-09-16 03:34:24 +0000306Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000307 ExprTy *Val) {
308 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000309 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000310 return new ParenExpr(L, R, e);
311}
312
313/// The UsualUnaryConversions() function is *not* called by this routine.
314/// See C99 6.3.2.1p[2-4] for more details.
315QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
316 SourceLocation OpLoc, bool isSizeof) {
317 // C99 6.5.3.4p1:
318 if (isa<FunctionType>(exprType) && isSizeof)
319 // alignof(function) is allowed.
320 Diag(OpLoc, diag::ext_sizeof_function_type);
321 else if (exprType->isVoidType())
322 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
323 else if (exprType->isIncompleteType()) {
324 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
325 diag::err_alignof_incomplete_type,
326 exprType.getAsString());
327 return QualType(); // error
328 }
329 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
330 return Context.getSizeType();
331}
332
333Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000334ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000335 SourceLocation LPLoc, TypeTy *Ty,
336 SourceLocation RPLoc) {
337 // If error parsing type, ignore.
338 if (Ty == 0) return true;
339
340 // Verify that this is a valid expression.
341 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
342
343 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
344
345 if (resultType.isNull())
346 return true;
347 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
348}
349
Chris Lattner5110ad52007-08-24 21:41:10 +0000350QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000351 DefaultFunctionArrayConversion(V);
352
Chris Lattnera16e42d2007-08-26 05:39:26 +0000353 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000354 if (const ComplexType *CT = V->getType()->getAsComplexType())
355 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000356
357 // Otherwise they pass through real integer and floating point types here.
358 if (V->getType()->isArithmeticType())
359 return V->getType();
360
361 // Reject anything else.
362 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
363 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000364}
365
366
Chris Lattner4b009652007-07-25 00:24:17 +0000367
Steve Naroff87d58b42007-09-16 03:34:24 +0000368Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000369 tok::TokenKind Kind,
370 ExprTy *Input) {
371 UnaryOperator::Opcode Opc;
372 switch (Kind) {
373 default: assert(0 && "Unknown unary op!");
374 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
375 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
376 }
377 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
378 if (result.isNull())
379 return true;
380 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
381}
382
383Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000384ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000385 ExprTy *Idx, SourceLocation RLoc) {
386 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
387
388 // Perform default conversions.
389 DefaultFunctionArrayConversion(LHSExp);
390 DefaultFunctionArrayConversion(RHSExp);
391
392 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
393
394 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000395 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000396 // in the subscript position. As a result, we need to derive the array base
397 // and index from the expression types.
398 Expr *BaseExpr, *IndexExpr;
399 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000400 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000401 BaseExpr = LHSExp;
402 IndexExpr = RHSExp;
403 // FIXME: need to deal with const...
404 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000405 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000406 // Handle the uncommon case of "123[Ptr]".
407 BaseExpr = RHSExp;
408 IndexExpr = LHSExp;
409 // FIXME: need to deal with const...
410 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000411 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
412 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000413 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000414
415 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman506806b2008-02-19 01:11:03 +0000416 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
Steve Naroff89345522007-08-03 22:40:33 +0000417 return Diag(LLoc, diag::err_ocuvector_component_access,
418 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000419 // FIXME: need to deal with const...
420 ResultType = VTy->getElementType();
421 } else {
422 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
423 RHSExp->getSourceRange());
424 }
425 // C99 6.5.2.1p1
426 if (!IndexExpr->getType()->isIntegerType())
427 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
428 IndexExpr->getSourceRange());
429
430 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
431 // the following check catches trying to index a pointer to a function (e.g.
432 // void (*)(int)). Functions are not objects in C99.
433 if (!ResultType->isObjectType())
434 return Diag(BaseExpr->getLocStart(),
435 diag::err_typecheck_subscript_not_object,
436 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
437
438 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
439}
440
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000441QualType Sema::
442CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
443 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000444 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000445
446 // The vector accessor can't exceed the number of elements.
447 const char *compStr = CompName.getName();
448 if (strlen(compStr) > vecType->getNumElements()) {
449 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
450 baseType.getAsString(), SourceRange(CompLoc));
451 return QualType();
452 }
453 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000454 if (vecType->getPointAccessorIdx(*compStr) != -1) {
455 do
456 compStr++;
457 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
458 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
459 do
460 compStr++;
461 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
462 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
463 do
464 compStr++;
465 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
466 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000467
468 if (*compStr) {
469 // We didn't get to the end of the string. This means the component names
470 // didn't come from the same set *or* we encountered an illegal name.
471 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
472 std::string(compStr,compStr+1), SourceRange(CompLoc));
473 return QualType();
474 }
475 // Each component accessor can't exceed the vector type.
476 compStr = CompName.getName();
477 while (*compStr) {
478 if (vecType->isAccessorWithinNumElements(*compStr))
479 compStr++;
480 else
481 break;
482 }
483 if (*compStr) {
484 // We didn't get to the end of the string. This means a component accessor
485 // exceeds the number of elements in the vector.
486 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
487 baseType.getAsString(), SourceRange(CompLoc));
488 return QualType();
489 }
490 // The component accessor looks fine - now we need to compute the actual type.
491 // The vector type is implied by the component accessor. For example,
492 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
493 unsigned CompSize = strlen(CompName.getName());
494 if (CompSize == 1)
495 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000496
497 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
498 // Now look up the TypeDefDecl from the vector type. Without this,
499 // diagostics look bad. We want OCU vector types to appear built-in.
500 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
501 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
502 return Context.getTypedefType(OCUVectorDecls[i]);
503 }
504 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000505}
506
Chris Lattner4b009652007-07-25 00:24:17 +0000507Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000508ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000509 tok::TokenKind OpKind, SourceLocation MemberLoc,
510 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000511 Expr *BaseExpr = static_cast<Expr *>(Base);
512 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000513
514 // Perform default conversions.
515 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000516
Steve Naroff2cb66382007-07-26 03:11:44 +0000517 QualType BaseType = BaseExpr->getType();
518 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000519
Chris Lattner4b009652007-07-25 00:24:17 +0000520 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000521 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000522 BaseType = PT->getPointeeType();
523 else
524 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
525 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000526 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000527 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000528 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000529 RecordDecl *RDecl = RTy->getDecl();
530 if (RTy->isIncompleteType())
531 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
532 BaseExpr->getSourceRange());
533 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000534 FieldDecl *MemberDecl = RDecl->getMember(&Member);
535 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000536 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
537 SourceRange(MemberLoc));
Eli Friedman76b49832008-02-06 22:48:16 +0000538
539 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000540 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000541 QualType MemberType = MemberDecl->getType();
542 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000543 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000544 MemberType = MemberType.getQualifiedType(combinedQualifiers);
545
546 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
547 MemberLoc, MemberType);
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000548 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000549 // Component access limited to variables (reject vec4.rg.g).
550 if (!isa<DeclRefExpr>(BaseExpr))
551 return Diag(OpLoc, diag::err_ocuvector_component_access,
552 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000553 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
554 if (ret.isNull())
555 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000556 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000557 } else if (BaseType->isObjCInterfaceType()) {
558 ObjCInterfaceDecl *IFace;
559 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
560 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000561 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000562 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
563 ObjCInterfaceDecl *clsDeclared;
564 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000565 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
566 OpKind==tok::arrow);
567 }
568 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
569 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000570}
571
Steve Naroff87d58b42007-09-16 03:34:24 +0000572/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000573/// This provides the location of the left/right parens and a list of comma
574/// locations.
575Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000576ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000577 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000578 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
579 Expr *Fn = static_cast<Expr *>(fn);
580 Expr **Args = reinterpret_cast<Expr**>(args);
581 assert(Fn && "no function call expression");
582
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000583 // Make the call expr early, before semantic checks. This guarantees cleanup
584 // of arguments and function on error.
585 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
586 Context.BoolTy, RParenLoc));
587
588 // Promote the function operand.
589 TheCall->setCallee(UsualUnaryConversions(Fn));
590
Chris Lattner4b009652007-07-25 00:24:17 +0000591 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
592 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000593 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000594 if (PT == 0)
595 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
596 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000597 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
598 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000599 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
600 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000601
602 // We know the result type of the call, set it.
603 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000604
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000605 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000606 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
607 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000608 unsigned NumArgsInProto = Proto->getNumArgs();
609 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000610
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000611 // If too few arguments are available, don't make the call.
612 if (NumArgs < NumArgsInProto)
613 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
614 Fn->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000615
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000616 // If too many are passed and not variadic, error on the extras and drop
617 // them.
618 if (NumArgs > NumArgsInProto) {
619 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000620 Diag(Args[NumArgsInProto]->getLocStart(),
621 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
622 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000623 Args[NumArgs-1]->getLocEnd()));
624 // This deletes the extra arguments.
625 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000626 }
627 NumArgsToCheck = NumArgsInProto;
628 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000629
Chris Lattner4b009652007-07-25 00:24:17 +0000630 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000631 for (unsigned i = 0; i != NumArgsToCheck; i++) {
632 Expr *Arg = Args[i];
Chris Lattner005ed752008-01-04 18:04:52 +0000633 QualType ProtoArgType = Proto->getArgType(i);
634 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000635
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000636 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000637 AssignConvertType ConvTy =
638 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000639 TheCall->setArg(i, Arg);
640
Chris Lattner005ed752008-01-04 18:04:52 +0000641 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
642 ArgType, Arg, "passing"))
643 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000644 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000645
646 // If this is a variadic call, handle args passed through "...".
647 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000648 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000649 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
650 Expr *Arg = Args[i];
651 DefaultArgumentPromotion(Arg);
652 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000653 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000654 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000655 } else {
656 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
657
Steve Naroffdb65e052007-08-28 23:30:39 +0000658 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000659 for (unsigned i = 0; i != NumArgs; i++) {
660 Expr *Arg = Args[i];
661 DefaultArgumentPromotion(Arg);
662 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000663 }
Chris Lattner4b009652007-07-25 00:24:17 +0000664 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000665
Chris Lattner2e64c072007-08-10 20:18:51 +0000666 // Do special checking on direct calls to functions.
667 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
668 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
669 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000670 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000671 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000672
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000673 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000674}
675
676Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000677ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000678 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000679 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000680 QualType literalType = QualType::getFromOpaquePtr(Ty);
681 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000682 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000683 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000684
Steve Naroffcb69fb72007-12-10 22:44:33 +0000685 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Narofff0b23542008-01-10 22:15:12 +0000686 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000687 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000688
689 bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
690 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000691 if (CheckForConstantInitializer(literalExpr, literalType))
692 return true;
693 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000694 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000695}
696
697Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000698ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000699 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000700 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000701
Steve Naroff0acc9c92007-09-15 18:49:24 +0000702 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000703 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000704
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000705 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
706 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
707 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000708}
709
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000710bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000711 assert(VectorTy->isVectorType() && "Not a vector type!");
712
713 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000714 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000715 return Diag(R.getBegin(),
716 Ty->isVectorType() ?
717 diag::err_invalid_conversion_between_vectors :
718 diag::err_invalid_conversion_between_vector_and_integer,
719 VectorTy.getAsString().c_str(),
720 Ty.getAsString().c_str(), R);
721 } else
722 return Diag(R.getBegin(),
723 diag::err_invalid_conversion_between_vector_and_scalar,
724 VectorTy.getAsString().c_str(),
725 Ty.getAsString().c_str(), R);
726
727 return false;
728}
729
Chris Lattner4b009652007-07-25 00:24:17 +0000730Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000731ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000732 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000733 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000734
735 Expr *castExpr = static_cast<Expr*>(Op);
736 QualType castType = QualType::getFromOpaquePtr(Ty);
737
Steve Naroff68adb482007-08-31 00:32:44 +0000738 UsualUnaryConversions(castExpr);
739
Chris Lattner4b009652007-07-25 00:24:17 +0000740 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
741 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000742 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Narofff459ee52008-01-24 22:55:05 +0000743 if (!castType->isScalarType() && !castType->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000744 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
745 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Steve Narofff459ee52008-01-24 22:55:05 +0000746 if (!castExpr->getType()->isScalarType() &&
747 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000748 return Diag(castExpr->getLocStart(),
749 diag::err_typecheck_expect_scalar_operand,
750 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000751
752 if (castExpr->getType()->isVectorType()) {
753 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
754 castExpr->getType(), castType))
755 return true;
756 } else if (castType->isVectorType()) {
757 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
758 castType, castExpr->getType()))
759 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000760 }
Chris Lattner4b009652007-07-25 00:24:17 +0000761 }
762 return new CastExpr(castType, castExpr, LParenLoc);
763}
764
Chris Lattner98a425c2007-11-26 01:40:58 +0000765/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
766/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000767inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
768 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
769 UsualUnaryConversions(cond);
770 UsualUnaryConversions(lex);
771 UsualUnaryConversions(rex);
772 QualType condT = cond->getType();
773 QualType lexT = lex->getType();
774 QualType rexT = rex->getType();
775
776 // first, check the condition.
777 if (!condT->isScalarType()) { // C99 6.5.15p2
778 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
779 condT.getAsString());
780 return QualType();
781 }
Chris Lattner992ae932008-01-06 22:42:25 +0000782
783 // Now check the two expressions.
784
785 // If both operands have arithmetic type, do the usual arithmetic conversions
786 // to find a common type: C99 6.5.15p3,5.
787 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000788 UsualArithmeticConversions(lex, rex);
789 return lex->getType();
790 }
Chris Lattner992ae932008-01-06 22:42:25 +0000791
792 // If both operands are the same structure or union type, the result is that
793 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000794 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000795 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000796 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000797 // "If both the operands have structure or union type, the result has
798 // that type." This implies that CV qualifiers are dropped.
799 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000800 }
Chris Lattner992ae932008-01-06 22:42:25 +0000801
802 // C99 6.5.15p5: "If both operands have void type, the result has void type."
803 if (lexT->isVoidType() && rexT->isVoidType())
804 return lexT.getUnqualifiedType();
Steve Naroff12ebf272008-01-08 01:11:38 +0000805
806 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
807 // the type of the other operand."
808 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000809 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000810 return lexT;
811 }
812 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000813 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000814 return rexT;
815 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000816 // Handle the case where both operands are pointers before we handle null
817 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000818 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
819 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
820 // get the "pointed to" types
821 QualType lhptee = LHSPT->getPointeeType();
822 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000823
Chris Lattner71225142007-07-31 21:27:01 +0000824 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
825 if (lhptee->isVoidType() &&
Eli Friedmanca07c902008-02-10 22:59:36 +0000826 (rhptee->isObjectType() || rhptee->isIncompleteType())) {
Chris Lattner35fef522008-02-20 20:55:12 +0000827 // Figure out necessary qualifiers (C99 6.5.15p6)
828 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000829 QualType destType = Context.getPointerType(destPointee);
830 ImpCastExprToType(lex, destType); // add qualifiers if necessary
831 ImpCastExprToType(rex, destType); // promote to void*
832 return destType;
833 }
Chris Lattner71225142007-07-31 21:27:01 +0000834 if (rhptee->isVoidType() &&
Eli Friedmanca07c902008-02-10 22:59:36 +0000835 (lhptee->isObjectType() || lhptee->isIncompleteType())) {
Chris Lattner35fef522008-02-20 20:55:12 +0000836 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000837 QualType destType = Context.getPointerType(destPointee);
838 ImpCastExprToType(lex, destType); // add qualifiers if necessary
839 ImpCastExprToType(rex, destType); // promote to void*
840 return destType;
841 }
Chris Lattner4b009652007-07-25 00:24:17 +0000842
Steve Naroff85f0dc52007-10-15 20:41:53 +0000843 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
844 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +0000845 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +0000846 lexT.getAsString(), rexT.getAsString(),
847 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +0000848 // In this situation, we assume void* type. No especially good
849 // reason, but this is what gcc does, and we do have to pick
850 // to get a consistent AST.
851 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
852 ImpCastExprToType(lex, voidPtrTy);
853 ImpCastExprToType(rex, voidPtrTy);
854 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +0000855 }
856 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000857 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
858 // differently qualified versions of compatible types, the result type is
859 // a pointer to an appropriately qualified version of the *composite*
860 // type.
Chris Lattner0ac51632008-01-06 22:50:31 +0000861 // FIXME: Need to return the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +0000862 // FIXME: Need to add qualifiers
Chris Lattner0ac51632008-01-06 22:50:31 +0000863 return lexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000864 }
Chris Lattner4b009652007-07-25 00:24:17 +0000865 }
Chris Lattner71225142007-07-31 21:27:01 +0000866
Chris Lattner992ae932008-01-06 22:42:25 +0000867 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000868 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
869 lexT.getAsString(), rexT.getAsString(),
870 lex->getSourceRange(), rex->getSourceRange());
871 return QualType();
872}
873
Steve Naroff87d58b42007-09-16 03:34:24 +0000874/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000875/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000876Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000877 SourceLocation ColonLoc,
878 ExprTy *Cond, ExprTy *LHS,
879 ExprTy *RHS) {
880 Expr *CondExpr = (Expr *) Cond;
881 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000882
883 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
884 // was the condition.
885 bool isLHSNull = LHSExpr == 0;
886 if (isLHSNull)
887 LHSExpr = CondExpr;
888
Chris Lattner4b009652007-07-25 00:24:17 +0000889 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
890 RHSExpr, QuestionLoc);
891 if (result.isNull())
892 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000893 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
894 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000895}
896
Steve Naroffdb65e052007-08-28 23:30:39 +0000897/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +0000898/// do not have a prototype. Arguments that have type float are promoted to
899/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000900void Sema::DefaultArgumentPromotion(Expr *&Expr) {
901 QualType Ty = Expr->getType();
902 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000903
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000904 if (Ty == Context.FloatTy)
Chris Lattnere992d6c2008-01-16 19:17:22 +0000905 ImpCastExprToType(Expr, Context.DoubleTy);
Steve Naroffbbaed752008-01-29 02:42:22 +0000906 else
907 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +0000908}
909
Chris Lattner4b009652007-07-25 00:24:17 +0000910/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
911void Sema::DefaultFunctionArrayConversion(Expr *&e) {
912 QualType t = e->getType();
913 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
914
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000915 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000916 ImpCastExprToType(e, ref->getReferenceeType()); // C++ [expr]
Chris Lattner4b009652007-07-25 00:24:17 +0000917 t = e->getType();
918 }
919 if (t->isFunctionType())
Chris Lattnere992d6c2008-01-16 19:17:22 +0000920 ImpCastExprToType(e, Context.getPointerType(t));
Steve Naroffac26e9a2008-02-09 16:59:44 +0000921 else if (const ArrayType *ary = t->getAsArrayType()) {
Steve Naroff9ffeda12008-02-09 17:25:18 +0000922 // Make sure we don't lose qualifiers when dealing with typedefs. Example:
Steve Naroffac26e9a2008-02-09 16:59:44 +0000923 // typedef int arr[10];
924 // void test2() {
925 // const arr b;
926 // b[4] = 1;
927 // }
928 QualType ELT = ary->getElementType();
Chris Lattner35fef522008-02-20 20:55:12 +0000929 // FIXME: Handle ASQualType
930 ELT = ELT.getQualifiedType(t.getCVRQualifiers()|ELT.getCVRQualifiers());
Steve Naroffac26e9a2008-02-09 16:59:44 +0000931 ImpCastExprToType(e, Context.getPointerType(ELT));
932 }
Chris Lattner4b009652007-07-25 00:24:17 +0000933}
934
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000935/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +0000936/// operators (C99 6.3). The conversions of array and function types are
937/// sometimes surpressed. For example, the array->pointer conversion doesn't
938/// apply if the array is an argument to the sizeof or address (&) operators.
939/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000940Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
941 QualType Ty = Expr->getType();
942 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000943
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000944 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000945 ImpCastExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000946 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000947 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000948 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +0000949 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000950 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000951 DefaultFunctionArrayConversion(Expr);
952
953 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000954}
955
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000956/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000957/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
958/// routine returns the first non-arithmetic type found. The client is
959/// responsible for emitting appropriate error diagnostics.
Steve Naroffe8419ca2008-01-15 22:21:49 +0000960/// FIXME: verify the conversion rules for "complex int" are consistent with GCC.
Steve Naroff8f708362007-08-24 19:07:16 +0000961QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
962 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000963 if (!isCompAssign) {
964 UsualUnaryConversions(lhsExpr);
965 UsualUnaryConversions(rhsExpr);
966 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000967 // For conversion purposes, we ignore any qualifiers.
968 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000969 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
970 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000971
972 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000973 if (lhs == rhs)
974 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000975
976 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
977 // The caller can deal with this (e.g. pointer + int).
978 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000979 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000980
981 // At this point, we have two different arithmetic types.
982
983 // Handle complex types first (C99 6.3.1.8p1).
984 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +0000985 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +0000986 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +0000987 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +0000988 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +0000989 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +0000990 }
Steve Naroffe8419ca2008-01-15 22:21:49 +0000991 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +0000992 // convert the lhs to the rhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +0000993 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +0000994 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000995 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000996 // This handles complex/complex, complex/float, or float/complex.
997 // When both operands are complex, the shorter operand is converted to the
998 // type of the longer, and that is the type of the result. This corresponds
999 // to what is done when combining two real floating-point operands.
1000 // The fun begins when size promotion occur across type domains.
1001 // From H&S 6.3.4: When one operand is complex and the other is a real
1002 // floating-point type, the less precise type is converted, within it's
1003 // real or complex domain, to the precision of the other type. For example,
1004 // when combining a "long double" with a "double _Complex", the
1005 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +00001006 int result = Context.compareFloatingType(lhs, rhs);
1007
1008 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001009 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1010 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001011 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001012 } else if (result < 0) { // The right side is bigger, convert lhs.
1013 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1014 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001015 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001016 }
1017 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1018 // domains match. This is a requirement for our implementation, C99
1019 // does not require this promotion.
1020 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1021 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001022 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001023 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001024 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001025 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001026 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001027 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001028 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001029 }
Chris Lattner4b009652007-07-25 00:24:17 +00001030 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001031 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001032 }
1033 // Now handle "real" floating types (i.e. float, double, long double).
1034 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1035 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001036 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001037 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001038 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001039 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001040 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001041 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001042 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001043 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001044 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001045 }
1046 // We have two real floating types, float/complex combos were handled above.
1047 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001048 int result = Context.compareFloatingType(lhs, rhs);
1049
1050 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001051 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001052 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001053 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001054 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001055 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001056 return rhs;
1057 }
1058 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001059 }
Steve Naroff43001212008-01-15 19:36:10 +00001060 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1061 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001062 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001063 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001064
Eli Friedman50727042008-02-08 01:19:44 +00001065 if (lhsComplexInt && rhsComplexInt) {
1066 if (Context.maxIntegerType(lhsComplexInt->getElementType(),
Eli Friedman94075c02008-02-08 01:24:30 +00001067 rhsComplexInt->getElementType()) == lhs) {
1068 // convert the rhs
1069 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1070 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001071 }
1072 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001073 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001074 return rhs;
1075 } else if (lhsComplexInt && rhs->isIntegerType()) {
1076 // convert the rhs to the lhs complex type.
1077 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1078 return lhs;
1079 } else if (rhsComplexInt && lhs->isIntegerType()) {
1080 // convert the lhs to the rhs complex type.
1081 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1082 return rhs;
1083 }
Steve Naroff43001212008-01-15 19:36:10 +00001084 }
Chris Lattner4b009652007-07-25 00:24:17 +00001085 // Finally, we have two differing integer types.
1086 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001087 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001088 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001089 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001090 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff8f708362007-08-24 19:07:16 +00001091 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001092}
1093
1094// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1095// being closely modeled after the C99 spec:-). The odd characteristic of this
1096// routine is it effectively iqnores the qualifiers on the top level pointee.
1097// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1098// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001099Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001100Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1101 QualType lhptee, rhptee;
1102
1103 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001104 lhptee = lhsType->getAsPointerType()->getPointeeType();
1105 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001106
1107 // make sure we operate on the canonical type
1108 lhptee = lhptee.getCanonicalType();
1109 rhptee = rhptee.getCanonicalType();
1110
Chris Lattner005ed752008-01-04 18:04:52 +00001111 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001112
1113 // C99 6.5.16.1p1: This following citation is common to constraints
1114 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1115 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001116 // FIXME: Handle ASQualType
1117 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1118 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001119 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001120
1121 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1122 // incomplete type and the other is a pointer to a qualified or unqualified
1123 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001124 if (lhptee->isVoidType()) {
1125 if (rhptee->isObjectType() || rhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001126 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001127
1128 // As an extension, we allow cast to/from void* to function pointer.
1129 if (rhptee->isFunctionType())
1130 return FunctionVoidPointer;
1131 }
1132
1133 if (rhptee->isVoidType()) {
1134 if (lhptee->isObjectType() || lhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001135 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001136
1137 // As an extension, we allow cast to/from void* to function pointer.
1138 if (lhptee->isFunctionType())
1139 return FunctionVoidPointer;
1140 }
1141
Chris Lattner4b009652007-07-25 00:24:17 +00001142 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1143 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001144 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1145 rhptee.getUnqualifiedType()))
1146 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001147 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001148}
1149
1150/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1151/// has code to accommodate several GCC extensions when type checking
1152/// pointers. Here are some objectionable examples that GCC considers warnings:
1153///
1154/// int a, *pint;
1155/// short *pshort;
1156/// struct foo *pfoo;
1157///
1158/// pint = pshort; // warning: assignment from incompatible pointer type
1159/// a = pint; // warning: assignment makes integer from pointer without a cast
1160/// pint = a; // warning: assignment makes pointer from integer without a cast
1161/// pint = pfoo; // warning: assignment from incompatible pointer type
1162///
1163/// As a result, the code for dealing with pointers is more complex than the
1164/// C99 spec dictates.
1165/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1166///
Chris Lattner005ed752008-01-04 18:04:52 +00001167Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001168Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001169 // Get canonical types. We're not formatting these types, just comparing
1170 // them.
1171 lhsType = lhsType.getCanonicalType();
1172 rhsType = rhsType.getCanonicalType();
1173
1174 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001175 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001176
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001177 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001178 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001179 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001180 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001181 }
Chris Lattner1853da22008-01-04 23:18:45 +00001182
Ted Kremenek42730c52008-01-07 19:49:32 +00001183 if (lhsType->isObjCQualifiedIdType()
1184 || rhsType->isObjCQualifiedIdType()) {
1185 if (Context.ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001186 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001187 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001188 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001189
1190 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1191 // For OCUVector, allow vector splats; float -> <n x float>
1192 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1193 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1194 return Compatible;
1195 }
1196
1197 // If LHS and RHS are both vectors of integer or both vectors of floating
1198 // point types, and the total vector length is the same, allow the
1199 // conversion. This is a bitcast; no bits are changed but the result type
1200 // is different.
1201 if (getLangOptions().LaxVectorConversions &&
1202 lhsType->isVectorType() && rhsType->isVectorType()) {
1203 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1204 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001205 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Nate Begemanec2d1062007-12-30 02:59:45 +00001206 return Compatible;
1207 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001208 }
1209 return Incompatible;
1210 }
1211
1212 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001213 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001214
1215 if (lhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001216 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001217 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001218
1219 if (rhsType->isPointerType())
1220 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001221 return Incompatible;
1222 }
1223
1224 if (rhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001225 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1226 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001227 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001228
1229 if (lhsType->isPointerType())
1230 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001231 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001232 }
1233
1234 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001235 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001236 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001237 }
1238 return Incompatible;
1239}
1240
Chris Lattner005ed752008-01-04 18:04:52 +00001241Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001242Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001243 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1244 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001245 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001246 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001247 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001248 return Compatible;
1249 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001250 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001251 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001252 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001253 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001254 //
1255 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1256 // are better understood.
1257 if (!lhsType->isReferenceType())
1258 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001259
Chris Lattner005ed752008-01-04 18:04:52 +00001260 Sema::AssignConvertType result =
1261 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001262
1263 // C99 6.5.16.1p2: The value of the right operand is converted to the
1264 // type of the assignment expression.
1265 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001266 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001267 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001268}
1269
Chris Lattner005ed752008-01-04 18:04:52 +00001270Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001271Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1272 return CheckAssignmentConstraints(lhsType, rhsType);
1273}
1274
Chris Lattner2c8bff72007-12-12 05:47:28 +00001275QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001276 Diag(loc, diag::err_typecheck_invalid_operands,
1277 lex->getType().getAsString(), rex->getType().getAsString(),
1278 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001279 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001280}
1281
1282inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1283 Expr *&rex) {
1284 QualType lhsType = lex->getType(), rhsType = rex->getType();
1285
1286 // make sure the vector types are identical.
1287 if (lhsType == rhsType)
1288 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001289
1290 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1291 // promote the rhs to the vector type.
1292 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1293 if (V->getElementType().getCanonicalType().getTypePtr()
1294 == rhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001295 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001296 return lhsType;
1297 }
1298 }
1299
1300 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1301 // promote the lhs to the vector type.
1302 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1303 if (V->getElementType().getCanonicalType().getTypePtr()
1304 == lhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001305 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001306 return rhsType;
1307 }
1308 }
1309
Chris Lattner4b009652007-07-25 00:24:17 +00001310 // You cannot convert between vector values of different size.
1311 Diag(loc, diag::err_typecheck_vector_not_convertable,
1312 lex->getType().getAsString(), rex->getType().getAsString(),
1313 lex->getSourceRange(), rex->getSourceRange());
1314 return QualType();
1315}
1316
1317inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001318 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001319{
1320 QualType lhsType = lex->getType(), rhsType = rex->getType();
1321
1322 if (lhsType->isVectorType() || rhsType->isVectorType())
1323 return CheckVectorOperands(loc, lex, rex);
1324
Steve Naroff8f708362007-08-24 19:07:16 +00001325 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001326
Chris Lattner4b009652007-07-25 00:24:17 +00001327 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001328 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001329 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001330}
1331
1332inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001333 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001334{
1335 QualType lhsType = lex->getType(), rhsType = rex->getType();
1336
Steve Naroff8f708362007-08-24 19:07:16 +00001337 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001338
Chris Lattner4b009652007-07-25 00:24:17 +00001339 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001340 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001341 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001342}
1343
1344inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001345 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001346{
1347 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1348 return CheckVectorOperands(loc, lex, rex);
1349
Steve Naroff8f708362007-08-24 19:07:16 +00001350 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001351
1352 // handle the common case first (both operands are arithmetic).
1353 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001354 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001355
1356 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1357 return lex->getType();
1358 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1359 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001360 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001361}
1362
1363inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001364 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001365{
1366 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1367 return CheckVectorOperands(loc, lex, rex);
1368
Steve Naroff8f708362007-08-24 19:07:16 +00001369 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001370
Chris Lattnerf6da2912007-12-09 21:53:25 +00001371 // Enforce type constraints: C99 6.5.6p3.
1372
1373 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001374 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001375 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001376
1377 // Either ptr - int or ptr - ptr.
1378 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001379 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001380
Chris Lattnerf6da2912007-12-09 21:53:25 +00001381 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001382 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001383 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001384 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001385 Diag(loc, diag::ext_gnu_void_ptr,
1386 lex->getSourceRange(), rex->getSourceRange());
1387 } else {
1388 Diag(loc, diag::err_typecheck_sub_ptr_object,
1389 lex->getType().getAsString(), lex->getSourceRange());
1390 return QualType();
1391 }
1392 }
1393
1394 // The result type of a pointer-int computation is the pointer type.
1395 if (rex->getType()->isIntegerType())
1396 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001397
Chris Lattnerf6da2912007-12-09 21:53:25 +00001398 // Handle pointer-pointer subtractions.
1399 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001400 QualType rpointee = RHSPTy->getPointeeType();
1401
Chris Lattnerf6da2912007-12-09 21:53:25 +00001402 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001403 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001404 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001405 if (rpointee->isVoidType()) {
1406 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001407 Diag(loc, diag::ext_gnu_void_ptr,
1408 lex->getSourceRange(), rex->getSourceRange());
1409 } else {
1410 Diag(loc, diag::err_typecheck_sub_ptr_object,
1411 rex->getType().getAsString(), rex->getSourceRange());
1412 return QualType();
1413 }
1414 }
1415
1416 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001417 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1418 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001419 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1420 lex->getType().getAsString(), rex->getType().getAsString(),
1421 lex->getSourceRange(), rex->getSourceRange());
1422 return QualType();
1423 }
1424
1425 return Context.getPointerDiffType();
1426 }
1427 }
1428
Chris Lattner2c8bff72007-12-12 05:47:28 +00001429 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001430}
1431
1432inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattner2c8bff72007-12-12 05:47:28 +00001433 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1434 // C99 6.5.7p2: Each of the operands shall have integer type.
1435 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1436 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001437
Chris Lattner2c8bff72007-12-12 05:47:28 +00001438 // Shifts don't perform usual arithmetic conversions, they just do integer
1439 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001440 if (!isCompAssign)
1441 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001442 UsualUnaryConversions(rex);
1443
1444 // "The type of the result is that of the promoted left operand."
1445 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001446}
1447
Chris Lattner254f3bc2007-08-26 01:18:55 +00001448inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1449 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001450{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001451 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001452 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1453 UsualArithmeticConversions(lex, rex);
1454 else {
1455 UsualUnaryConversions(lex);
1456 UsualUnaryConversions(rex);
1457 }
Chris Lattner4b009652007-07-25 00:24:17 +00001458 QualType lType = lex->getType();
1459 QualType rType = rex->getType();
1460
Ted Kremenek486509e2007-10-29 17:13:39 +00001461 // For non-floating point types, check for self-comparisons of the form
1462 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1463 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001464 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001465 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1466 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001467 if (DRL->getDecl() == DRR->getDecl())
1468 Diag(loc, diag::warn_selfcomparison);
1469 }
1470
Chris Lattner254f3bc2007-08-26 01:18:55 +00001471 if (isRelational) {
1472 if (lType->isRealType() && rType->isRealType())
1473 return Context.IntTy;
1474 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001475 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001476 if (lType->isFloatingType()) {
1477 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001478 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001479 }
1480
Chris Lattner254f3bc2007-08-26 01:18:55 +00001481 if (lType->isArithmeticType() && rType->isArithmeticType())
1482 return Context.IntTy;
1483 }
Chris Lattner4b009652007-07-25 00:24:17 +00001484
Chris Lattner22be8422007-08-26 01:10:14 +00001485 bool LHSIsNull = lex->isNullPointerConstant(Context);
1486 bool RHSIsNull = rex->isNullPointerConstant(Context);
1487
Chris Lattner254f3bc2007-08-26 01:18:55 +00001488 // All of the following pointer related warnings are GCC extensions, except
1489 // when handling null pointer constants. One day, we can consider making them
1490 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001491 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Eli Friedman50727042008-02-08 01:19:44 +00001492 QualType lpointee = lType->getAsPointerType()->getPointeeType();
1493 QualType rpointee = rType->getAsPointerType()->getPointeeType();
1494
Steve Naroff3b435622007-11-13 14:57:38 +00001495 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Steve Naroff577f9722008-01-29 18:58:14 +00001496 !lpointee->isVoidType() && !lpointee->isVoidType() &&
1497 !Context.typesAreCompatible(lpointee.getUnqualifiedType(),
Eli Friedman50727042008-02-08 01:19:44 +00001498 rpointee.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001499 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1500 lType.getAsString(), rType.getAsString(),
1501 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001502 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001503 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001504 return Context.IntTy;
1505 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001506 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
1507 && Context.ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001508 ImpCastExprToType(rex, lType);
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001509 return Context.IntTy;
1510 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001511 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001512 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001513 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1514 lType.getAsString(), rType.getAsString(),
1515 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001516 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001517 return Context.IntTy;
1518 }
1519 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001520 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001521 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1522 lType.getAsString(), rType.getAsString(),
1523 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001524 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001525 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001526 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001527 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001528}
1529
Chris Lattner4b009652007-07-25 00:24:17 +00001530inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001531 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001532{
1533 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1534 return CheckVectorOperands(loc, lex, rex);
1535
Steve Naroff8f708362007-08-24 19:07:16 +00001536 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001537
1538 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001539 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001540 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001541}
1542
1543inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1544 Expr *&lex, Expr *&rex, SourceLocation loc)
1545{
1546 UsualUnaryConversions(lex);
1547 UsualUnaryConversions(rex);
1548
1549 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1550 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001551 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001552}
1553
1554inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001555 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001556{
1557 QualType lhsType = lex->getType();
1558 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001559 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1560
1561 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001562 case Expr::MLV_Valid:
1563 break;
1564 case Expr::MLV_ConstQualified:
1565 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1566 return QualType();
1567 case Expr::MLV_ArrayType:
1568 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1569 lhsType.getAsString(), lex->getSourceRange());
1570 return QualType();
1571 case Expr::MLV_NotObjectType:
1572 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1573 lhsType.getAsString(), lex->getSourceRange());
1574 return QualType();
1575 case Expr::MLV_InvalidExpression:
1576 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1577 lex->getSourceRange());
1578 return QualType();
1579 case Expr::MLV_IncompleteType:
1580 case Expr::MLV_IncompleteVoidType:
1581 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1582 lhsType.getAsString(), lex->getSourceRange());
1583 return QualType();
1584 case Expr::MLV_DuplicateVectorComponents:
1585 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1586 lex->getSourceRange());
1587 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001588 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001589
Chris Lattner005ed752008-01-04 18:04:52 +00001590 AssignConvertType ConvTy;
1591 if (compoundType.isNull())
1592 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1593 else
1594 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1595
1596 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1597 rex, "assigning"))
1598 return QualType();
1599
Chris Lattner4b009652007-07-25 00:24:17 +00001600 // C99 6.5.16p3: The type of an assignment expression is the type of the
1601 // left operand unless the left operand has qualified type, in which case
1602 // it is the unqualified version of the type of the left operand.
1603 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1604 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001605 // C++ 5.17p1: the type of the assignment expression is that of its left
1606 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001607 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001608}
1609
1610inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1611 Expr *&lex, Expr *&rex, SourceLocation loc) {
1612 UsualUnaryConversions(rex);
1613 return rex->getType();
1614}
1615
1616/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1617/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1618QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1619 QualType resType = op->getType();
1620 assert(!resType.isNull() && "no type for increment/decrement expression");
1621
Steve Naroffd30e1932007-08-24 17:20:07 +00001622 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001623 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001624 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1625 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1626 resType.getAsString(), op->getSourceRange());
1627 return QualType();
1628 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001629 } else if (!resType->isRealType()) {
1630 if (resType->isComplexType())
1631 // C99 does not support ++/-- on complex types.
1632 Diag(OpLoc, diag::ext_integer_increment_complex,
1633 resType.getAsString(), op->getSourceRange());
1634 else {
1635 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1636 resType.getAsString(), op->getSourceRange());
1637 return QualType();
1638 }
Chris Lattner4b009652007-07-25 00:24:17 +00001639 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001640 // At this point, we know we have a real, complex or pointer type.
1641 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001642 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1643 if (mlval != Expr::MLV_Valid) {
1644 // FIXME: emit a more precise diagnostic...
1645 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1646 op->getSourceRange());
1647 return QualType();
1648 }
1649 return resType;
1650}
1651
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001652/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001653/// This routine allows us to typecheck complex/recursive expressions
1654/// where the declaration is needed for type checking. Here are some
1655/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001656static ValueDecl *getPrimaryDecl(Expr *e) {
Chris Lattner4b009652007-07-25 00:24:17 +00001657 switch (e->getStmtClass()) {
1658 case Stmt::DeclRefExprClass:
1659 return cast<DeclRefExpr>(e)->getDecl();
1660 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001661 // Fields cannot be declared with a 'register' storage class.
1662 // &X->f is always ok, even if X is declared register.
1663 if (cast<MemberExpr>(e)->isArrow())
1664 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001665 return getPrimaryDecl(cast<MemberExpr>(e)->getBase());
1666 case Stmt::ArraySubscriptExprClass: {
1667 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1668
1669 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(e)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001670 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001671 return 0;
1672 else
1673 return VD;
1674 }
Chris Lattner4b009652007-07-25 00:24:17 +00001675 case Stmt::UnaryOperatorClass:
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001676 return getPrimaryDecl(cast<UnaryOperator>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001677 case Stmt::ParenExprClass:
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001678 return getPrimaryDecl(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001679 case Stmt::ImplicitCastExprClass:
1680 // &X[4] when X is an array, has an implicit cast from array to pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001681 return getPrimaryDecl(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001682 default:
1683 return 0;
1684 }
1685}
1686
1687/// CheckAddressOfOperand - The operand of & must be either a function
1688/// designator or an lvalue designating an object. If it is an lvalue, the
1689/// object cannot be declared with storage class register or be a bit field.
1690/// Note: The usual conversions are *not* applied to the operand of the &
1691/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1692QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001693 if (getLangOptions().C99) {
1694 // Implement C99-only parts of addressof rules.
1695 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1696 if (uOp->getOpcode() == UnaryOperator::Deref)
1697 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1698 // (assuming the deref expression is valid).
1699 return uOp->getSubExpr()->getType();
1700 }
1701 // Technically, there should be a check for array subscript
1702 // expressions here, but the result of one is always an lvalue anyway.
1703 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001704 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001705 Expr::isLvalueResult lval = op->isLvalue();
1706
1707 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001708 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1709 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001710 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1711 op->getSourceRange());
1712 return QualType();
1713 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00001714 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1715 if (MemExpr->getMemberDecl()->isBitField()) {
1716 Diag(OpLoc, diag::err_typecheck_address_of,
1717 std::string("bit-field"), op->getSourceRange());
1718 return QualType();
1719 }
1720 // Check for Apple extension for accessing vector components.
1721 } else if (isa<ArraySubscriptExpr>(op) &&
1722 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
1723 Diag(OpLoc, diag::err_typecheck_address_of,
1724 std::string("vector"), op->getSourceRange());
1725 return QualType();
1726 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00001727 // We have an lvalue with a decl. Make sure the decl is not declared
1728 // with the register storage-class specifier.
1729 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1730 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00001731 Diag(OpLoc, diag::err_typecheck_address_of,
1732 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001733 return QualType();
1734 }
1735 } else
1736 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00001737 }
1738 // If the operand has type "type", the result has type "pointer to type".
1739 return Context.getPointerType(op->getType());
1740}
1741
1742QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1743 UsualUnaryConversions(op);
1744 QualType qType = op->getType();
1745
Chris Lattner7931f4a2007-07-31 16:53:04 +00001746 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001747 // Note that per both C89 and C99, this is always legal, even
1748 // if ptype is an incomplete type or void.
1749 // It would be possible to warn about dereferencing a
1750 // void pointer, but it's completely well-defined,
1751 // and such a warning is unlikely to catch any mistakes.
1752 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001753 }
1754 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1755 qType.getAsString(), op->getSourceRange());
1756 return QualType();
1757}
1758
1759static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1760 tok::TokenKind Kind) {
1761 BinaryOperator::Opcode Opc;
1762 switch (Kind) {
1763 default: assert(0 && "Unknown binop!");
1764 case tok::star: Opc = BinaryOperator::Mul; break;
1765 case tok::slash: Opc = BinaryOperator::Div; break;
1766 case tok::percent: Opc = BinaryOperator::Rem; break;
1767 case tok::plus: Opc = BinaryOperator::Add; break;
1768 case tok::minus: Opc = BinaryOperator::Sub; break;
1769 case tok::lessless: Opc = BinaryOperator::Shl; break;
1770 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1771 case tok::lessequal: Opc = BinaryOperator::LE; break;
1772 case tok::less: Opc = BinaryOperator::LT; break;
1773 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1774 case tok::greater: Opc = BinaryOperator::GT; break;
1775 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1776 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1777 case tok::amp: Opc = BinaryOperator::And; break;
1778 case tok::caret: Opc = BinaryOperator::Xor; break;
1779 case tok::pipe: Opc = BinaryOperator::Or; break;
1780 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1781 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1782 case tok::equal: Opc = BinaryOperator::Assign; break;
1783 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1784 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1785 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1786 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1787 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1788 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1789 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1790 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1791 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1792 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1793 case tok::comma: Opc = BinaryOperator::Comma; break;
1794 }
1795 return Opc;
1796}
1797
1798static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1799 tok::TokenKind Kind) {
1800 UnaryOperator::Opcode Opc;
1801 switch (Kind) {
1802 default: assert(0 && "Unknown unary op!");
1803 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1804 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1805 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1806 case tok::star: Opc = UnaryOperator::Deref; break;
1807 case tok::plus: Opc = UnaryOperator::Plus; break;
1808 case tok::minus: Opc = UnaryOperator::Minus; break;
1809 case tok::tilde: Opc = UnaryOperator::Not; break;
1810 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1811 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1812 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1813 case tok::kw___real: Opc = UnaryOperator::Real; break;
1814 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1815 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1816 }
1817 return Opc;
1818}
1819
1820// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001821Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001822 ExprTy *LHS, ExprTy *RHS) {
1823 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1824 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1825
Steve Naroff87d58b42007-09-16 03:34:24 +00001826 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1827 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001828
1829 QualType ResultTy; // Result type of the binary operator.
1830 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1831
1832 switch (Opc) {
1833 default:
1834 assert(0 && "Unknown binary expr!");
1835 case BinaryOperator::Assign:
1836 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1837 break;
1838 case BinaryOperator::Mul:
1839 case BinaryOperator::Div:
1840 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1841 break;
1842 case BinaryOperator::Rem:
1843 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1844 break;
1845 case BinaryOperator::Add:
1846 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1847 break;
1848 case BinaryOperator::Sub:
1849 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1850 break;
1851 case BinaryOperator::Shl:
1852 case BinaryOperator::Shr:
1853 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1854 break;
1855 case BinaryOperator::LE:
1856 case BinaryOperator::LT:
1857 case BinaryOperator::GE:
1858 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001859 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001860 break;
1861 case BinaryOperator::EQ:
1862 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001863 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001864 break;
1865 case BinaryOperator::And:
1866 case BinaryOperator::Xor:
1867 case BinaryOperator::Or:
1868 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1869 break;
1870 case BinaryOperator::LAnd:
1871 case BinaryOperator::LOr:
1872 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1873 break;
1874 case BinaryOperator::MulAssign:
1875 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001876 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001877 if (!CompTy.isNull())
1878 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1879 break;
1880 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001881 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001882 if (!CompTy.isNull())
1883 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1884 break;
1885 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001886 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001887 if (!CompTy.isNull())
1888 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1889 break;
1890 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001891 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001892 if (!CompTy.isNull())
1893 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1894 break;
1895 case BinaryOperator::ShlAssign:
1896 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001897 CompTy = CheckShiftOperands(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::AndAssign:
1902 case BinaryOperator::XorAssign:
1903 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001904 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001905 if (!CompTy.isNull())
1906 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1907 break;
1908 case BinaryOperator::Comma:
1909 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1910 break;
1911 }
1912 if (ResultTy.isNull())
1913 return true;
1914 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001915 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001916 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001917 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001918}
1919
1920// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001921Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001922 ExprTy *input) {
1923 Expr *Input = (Expr*)input;
1924 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1925 QualType resultType;
1926 switch (Opc) {
1927 default:
1928 assert(0 && "Unimplemented unary expr!");
1929 case UnaryOperator::PreInc:
1930 case UnaryOperator::PreDec:
1931 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1932 break;
1933 case UnaryOperator::AddrOf:
1934 resultType = CheckAddressOfOperand(Input, OpLoc);
1935 break;
1936 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001937 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001938 resultType = CheckIndirectionOperand(Input, OpLoc);
1939 break;
1940 case UnaryOperator::Plus:
1941 case UnaryOperator::Minus:
1942 UsualUnaryConversions(Input);
1943 resultType = Input->getType();
1944 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1945 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1946 resultType.getAsString());
1947 break;
1948 case UnaryOperator::Not: // bitwise complement
1949 UsualUnaryConversions(Input);
1950 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001951 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1952 if (!resultType->isIntegerType()) {
1953 if (resultType->isComplexType())
1954 // C99 does not support '~' for complex conjugation.
1955 Diag(OpLoc, diag::ext_integer_complement_complex,
1956 resultType.getAsString());
1957 else
1958 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1959 resultType.getAsString());
1960 }
Chris Lattner4b009652007-07-25 00:24:17 +00001961 break;
1962 case UnaryOperator::LNot: // logical negation
1963 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1964 DefaultFunctionArrayConversion(Input);
1965 resultType = Input->getType();
1966 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1967 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1968 resultType.getAsString());
1969 // LNot always has type int. C99 6.5.3.3p5.
1970 resultType = Context.IntTy;
1971 break;
1972 case UnaryOperator::SizeOf:
1973 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1974 break;
1975 case UnaryOperator::AlignOf:
1976 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1977 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001978 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001979 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001980 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001981 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001982 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001983 resultType = Input->getType();
1984 break;
1985 }
1986 if (resultType.isNull())
1987 return true;
1988 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1989}
1990
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001991/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1992Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001993 SourceLocation LabLoc,
1994 IdentifierInfo *LabelII) {
1995 // Look up the record for this label identifier.
1996 LabelStmt *&LabelDecl = LabelMap[LabelII];
1997
1998 // If we haven't seen this label yet, create a forward reference.
1999 if (LabelDecl == 0)
2000 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2001
2002 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002003 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2004 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002005}
2006
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002007Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002008 SourceLocation RPLoc) { // "({..})"
2009 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2010 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2011 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2012
2013 // FIXME: there are a variety of strange constraints to enforce here, for
2014 // example, it is not possible to goto into a stmt expression apparently.
2015 // More semantic analysis is needed.
2016
2017 // FIXME: the last statement in the compount stmt has its value used. We
2018 // should not warn about it being unused.
2019
2020 // If there are sub stmts in the compound stmt, take the type of the last one
2021 // as the type of the stmtexpr.
2022 QualType Ty = Context.VoidTy;
2023
2024 if (!Compound->body_empty())
2025 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2026 Ty = LastExpr->getType();
2027
2028 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2029}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002030
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002031Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002032 SourceLocation TypeLoc,
2033 TypeTy *argty,
2034 OffsetOfComponent *CompPtr,
2035 unsigned NumComponents,
2036 SourceLocation RPLoc) {
2037 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2038 assert(!ArgTy.isNull() && "Missing type argument!");
2039
2040 // We must have at least one component that refers to the type, and the first
2041 // one is known to be a field designator. Verify that the ArgTy represents
2042 // a struct/union/class.
2043 if (!ArgTy->isRecordType())
2044 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2045
2046 // Otherwise, create a compound literal expression as the base, and
2047 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002048 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002049
Chris Lattnerb37522e2007-08-31 21:49:13 +00002050 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2051 // GCC extension, diagnose them.
2052 if (NumComponents != 1)
2053 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2054 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2055
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002056 for (unsigned i = 0; i != NumComponents; ++i) {
2057 const OffsetOfComponent &OC = CompPtr[i];
2058 if (OC.isBrackets) {
2059 // Offset of an array sub-field. TODO: Should we allow vector elements?
2060 const ArrayType *AT = Res->getType()->getAsArrayType();
2061 if (!AT) {
2062 delete Res;
2063 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2064 Res->getType().getAsString());
2065 }
2066
Chris Lattner2af6a802007-08-30 17:59:59 +00002067 // FIXME: C++: Verify that operator[] isn't overloaded.
2068
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002069 // C99 6.5.2.1p1
2070 Expr *Idx = static_cast<Expr*>(OC.U.E);
2071 if (!Idx->getType()->isIntegerType())
2072 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2073 Idx->getSourceRange());
2074
2075 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2076 continue;
2077 }
2078
2079 const RecordType *RC = Res->getType()->getAsRecordType();
2080 if (!RC) {
2081 delete Res;
2082 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2083 Res->getType().getAsString());
2084 }
2085
2086 // Get the decl corresponding to this.
2087 RecordDecl *RD = RC->getDecl();
2088 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2089 if (!MemberDecl)
2090 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2091 OC.U.IdentInfo->getName(),
2092 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002093
2094 // FIXME: C++: Verify that MemberDecl isn't a static field.
2095 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002096 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2097 // matter here.
2098 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002099 }
2100
2101 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2102 BuiltinLoc);
2103}
2104
2105
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002106Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002107 TypeTy *arg1, TypeTy *arg2,
2108 SourceLocation RPLoc) {
2109 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2110 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2111
2112 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2113
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002114 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002115}
2116
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002117Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002118 ExprTy *expr1, ExprTy *expr2,
2119 SourceLocation RPLoc) {
2120 Expr *CondExpr = static_cast<Expr*>(cond);
2121 Expr *LHSExpr = static_cast<Expr*>(expr1);
2122 Expr *RHSExpr = static_cast<Expr*>(expr2);
2123
2124 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2125
2126 // The conditional expression is required to be a constant expression.
2127 llvm::APSInt condEval(32);
2128 SourceLocation ExpLoc;
2129 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2130 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2131 CondExpr->getSourceRange());
2132
2133 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2134 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2135 RHSExpr->getType();
2136 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2137}
2138
Nate Begemanbd881ef2008-01-30 20:50:20 +00002139/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002140/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002141/// The number of arguments has already been validated to match the number of
2142/// arguments in FnType.
2143static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002144 unsigned NumParams = FnType->getNumArgs();
2145 for (unsigned i = 0; i != NumParams; ++i)
Nate Begemanbd881ef2008-01-30 20:50:20 +00002146 if (Args[i]->getType().getCanonicalType() !=
2147 FnType->getArgType(i).getCanonicalType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002148 return false;
2149 return true;
2150}
2151
2152Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2153 SourceLocation *CommaLocs,
2154 SourceLocation BuiltinLoc,
2155 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002156 // __builtin_overload requires at least 2 arguments
2157 if (NumArgs < 2)
2158 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2159 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002160
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002161 // The first argument is required to be a constant expression. It tells us
2162 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002163 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002164 Expr *NParamsExpr = Args[0];
2165 llvm::APSInt constEval(32);
2166 SourceLocation ExpLoc;
2167 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2168 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2169 NParamsExpr->getSourceRange());
2170
2171 // Verify that the number of parameters is > 0
2172 unsigned NumParams = constEval.getZExtValue();
2173 if (NumParams == 0)
2174 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2175 NParamsExpr->getSourceRange());
2176 // Verify that we have at least 1 + NumParams arguments to the builtin.
2177 if ((NumParams + 1) > NumArgs)
2178 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2179 SourceRange(BuiltinLoc, RParenLoc));
2180
2181 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002182 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002183 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002184 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2185 // UsualUnaryConversions will convert the function DeclRefExpr into a
2186 // pointer to function.
2187 Expr *Fn = UsualUnaryConversions(Args[i]);
2188 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002189 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2190 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2191 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2192 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002193
2194 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2195 // parameters, and the number of parameters must match the value passed to
2196 // the builtin.
2197 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002198 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2199 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002200
2201 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002202 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002203 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002204 if (ExprsMatchFnType(Args+1, FnType)) {
2205 if (OE)
2206 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2207 OE->getFn()->getSourceRange());
2208 // Remember our match, and continue processing the remaining arguments
2209 // to catch any errors.
2210 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2211 BuiltinLoc, RParenLoc);
2212 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002213 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002214 // Return the newly created OverloadExpr node, if we succeded in matching
2215 // exactly one of the candidate functions.
2216 if (OE)
2217 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002218
2219 // If we didn't find a matching function Expr in the __builtin_overload list
2220 // the return an error.
2221 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002222 for (unsigned i = 0; i != NumParams; ++i) {
2223 if (i != 0) typeNames += ", ";
2224 typeNames += Args[i+1]->getType().getAsString();
2225 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002226
2227 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2228 SourceRange(BuiltinLoc, RParenLoc));
2229}
2230
Anders Carlsson36760332007-10-15 20:28:48 +00002231Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2232 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002233 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002234 Expr *E = static_cast<Expr*>(expr);
2235 QualType T = QualType::getFromOpaquePtr(type);
2236
2237 InitBuiltinVaListType();
2238
Chris Lattner005ed752008-01-04 18:04:52 +00002239 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2240 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002241 return Diag(E->getLocStart(),
2242 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2243 E->getType().getAsString(),
2244 E->getSourceRange());
2245
2246 // FIXME: Warn if a non-POD type is passed in.
2247
2248 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2249}
2250
Chris Lattner005ed752008-01-04 18:04:52 +00002251bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2252 SourceLocation Loc,
2253 QualType DstType, QualType SrcType,
2254 Expr *SrcExpr, const char *Flavor) {
2255 // Decode the result (notice that AST's are still created for extensions).
2256 bool isInvalid = false;
2257 unsigned DiagKind;
2258 switch (ConvTy) {
2259 default: assert(0 && "Unknown conversion type");
2260 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002261 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002262 DiagKind = diag::ext_typecheck_convert_pointer_int;
2263 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002264 case IntToPointer:
2265 DiagKind = diag::ext_typecheck_convert_int_pointer;
2266 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002267 case IncompatiblePointer:
2268 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2269 break;
2270 case FunctionVoidPointer:
2271 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2272 break;
2273 case CompatiblePointerDiscardsQualifiers:
2274 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2275 break;
2276 case Incompatible:
2277 DiagKind = diag::err_typecheck_convert_incompatible;
2278 isInvalid = true;
2279 break;
2280 }
2281
2282 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2283 SrcExpr->getSourceRange());
2284 return isInvalid;
2285}
2286