blob: 2cea607343e41eb2cedaf7c88040f4ad50c06adf [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
17#include "clang/AST/Decl.h"
Steve Narofffa465d12007-10-02 20:01:56 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/TargetInfo.h"
27#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Steve Naroff87d58b42007-09-16 03:34:24 +000031/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000032/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
33/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
34/// multiple tokens. However, the common case is that StringToks points to one
35/// string.
36///
37Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000038Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000039 assert(NumStringToks && "Must have at least one string!");
40
41 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
42 if (Literal.hadError)
43 return ExprResult(true);
44
45 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
46 for (unsigned i = 0; i != NumStringToks; ++i)
47 StringTokLocs.push_back(StringToks[i].getLocation());
48
49 // FIXME: handle wchar_t
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000050 QualType t;
51
52 if (Literal.Pascal)
53 t = Context.getPointerType(Context.UnsignedCharTy);
54 else
55 t = Context.getPointerType(Context.CharTy);
56
57 if (Literal.Pascal && Literal.GetStringLength() > 256)
58 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
59 SourceRange(StringToks[0].getLocation(),
60 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000061
62 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
63 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000064 Literal.AnyWide, t,
65 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000066 StringToks[NumStringToks-1].getLocation());
67}
68
69
Steve Naroff0acc9c92007-09-15 18:49:24 +000070/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000071/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
72/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000073Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000074 IdentifierInfo &II,
75 bool HasTrailingLParen) {
76 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000077 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000078 if (D == 0) {
79 // Otherwise, this could be an implicitly declared function reference (legal
80 // in C90, extension in C99).
81 if (HasTrailingLParen &&
82 // Not in C++.
83 !getLangOptions().CPlusPlus)
84 D = ImplicitlyDefineFunction(Loc, II, S);
85 else {
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000086 if (CurMethodDecl) {
87 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
88 ObjcInterfaceDecl *clsDeclared;
Steve Naroff6b759ce2007-11-15 02:58:25 +000089 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
90 IdentifierInfo &II = Context.Idents.get("self");
91 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
92 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
93 static_cast<Expr*>(SelfExpr.Val), true, true);
94 }
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000095 }
Chris Lattner4b009652007-07-25 00:24:17 +000096 // If this name wasn't predeclared and if this is not a function call,
97 // diagnose the problem.
98 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
99 }
100 }
Steve Naroff91b03f72007-08-28 03:03:08 +0000101 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +0000102 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000103 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000104 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000105 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000106 }
Chris Lattner4b009652007-07-25 00:24:17 +0000107 if (isa<TypedefDecl>(D))
108 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
109
110 assert(0 && "Invalid decl");
111 abort();
112}
113
Steve Naroff87d58b42007-09-16 03:34:24 +0000114Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000115 tok::TokenKind Kind) {
116 PreDefinedExpr::IdentType IT;
117
118 switch (Kind) {
119 default:
120 assert(0 && "Unknown simple primary expr!");
121 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
122 IT = PreDefinedExpr::Func;
123 break;
124 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
125 IT = PreDefinedExpr::Function;
126 break;
127 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
128 IT = PreDefinedExpr::PrettyFunction;
129 break;
130 }
131
132 // Pre-defined identifiers are always of type char *.
133 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
134}
135
Steve Naroff87d58b42007-09-16 03:34:24 +0000136Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000137 llvm::SmallString<16> CharBuffer;
138 CharBuffer.resize(Tok.getLength());
139 const char *ThisTokBegin = &CharBuffer[0];
140 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
141
142 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
143 Tok.getLocation(), PP);
144 if (Literal.hadError())
145 return ExprResult(true);
146 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
147 Tok.getLocation());
148}
149
Steve Naroff87d58b42007-09-16 03:34:24 +0000150Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000151 // fast path for a single digit (which is quite common). A single digit
152 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
153 if (Tok.getLength() == 1) {
154 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
155
Chris Lattner3496d522007-09-04 02:45:27 +0000156 unsigned IntSize = static_cast<unsigned>(
157 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000158 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
159 Context.IntTy,
160 Tok.getLocation()));
161 }
162 llvm::SmallString<512> IntegerBuffer;
163 IntegerBuffer.resize(Tok.getLength());
164 const char *ThisTokBegin = &IntegerBuffer[0];
165
166 // Get the spelling of the token, which eliminates trigraphs, etc.
167 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
168 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
169 Tok.getLocation(), PP);
170 if (Literal.hadError)
171 return ExprResult(true);
172
Chris Lattner1de66eb2007-08-26 03:42:43 +0000173 Expr *Res;
174
175 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000176 QualType Ty;
177 const llvm::fltSemantics *Format;
178 uint64_t Size; unsigned Align;
179
180 if (Literal.isFloat) {
181 Ty = Context.FloatTy;
182 Context.Target.getFloatInfo(Size, Align, Format, Tok.getLocation());
183 } else if (Literal.isLong) {
184 Ty = Context.LongDoubleTy;
185 Context.Target.getLongDoubleInfo(Size, Align, Format, Tok.getLocation());
186 } else {
187 Ty = Context.DoubleTy;
188 Context.Target.getDoubleInfo(Size, Align, Format, Tok.getLocation());
189 }
190
191 Res = new FloatingLiteral(Literal.GetFloatValue(*Format), Ty,
192 Tok.getLocation());
Chris Lattner1de66eb2007-08-26 03:42:43 +0000193 } else if (!Literal.isIntegerLiteral()) {
194 return ExprResult(true);
195 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000196 QualType t;
197
Neil Booth7421e9c2007-08-29 22:00:19 +0000198 // long long is a C99 feature.
199 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000200 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000201 Diag(Tok.getLocation(), diag::ext_longlong);
202
Chris Lattner4b009652007-07-25 00:24:17 +0000203 // Get the value in the widest-possible width.
204 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
205
206 if (Literal.GetIntegerValue(ResultVal)) {
207 // If this value didn't fit into uintmax_t, warn and force to ull.
208 Diag(Tok.getLocation(), diag::warn_integer_too_large);
209 t = Context.UnsignedLongLongTy;
210 assert(Context.getTypeSize(t, Tok.getLocation()) ==
211 ResultVal.getBitWidth() && "long long is not intmax_t?");
212 } else {
213 // If this value fits into a ULL, try to figure out what else it fits into
214 // according to the rules of C99 6.4.4.1p5.
215
216 // Octal, Hexadecimal, and integers with a U suffix are allowed to
217 // be an unsigned int.
218 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
219
220 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000221 if (!Literal.isLong && !Literal.isLongLong) {
222 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000223 unsigned IntSize = static_cast<unsigned>(
224 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000225 // Does it fit in a unsigned int?
226 if (ResultVal.isIntN(IntSize)) {
227 // Does it fit in a signed int?
228 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
229 t = Context.IntTy;
230 else if (AllowUnsigned)
231 t = Context.UnsignedIntTy;
232 }
233
234 if (!t.isNull())
235 ResultVal.trunc(IntSize);
236 }
237
238 // Are long/unsigned long possibilities?
239 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000240 unsigned LongSize = static_cast<unsigned>(
241 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000242
243 // Does it fit in a unsigned long?
244 if (ResultVal.isIntN(LongSize)) {
245 // Does it fit in a signed long?
246 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
247 t = Context.LongTy;
248 else if (AllowUnsigned)
249 t = Context.UnsignedLongTy;
250 }
251 if (!t.isNull())
252 ResultVal.trunc(LongSize);
253 }
254
255 // Finally, check long long if needed.
256 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000257 unsigned LongLongSize = static_cast<unsigned>(
258 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000259
260 // Does it fit in a unsigned long long?
261 if (ResultVal.isIntN(LongLongSize)) {
262 // Does it fit in a signed long long?
263 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
264 t = Context.LongLongTy;
265 else if (AllowUnsigned)
266 t = Context.UnsignedLongLongTy;
267 }
268 }
269
270 // If we still couldn't decide a type, we probably have something that
271 // does not fit in a signed long long, but has no U suffix.
272 if (t.isNull()) {
273 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
274 t = Context.UnsignedLongLongTy;
275 }
276 }
277
Chris Lattner1de66eb2007-08-26 03:42:43 +0000278 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000279 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000280
281 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
282 if (Literal.isImaginary)
283 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
284
285 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000286}
287
Steve Naroff87d58b42007-09-16 03:34:24 +0000288Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000289 ExprTy *Val) {
290 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000291 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000292 return new ParenExpr(L, R, e);
293}
294
295/// The UsualUnaryConversions() function is *not* called by this routine.
296/// See C99 6.3.2.1p[2-4] for more details.
297QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
298 SourceLocation OpLoc, bool isSizeof) {
299 // C99 6.5.3.4p1:
300 if (isa<FunctionType>(exprType) && isSizeof)
301 // alignof(function) is allowed.
302 Diag(OpLoc, diag::ext_sizeof_function_type);
303 else if (exprType->isVoidType())
304 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
305 else if (exprType->isIncompleteType()) {
306 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
307 diag::err_alignof_incomplete_type,
308 exprType.getAsString());
309 return QualType(); // error
310 }
311 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
312 return Context.getSizeType();
313}
314
315Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000316ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000317 SourceLocation LPLoc, TypeTy *Ty,
318 SourceLocation RPLoc) {
319 // If error parsing type, ignore.
320 if (Ty == 0) return true;
321
322 // Verify that this is a valid expression.
323 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
324
325 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
326
327 if (resultType.isNull())
328 return true;
329 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
330}
331
Chris Lattner5110ad52007-08-24 21:41:10 +0000332QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000333 DefaultFunctionArrayConversion(V);
334
Chris Lattnera16e42d2007-08-26 05:39:26 +0000335 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000336 if (const ComplexType *CT = V->getType()->getAsComplexType())
337 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000338
339 // Otherwise they pass through real integer and floating point types here.
340 if (V->getType()->isArithmeticType())
341 return V->getType();
342
343 // Reject anything else.
344 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
345 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000346}
347
348
Chris Lattner4b009652007-07-25 00:24:17 +0000349
Steve Naroff87d58b42007-09-16 03:34:24 +0000350Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000351 tok::TokenKind Kind,
352 ExprTy *Input) {
353 UnaryOperator::Opcode Opc;
354 switch (Kind) {
355 default: assert(0 && "Unknown unary op!");
356 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
357 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
358 }
359 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
360 if (result.isNull())
361 return true;
362 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
363}
364
365Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000366ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000367 ExprTy *Idx, SourceLocation RLoc) {
368 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
369
370 // Perform default conversions.
371 DefaultFunctionArrayConversion(LHSExp);
372 DefaultFunctionArrayConversion(RHSExp);
373
374 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
375
376 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000377 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000378 // in the subscript position. As a result, we need to derive the array base
379 // and index from the expression types.
380 Expr *BaseExpr, *IndexExpr;
381 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000382 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000383 BaseExpr = LHSExp;
384 IndexExpr = RHSExp;
385 // FIXME: need to deal with const...
386 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000387 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000388 // Handle the uncommon case of "123[Ptr]".
389 BaseExpr = RHSExp;
390 IndexExpr = LHSExp;
391 // FIXME: need to deal with const...
392 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000393 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
394 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000395 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000396
397 // Component access limited to variables (reject vec4.rg[1]).
398 if (!isa<DeclRefExpr>(BaseExpr))
399 return Diag(LLoc, diag::err_ocuvector_component_access,
400 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000401 // FIXME: need to deal with const...
402 ResultType = VTy->getElementType();
403 } else {
404 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
405 RHSExp->getSourceRange());
406 }
407 // C99 6.5.2.1p1
408 if (!IndexExpr->getType()->isIntegerType())
409 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
410 IndexExpr->getSourceRange());
411
412 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
413 // the following check catches trying to index a pointer to a function (e.g.
414 // void (*)(int)). Functions are not objects in C99.
415 if (!ResultType->isObjectType())
416 return Diag(BaseExpr->getLocStart(),
417 diag::err_typecheck_subscript_not_object,
418 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
419
420 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
421}
422
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000423QualType Sema::
424CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
425 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000426 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000427
428 // The vector accessor can't exceed the number of elements.
429 const char *compStr = CompName.getName();
430 if (strlen(compStr) > vecType->getNumElements()) {
431 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
432 baseType.getAsString(), SourceRange(CompLoc));
433 return QualType();
434 }
435 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000436 if (vecType->getPointAccessorIdx(*compStr) != -1) {
437 do
438 compStr++;
439 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
440 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
441 do
442 compStr++;
443 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
444 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
445 do
446 compStr++;
447 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
448 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000449
450 if (*compStr) {
451 // We didn't get to the end of the string. This means the component names
452 // didn't come from the same set *or* we encountered an illegal name.
453 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
454 std::string(compStr,compStr+1), SourceRange(CompLoc));
455 return QualType();
456 }
457 // Each component accessor can't exceed the vector type.
458 compStr = CompName.getName();
459 while (*compStr) {
460 if (vecType->isAccessorWithinNumElements(*compStr))
461 compStr++;
462 else
463 break;
464 }
465 if (*compStr) {
466 // We didn't get to the end of the string. This means a component accessor
467 // exceeds the number of elements in the vector.
468 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
469 baseType.getAsString(), SourceRange(CompLoc));
470 return QualType();
471 }
472 // The component accessor looks fine - now we need to compute the actual type.
473 // The vector type is implied by the component accessor. For example,
474 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
475 unsigned CompSize = strlen(CompName.getName());
476 if (CompSize == 1)
477 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000478
479 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
480 // Now look up the TypeDefDecl from the vector type. Without this,
481 // diagostics look bad. We want OCU vector types to appear built-in.
482 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
483 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
484 return Context.getTypedefType(OCUVectorDecls[i]);
485 }
486 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000487}
488
Chris Lattner4b009652007-07-25 00:24:17 +0000489Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000490ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000491 tok::TokenKind OpKind, SourceLocation MemberLoc,
492 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000493 Expr *BaseExpr = static_cast<Expr *>(Base);
494 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000495
Steve Naroff2cb66382007-07-26 03:11:44 +0000496 QualType BaseType = BaseExpr->getType();
497 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000498
Chris Lattner4b009652007-07-25 00:24:17 +0000499 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000500 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000501 BaseType = PT->getPointeeType();
502 else
503 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
504 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000505 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000506 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000507 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000508 RecordDecl *RDecl = RTy->getDecl();
509 if (RTy->isIncompleteType())
510 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
511 BaseExpr->getSourceRange());
512 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000513 FieldDecl *MemberDecl = RDecl->getMember(&Member);
514 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000515 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
516 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000517 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
518 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000519 // Component access limited to variables (reject vec4.rg.g).
520 if (!isa<DeclRefExpr>(BaseExpr))
521 return Diag(OpLoc, diag::err_ocuvector_component_access,
522 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000523 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
524 if (ret.isNull())
525 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000526 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000527 } else if (BaseType->isObjcInterfaceType()) {
528 ObjcInterfaceDecl *IFace;
529 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
530 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
531 else
532 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)
533 ->getInterfaceType()->getDecl();
534 ObjcInterfaceDecl *clsDeclared;
535 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
536 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
537 OpKind==tok::arrow);
538 }
539 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
540 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000541}
542
Steve Naroff87d58b42007-09-16 03:34:24 +0000543/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000544/// This provides the location of the left/right parens and a list of comma
545/// locations.
546Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000547ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000548 ExprTy **args, unsigned NumArgsInCall,
549 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
550 Expr *Fn = static_cast<Expr *>(fn);
551 Expr **Args = reinterpret_cast<Expr**>(args);
552 assert(Fn && "no function call expression");
553
554 UsualUnaryConversions(Fn);
555 QualType funcType = Fn->getType();
556
557 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
558 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000559 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000560 if (PT == 0)
561 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
562 SourceRange(Fn->getLocStart(), RParenLoc));
563
Chris Lattner71225142007-07-31 21:27:01 +0000564 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000565 if (funcT == 0)
566 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
567 SourceRange(Fn->getLocStart(), RParenLoc));
568
569 // If a prototype isn't declared, the parser implicitly defines a func decl
570 QualType resultType = funcT->getResultType();
571
572 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
573 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
574 // assignment, to the types of the corresponding parameter, ...
575
576 unsigned NumArgsInProto = proto->getNumArgs();
577 unsigned NumArgsToCheck = NumArgsInCall;
578
579 if (NumArgsInCall < NumArgsInProto)
580 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
581 Fn->getSourceRange());
582 else if (NumArgsInCall > NumArgsInProto) {
583 if (!proto->isVariadic()) {
584 Diag(Args[NumArgsInProto]->getLocStart(),
585 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
586 SourceRange(Args[NumArgsInProto]->getLocStart(),
587 Args[NumArgsInCall-1]->getLocEnd()));
588 }
589 NumArgsToCheck = NumArgsInProto;
590 }
591 // Continue to check argument types (even if we have too few/many args).
592 for (unsigned i = 0; i < NumArgsToCheck; i++) {
593 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000594 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000595
596 QualType lhsType = proto->getArgType(i);
597 QualType rhsType = argExpr->getType();
598
Steve Naroff75644062007-07-25 20:45:33 +0000599 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000600 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000601 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000602 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000603 lhsType = Context.getPointerType(lhsType);
604
605 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
606 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000607 if (Args[i] != argExpr) // The expression was converted.
608 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000609 SourceLocation l = argExpr->getLocStart();
610
611 // decode the result (notice that AST's are still created for extensions).
612 switch (result) {
613 case Compatible:
614 break;
615 case PointerFromInt:
616 // check for null pointer constant (C99 6.3.2.3p3)
617 if (!argExpr->isNullPointerConstant(Context)) {
618 Diag(l, diag::ext_typecheck_passing_pointer_int,
619 lhsType.getAsString(), rhsType.getAsString(),
620 Fn->getSourceRange(), argExpr->getSourceRange());
621 }
622 break;
623 case IntFromPointer:
624 Diag(l, diag::ext_typecheck_passing_pointer_int,
625 lhsType.getAsString(), rhsType.getAsString(),
626 Fn->getSourceRange(), argExpr->getSourceRange());
627 break;
628 case IncompatiblePointer:
629 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
630 rhsType.getAsString(), lhsType.getAsString(),
631 Fn->getSourceRange(), argExpr->getSourceRange());
632 break;
633 case CompatiblePointerDiscardsQualifiers:
634 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
635 rhsType.getAsString(), lhsType.getAsString(),
636 Fn->getSourceRange(), argExpr->getSourceRange());
637 break;
638 case Incompatible:
639 return Diag(l, diag::err_typecheck_passing_incompatible,
640 rhsType.getAsString(), lhsType.getAsString(),
641 Fn->getSourceRange(), argExpr->getSourceRange());
642 }
643 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000644 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
645 // Promote the arguments (C99 6.5.2.2p7).
646 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
647 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000648 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000649
650 DefaultArgumentPromotion(argExpr);
651 if (Args[i] != argExpr) // The expression was converted.
652 Args[i] = argExpr; // Make sure we store the converted expression.
653 }
654 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
655 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000656 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000657 }
658 } else if (isa<FunctionTypeNoProto>(funcT)) {
659 // Promote the arguments (C99 6.5.2.2p6).
660 for (unsigned i = 0; i < NumArgsInCall; i++) {
661 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000662 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000663
664 DefaultArgumentPromotion(argExpr);
665 if (Args[i] != argExpr) // The expression was converted.
666 Args[i] = argExpr; // Make sure we store the converted expression.
667 }
Chris Lattner4b009652007-07-25 00:24:17 +0000668 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000669 // Do special checking on direct calls to functions.
670 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
671 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
672 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000673 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
674 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000675 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000676
Chris Lattner4b009652007-07-25 00:24:17 +0000677 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
678}
679
680Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000681ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000682 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000683 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000684 QualType literalType = QualType::getFromOpaquePtr(Ty);
685 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000686 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000687 Expr *literalExpr = static_cast<Expr*>(InitExpr);
688
689 // FIXME: add semantic analysis (C99 6.5.2.5).
690 return new CompoundLiteralExpr(literalType, literalExpr);
691}
692
693Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000694ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000695 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000696 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000697
Steve Naroff0acc9c92007-09-15 18:49:24 +0000698 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000699 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000700
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000701 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
702 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
703 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000704}
705
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000706bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty)
707{
708 assert(VectorTy->isVectorType() && "Not a vector type!");
709
710 if (Ty->isVectorType() || Ty->isIntegerType()) {
711 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
712 Context.getTypeSize(Ty, SourceLocation()))
713 return Diag(R.getBegin(),
714 Ty->isVectorType() ?
715 diag::err_invalid_conversion_between_vectors :
716 diag::err_invalid_conversion_between_vector_and_integer,
717 VectorTy.getAsString().c_str(),
718 Ty.getAsString().c_str(), R);
719 } else
720 return Diag(R.getBegin(),
721 diag::err_invalid_conversion_between_vector_and_scalar,
722 VectorTy.getAsString().c_str(),
723 Ty.getAsString().c_str(), R);
724
725 return false;
726}
727
Chris Lattner4b009652007-07-25 00:24:17 +0000728Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000729ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000730 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000731 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000732
733 Expr *castExpr = static_cast<Expr*>(Op);
734 QualType castType = QualType::getFromOpaquePtr(Ty);
735
Steve Naroff68adb482007-08-31 00:32:44 +0000736 UsualUnaryConversions(castExpr);
737
Chris Lattner4b009652007-07-25 00:24:17 +0000738 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
739 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000740 if (!castType->isVoidType()) { // Cast to void allows any expr type.
741 if (!castType->isScalarType())
742 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
743 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000744 if (!castExpr->getType()->isScalarType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000745 return Diag(castExpr->getLocStart(),
746 diag::err_typecheck_expect_scalar_operand,
747 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000748
749 if (castExpr->getType()->isVectorType()) {
750 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
751 castExpr->getType(), castType))
752 return true;
753 } else if (castType->isVectorType()) {
754 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
755 castType, castExpr->getType()))
756 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000757 }
Chris Lattner4b009652007-07-25 00:24:17 +0000758 }
759 return new CastExpr(castType, castExpr, LParenLoc);
760}
761
Steve Naroff144667e2007-10-18 05:13:08 +0000762// promoteExprToType - a helper function to ensure we create exactly one
763// ImplicitCastExpr.
764static void promoteExprToType(Expr *&expr, QualType type) {
765 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
766 impCast->setType(type);
767 else
768 expr = new ImplicitCastExpr(type, expr);
769 return;
770}
771
Chris Lattner98a425c2007-11-26 01:40:58 +0000772/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
773/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000774inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
775 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
776 UsualUnaryConversions(cond);
777 UsualUnaryConversions(lex);
778 UsualUnaryConversions(rex);
779 QualType condT = cond->getType();
780 QualType lexT = lex->getType();
781 QualType rexT = rex->getType();
782
783 // first, check the condition.
784 if (!condT->isScalarType()) { // C99 6.5.15p2
785 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
786 condT.getAsString());
787 return QualType();
788 }
789 // now check the two expressions.
790 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
791 UsualArithmeticConversions(lex, rex);
792 return lex->getType();
793 }
Chris Lattner71225142007-07-31 21:27:01 +0000794 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
795 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattner98a425c2007-11-26 01:40:58 +0000796 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner71225142007-07-31 21:27:01 +0000797 return lexT;
798
Chris Lattner4b009652007-07-25 00:24:17 +0000799 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
800 lexT.getAsString(), rexT.getAsString(),
801 lex->getSourceRange(), rex->getSourceRange());
802 return QualType();
803 }
804 }
805 // C99 6.5.15p3
Steve Naroff144667e2007-10-18 05:13:08 +0000806 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
807 promoteExprToType(rex, lexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000808 return lexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000809 }
810 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
811 promoteExprToType(lex, rexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000812 return rexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000813 }
Chris Lattner71225142007-07-31 21:27:01 +0000814 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
815 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
816 // get the "pointed to" types
817 QualType lhptee = LHSPT->getPointeeType();
818 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000819
Chris Lattner71225142007-07-31 21:27:01 +0000820 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
821 if (lhptee->isVoidType() &&
822 (rhptee->isObjectType() || rhptee->isIncompleteType()))
823 return lexT;
824 if (rhptee->isVoidType() &&
825 (lhptee->isObjectType() || lhptee->isIncompleteType()))
826 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000827
Steve Naroff85f0dc52007-10-15 20:41:53 +0000828 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
829 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000830 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
831 lexT.getAsString(), rexT.getAsString(),
832 lex->getSourceRange(), rex->getSourceRange());
833 return lexT; // FIXME: this is an _ext - is this return o.k?
834 }
835 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000836 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
837 // differently qualified versions of compatible types, the result type is
838 // a pointer to an appropriately qualified version of the *composite*
839 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000840 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000841 }
Chris Lattner4b009652007-07-25 00:24:17 +0000842 }
Chris Lattner71225142007-07-31 21:27:01 +0000843
Chris Lattner4b009652007-07-25 00:24:17 +0000844 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
845 return lexT;
846
847 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
848 lexT.getAsString(), rexT.getAsString(),
849 lex->getSourceRange(), rex->getSourceRange());
850 return QualType();
851}
852
Steve Naroff87d58b42007-09-16 03:34:24 +0000853/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000854/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000855Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000856 SourceLocation ColonLoc,
857 ExprTy *Cond, ExprTy *LHS,
858 ExprTy *RHS) {
859 Expr *CondExpr = (Expr *) Cond;
860 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000861
862 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
863 // was the condition.
864 bool isLHSNull = LHSExpr == 0;
865 if (isLHSNull)
866 LHSExpr = CondExpr;
867
Chris Lattner4b009652007-07-25 00:24:17 +0000868 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
869 RHSExpr, QuestionLoc);
870 if (result.isNull())
871 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000872 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
873 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000874}
875
Steve Naroffdb65e052007-08-28 23:30:39 +0000876/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
877/// do not have a prototype. Integer promotions are performed on each
878/// argument, and arguments that have type float are promoted to double.
879void Sema::DefaultArgumentPromotion(Expr *&expr) {
880 QualType t = expr->getType();
881 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
882
883 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
884 promoteExprToType(expr, Context.IntTy);
885 if (t == Context.FloatTy)
886 promoteExprToType(expr, Context.DoubleTy);
887}
888
Chris Lattner4b009652007-07-25 00:24:17 +0000889/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
890void Sema::DefaultFunctionArrayConversion(Expr *&e) {
891 QualType t = e->getType();
892 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
893
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000894 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000895 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
896 t = e->getType();
897 }
898 if (t->isFunctionType())
899 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000900 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000901 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
902}
903
904/// UsualUnaryConversion - Performs various conversions that are common to most
905/// operators (C99 6.3). The conversions of array and function types are
906/// sometimes surpressed. For example, the array->pointer conversion doesn't
907/// apply if the array is an argument to the sizeof or address (&) operators.
908/// In these instances, this routine should *not* be called.
909void Sema::UsualUnaryConversions(Expr *&expr) {
910 QualType t = expr->getType();
911 assert(!t.isNull() && "UsualUnaryConversions - missing type");
912
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000913 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000914 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
915 t = expr->getType();
916 }
917 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
918 promoteExprToType(expr, Context.IntTy);
919 else
920 DefaultFunctionArrayConversion(expr);
921}
922
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000923/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000924/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
925/// routine returns the first non-arithmetic type found. The client is
926/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000927QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
928 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000929 if (!isCompAssign) {
930 UsualUnaryConversions(lhsExpr);
931 UsualUnaryConversions(rhsExpr);
932 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000933 // For conversion purposes, we ignore any qualifiers.
934 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000935 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
936 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000937
938 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000939 if (lhs == rhs)
940 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000941
942 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
943 // The caller can deal with this (e.g. pointer + int).
944 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000945 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000946
947 // At this point, we have two different arithmetic types.
948
949 // Handle complex types first (C99 6.3.1.8p1).
950 if (lhs->isComplexType() || rhs->isComplexType()) {
951 // if we have an integer operand, the result is the complex type.
952 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000953 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
954 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000955 }
956 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000957 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
958 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000959 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000960 // This handles complex/complex, complex/float, or float/complex.
961 // When both operands are complex, the shorter operand is converted to the
962 // type of the longer, and that is the type of the result. This corresponds
963 // to what is done when combining two real floating-point operands.
964 // The fun begins when size promotion occur across type domains.
965 // From H&S 6.3.4: When one operand is complex and the other is a real
966 // floating-point type, the less precise type is converted, within it's
967 // real or complex domain, to the precision of the other type. For example,
968 // when combining a "long double" with a "double _Complex", the
969 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000970 int result = Context.compareFloatingType(lhs, rhs);
971
972 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000973 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
974 if (!isCompAssign)
975 promoteExprToType(rhsExpr, rhs);
976 } else if (result < 0) { // The right side is bigger, convert lhs.
977 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
978 if (!isCompAssign)
979 promoteExprToType(lhsExpr, lhs);
980 }
981 // At this point, lhs and rhs have the same rank/size. Now, make sure the
982 // domains match. This is a requirement for our implementation, C99
983 // does not require this promotion.
984 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
985 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000986 if (!isCompAssign)
987 promoteExprToType(lhsExpr, rhs);
988 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000989 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000990 if (!isCompAssign)
991 promoteExprToType(rhsExpr, lhs);
992 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000993 }
Chris Lattner4b009652007-07-25 00:24:17 +0000994 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000995 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000996 }
997 // Now handle "real" floating types (i.e. float, double, long double).
998 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
999 // if we have an integer operand, the result is the real floating type.
1000 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001001 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1002 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001003 }
1004 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001005 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1006 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001007 }
1008 // We have two real floating types, float/complex combos were handled above.
1009 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001010 int result = Context.compareFloatingType(lhs, rhs);
1011
1012 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001013 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1014 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001015 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001016 if (result < 0) { // convert the lhs
1017 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1018 return rhs;
1019 }
1020 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001021 }
1022 // Finally, we have two differing integer types.
1023 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001024 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1025 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001026 }
Steve Naroff8f708362007-08-24 19:07:16 +00001027 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1028 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001029}
1030
1031// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1032// being closely modeled after the C99 spec:-). The odd characteristic of this
1033// routine is it effectively iqnores the qualifiers on the top level pointee.
1034// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1035// FIXME: add a couple examples in this comment.
1036Sema::AssignmentCheckResult
1037Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1038 QualType lhptee, rhptee;
1039
1040 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001041 lhptee = lhsType->getAsPointerType()->getPointeeType();
1042 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001043
1044 // make sure we operate on the canonical type
1045 lhptee = lhptee.getCanonicalType();
1046 rhptee = rhptee.getCanonicalType();
1047
1048 AssignmentCheckResult r = Compatible;
1049
1050 // C99 6.5.16.1p1: This following citation is common to constraints
1051 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1052 // qualifiers of the type *pointed to* by the right;
1053 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1054 rhptee.getQualifiers())
1055 r = CompatiblePointerDiscardsQualifiers;
1056
1057 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1058 // incomplete type and the other is a pointer to a qualified or unqualified
1059 // version of void...
1060 if (lhptee.getUnqualifiedType()->isVoidType() &&
1061 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1062 ;
1063 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1064 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1065 ;
1066 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1067 // unqualified versions of compatible types, ...
Steve Naroff85f0dc52007-10-15 20:41:53 +00001068 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1069 rhptee.getUnqualifiedType()))
Chris Lattner4b009652007-07-25 00:24:17 +00001070 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1071 return r;
1072}
1073
1074/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1075/// has code to accommodate several GCC extensions when type checking
1076/// pointers. Here are some objectionable examples that GCC considers warnings:
1077///
1078/// int a, *pint;
1079/// short *pshort;
1080/// struct foo *pfoo;
1081///
1082/// pint = pshort; // warning: assignment from incompatible pointer type
1083/// a = pint; // warning: assignment makes integer from pointer without a cast
1084/// pint = a; // warning: assignment makes pointer from integer without a cast
1085/// pint = pfoo; // warning: assignment from incompatible pointer type
1086///
1087/// As a result, the code for dealing with pointers is more complex than the
1088/// C99 spec dictates.
1089/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1090///
1091Sema::AssignmentCheckResult
1092Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroffeed76842007-11-13 00:31:42 +00001093 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1094 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattnera703c2e2007-10-29 05:15:40 +00001095 return Compatible; // common case, fast path...
Chris Lattner4b009652007-07-25 00:24:17 +00001096
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001097 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001098 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001099 return Compatible;
1100 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001101 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1102 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1103 return Incompatible;
1104 }
1105 return Compatible;
1106 } else if (lhsType->isPointerType()) {
1107 if (rhsType->isIntegerType())
1108 return PointerFromInt;
1109
1110 if (rhsType->isPointerType())
1111 return CheckPointerTypesForAssignment(lhsType, rhsType);
1112 } else if (rhsType->isPointerType()) {
1113 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1114 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1115 return IntFromPointer;
1116
1117 if (lhsType->isPointerType())
1118 return CheckPointerTypesForAssignment(lhsType, rhsType);
1119 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001120 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001121 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001122 }
1123 return Incompatible;
1124}
1125
1126Sema::AssignmentCheckResult
1127Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Chris Lattner5f505bf2007-10-16 02:55:40 +00001128 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001129 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001130 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001131 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001132 //
1133 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1134 // are better understood.
1135 if (!lhsType->isReferenceType())
1136 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001137
1138 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001139
Steve Naroff0f32f432007-08-24 22:33:52 +00001140 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1141
1142 // C99 6.5.16.1p2: The value of the right operand is converted to the
1143 // type of the assignment expression.
1144 if (rExpr->getType() != lhsType)
1145 promoteExprToType(rExpr, lhsType);
1146 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001147}
1148
1149Sema::AssignmentCheckResult
1150Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1151 return CheckAssignmentConstraints(lhsType, rhsType);
1152}
1153
1154inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1155 Diag(loc, diag::err_typecheck_invalid_operands,
1156 lex->getType().getAsString(), rex->getType().getAsString(),
1157 lex->getSourceRange(), rex->getSourceRange());
1158}
1159
1160inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1161 Expr *&rex) {
1162 QualType lhsType = lex->getType(), rhsType = rex->getType();
1163
1164 // make sure the vector types are identical.
1165 if (lhsType == rhsType)
1166 return lhsType;
1167 // You cannot convert between vector values of different size.
1168 Diag(loc, diag::err_typecheck_vector_not_convertable,
1169 lex->getType().getAsString(), rex->getType().getAsString(),
1170 lex->getSourceRange(), rex->getSourceRange());
1171 return QualType();
1172}
1173
1174inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001175 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001176{
1177 QualType lhsType = lex->getType(), rhsType = rex->getType();
1178
1179 if (lhsType->isVectorType() || rhsType->isVectorType())
1180 return CheckVectorOperands(loc, lex, rex);
1181
Steve Naroff8f708362007-08-24 19:07:16 +00001182 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001183
Chris Lattner4b009652007-07-25 00:24:17 +00001184 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001185 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001186 InvalidOperands(loc, lex, rex);
1187 return QualType();
1188}
1189
1190inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001191 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001192{
1193 QualType lhsType = lex->getType(), rhsType = rex->getType();
1194
Steve Naroff8f708362007-08-24 19:07:16 +00001195 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001196
Chris Lattner4b009652007-07-25 00:24:17 +00001197 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001198 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001199 InvalidOperands(loc, lex, rex);
1200 return QualType();
1201}
1202
1203inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001204 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001205{
1206 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1207 return CheckVectorOperands(loc, lex, rex);
1208
Steve Naroff8f708362007-08-24 19:07:16 +00001209 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001210
1211 // handle the common case first (both operands are arithmetic).
1212 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001213 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001214
1215 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1216 return lex->getType();
1217 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1218 return rex->getType();
1219 InvalidOperands(loc, lex, rex);
1220 return QualType();
1221}
1222
1223inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001224 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001225{
1226 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1227 return CheckVectorOperands(loc, lex, rex);
1228
Steve Naroff8f708362007-08-24 19:07:16 +00001229 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001230
1231 // handle the common case first (both operands are arithmetic).
1232 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001233 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001234
1235 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001236 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001237 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1238 return Context.getPointerDiffType();
1239 InvalidOperands(loc, lex, rex);
1240 return QualType();
1241}
1242
1243inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001244 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001245{
1246 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1247 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001248 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001249
1250 // handle the common case first (both operands are arithmetic).
1251 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001252 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001253 InvalidOperands(loc, lex, rex);
1254 return QualType();
1255}
1256
Chris Lattner254f3bc2007-08-26 01:18:55 +00001257inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1258 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001259{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001260 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001261 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1262 UsualArithmeticConversions(lex, rex);
1263 else {
1264 UsualUnaryConversions(lex);
1265 UsualUnaryConversions(rex);
1266 }
Chris Lattner4b009652007-07-25 00:24:17 +00001267 QualType lType = lex->getType();
1268 QualType rType = rex->getType();
1269
Ted Kremenek486509e2007-10-29 17:13:39 +00001270 // For non-floating point types, check for self-comparisons of the form
1271 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1272 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001273 if (!lType->isFloatingType()) {
1274 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1275 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1276 if (DRL->getDecl() == DRR->getDecl())
1277 Diag(loc, diag::warn_selfcomparison);
1278 }
1279
Chris Lattner254f3bc2007-08-26 01:18:55 +00001280 if (isRelational) {
1281 if (lType->isRealType() && rType->isRealType())
1282 return Context.IntTy;
1283 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001284 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001285 if (lType->isFloatingType()) {
1286 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001287 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001288 }
1289
Chris Lattner254f3bc2007-08-26 01:18:55 +00001290 if (lType->isArithmeticType() && rType->isArithmeticType())
1291 return Context.IntTy;
1292 }
Chris Lattner4b009652007-07-25 00:24:17 +00001293
Chris Lattner22be8422007-08-26 01:10:14 +00001294 bool LHSIsNull = lex->isNullPointerConstant(Context);
1295 bool RHSIsNull = rex->isNullPointerConstant(Context);
1296
Chris Lattner254f3bc2007-08-26 01:18:55 +00001297 // All of the following pointer related warnings are GCC extensions, except
1298 // when handling null pointer constants. One day, we can consider making them
1299 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001300 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001301
1302 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1303 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1304 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001305 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1306 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001307 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1308 lType.getAsString(), rType.getAsString(),
1309 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001310 }
Chris Lattner22be8422007-08-26 01:10:14 +00001311 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001312 return Context.IntTy;
1313 }
1314 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001315 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001316 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1317 lType.getAsString(), rType.getAsString(),
1318 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001319 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001320 return Context.IntTy;
1321 }
1322 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001323 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001324 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1325 lType.getAsString(), rType.getAsString(),
1326 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001327 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001328 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001329 }
1330 InvalidOperands(loc, lex, rex);
1331 return QualType();
1332}
1333
Chris Lattner4b009652007-07-25 00:24:17 +00001334inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001335 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001336{
1337 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1338 return CheckVectorOperands(loc, lex, rex);
1339
Steve Naroff8f708362007-08-24 19:07:16 +00001340 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001341
1342 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001343 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001344 InvalidOperands(loc, lex, rex);
1345 return QualType();
1346}
1347
1348inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1349 Expr *&lex, Expr *&rex, SourceLocation loc)
1350{
1351 UsualUnaryConversions(lex);
1352 UsualUnaryConversions(rex);
1353
1354 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1355 return Context.IntTy;
1356 InvalidOperands(loc, lex, rex);
1357 return QualType();
1358}
1359
1360inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001361 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001362{
1363 QualType lhsType = lex->getType();
1364 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1365 bool hadError = false;
1366 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1367
1368 switch (mlval) { // C99 6.5.16p2
1369 case Expr::MLV_Valid:
1370 break;
1371 case Expr::MLV_ConstQualified:
1372 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1373 hadError = true;
1374 break;
1375 case Expr::MLV_ArrayType:
1376 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1377 lhsType.getAsString(), lex->getSourceRange());
1378 return QualType();
1379 case Expr::MLV_NotObjectType:
1380 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1381 lhsType.getAsString(), lex->getSourceRange());
1382 return QualType();
1383 case Expr::MLV_InvalidExpression:
1384 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1385 lex->getSourceRange());
1386 return QualType();
1387 case Expr::MLV_IncompleteType:
1388 case Expr::MLV_IncompleteVoidType:
1389 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1390 lhsType.getAsString(), lex->getSourceRange());
1391 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001392 case Expr::MLV_DuplicateVectorComponents:
1393 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1394 lex->getSourceRange());
1395 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001396 }
1397 AssignmentCheckResult result;
1398
1399 if (compoundType.isNull())
1400 result = CheckSingleAssignmentConstraints(lhsType, rex);
1401 else
1402 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001403
Chris Lattner4b009652007-07-25 00:24:17 +00001404 // decode the result (notice that extensions still return a type).
1405 switch (result) {
1406 case Compatible:
1407 break;
1408 case Incompatible:
1409 Diag(loc, diag::err_typecheck_assign_incompatible,
1410 lhsType.getAsString(), rhsType.getAsString(),
1411 lex->getSourceRange(), rex->getSourceRange());
1412 hadError = true;
1413 break;
1414 case PointerFromInt:
1415 // check for null pointer constant (C99 6.3.2.3p3)
1416 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1417 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1418 lhsType.getAsString(), rhsType.getAsString(),
1419 lex->getSourceRange(), rex->getSourceRange());
1420 }
1421 break;
1422 case IntFromPointer:
1423 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1424 lhsType.getAsString(), rhsType.getAsString(),
1425 lex->getSourceRange(), rex->getSourceRange());
1426 break;
1427 case IncompatiblePointer:
1428 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1429 lhsType.getAsString(), rhsType.getAsString(),
1430 lex->getSourceRange(), rex->getSourceRange());
1431 break;
1432 case CompatiblePointerDiscardsQualifiers:
1433 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1434 lhsType.getAsString(), rhsType.getAsString(),
1435 lex->getSourceRange(), rex->getSourceRange());
1436 break;
1437 }
1438 // C99 6.5.16p3: The type of an assignment expression is the type of the
1439 // left operand unless the left operand has qualified type, in which case
1440 // it is the unqualified version of the type of the left operand.
1441 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1442 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001443 // C++ 5.17p1: the type of the assignment expression is that of its left
1444 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001445 return hadError ? QualType() : lhsType.getUnqualifiedType();
1446}
1447
1448inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1449 Expr *&lex, Expr *&rex, SourceLocation loc) {
1450 UsualUnaryConversions(rex);
1451 return rex->getType();
1452}
1453
1454/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1455/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1456QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1457 QualType resType = op->getType();
1458 assert(!resType.isNull() && "no type for increment/decrement expression");
1459
Steve Naroffd30e1932007-08-24 17:20:07 +00001460 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001461 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001462 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1463 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1464 resType.getAsString(), op->getSourceRange());
1465 return QualType();
1466 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001467 } else if (!resType->isRealType()) {
1468 if (resType->isComplexType())
1469 // C99 does not support ++/-- on complex types.
1470 Diag(OpLoc, diag::ext_integer_increment_complex,
1471 resType.getAsString(), op->getSourceRange());
1472 else {
1473 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1474 resType.getAsString(), op->getSourceRange());
1475 return QualType();
1476 }
Chris Lattner4b009652007-07-25 00:24:17 +00001477 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001478 // At this point, we know we have a real, complex or pointer type.
1479 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001480 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1481 if (mlval != Expr::MLV_Valid) {
1482 // FIXME: emit a more precise diagnostic...
1483 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1484 op->getSourceRange());
1485 return QualType();
1486 }
1487 return resType;
1488}
1489
1490/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1491/// This routine allows us to typecheck complex/recursive expressions
1492/// where the declaration is needed for type checking. Here are some
1493/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1494static Decl *getPrimaryDeclaration(Expr *e) {
1495 switch (e->getStmtClass()) {
1496 case Stmt::DeclRefExprClass:
1497 return cast<DeclRefExpr>(e)->getDecl();
1498 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001499 // Fields cannot be declared with a 'register' storage class.
1500 // &X->f is always ok, even if X is declared register.
1501 if (cast<MemberExpr>(e)->isArrow())
1502 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001503 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1504 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001505 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001506 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001507 case Stmt::UnaryOperatorClass:
1508 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1509 case Stmt::ParenExprClass:
1510 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001511 case Stmt::ImplicitCastExprClass:
1512 // &X[4] when X is an array, has an implicit cast from array to pointer.
1513 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001514 default:
1515 return 0;
1516 }
1517}
1518
1519/// CheckAddressOfOperand - The operand of & must be either a function
1520/// designator or an lvalue designating an object. If it is an lvalue, the
1521/// object cannot be declared with storage class register or be a bit field.
1522/// Note: The usual conversions are *not* applied to the operand of the &
1523/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1524QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1525 Decl *dcl = getPrimaryDeclaration(op);
1526 Expr::isLvalueResult lval = op->isLvalue();
1527
1528 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001529 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1530 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001531 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1532 op->getSourceRange());
1533 return QualType();
1534 }
1535 } else if (dcl) {
1536 // We have an lvalue with a decl. Make sure the decl is not declared
1537 // with the register storage-class specifier.
1538 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1539 if (vd->getStorageClass() == VarDecl::Register) {
1540 Diag(OpLoc, diag::err_typecheck_address_of_register,
1541 op->getSourceRange());
1542 return QualType();
1543 }
1544 } else
1545 assert(0 && "Unknown/unexpected decl type");
1546
1547 // FIXME: add check for bitfields!
1548 }
1549 // If the operand has type "type", the result has type "pointer to type".
1550 return Context.getPointerType(op->getType());
1551}
1552
1553QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1554 UsualUnaryConversions(op);
1555 QualType qType = op->getType();
1556
Chris Lattner7931f4a2007-07-31 16:53:04 +00001557 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001558 QualType ptype = PT->getPointeeType();
1559 // C99 6.5.3.2p4. "if it points to an object,...".
1560 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1561 // GCC compat: special case 'void *' (treat as warning).
1562 if (ptype->isVoidType()) {
1563 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1564 qType.getAsString(), op->getSourceRange());
1565 } else {
1566 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1567 ptype.getAsString(), op->getSourceRange());
1568 return QualType();
1569 }
1570 }
1571 return ptype;
1572 }
1573 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1574 qType.getAsString(), op->getSourceRange());
1575 return QualType();
1576}
1577
1578static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1579 tok::TokenKind Kind) {
1580 BinaryOperator::Opcode Opc;
1581 switch (Kind) {
1582 default: assert(0 && "Unknown binop!");
1583 case tok::star: Opc = BinaryOperator::Mul; break;
1584 case tok::slash: Opc = BinaryOperator::Div; break;
1585 case tok::percent: Opc = BinaryOperator::Rem; break;
1586 case tok::plus: Opc = BinaryOperator::Add; break;
1587 case tok::minus: Opc = BinaryOperator::Sub; break;
1588 case tok::lessless: Opc = BinaryOperator::Shl; break;
1589 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1590 case tok::lessequal: Opc = BinaryOperator::LE; break;
1591 case tok::less: Opc = BinaryOperator::LT; break;
1592 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1593 case tok::greater: Opc = BinaryOperator::GT; break;
1594 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1595 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1596 case tok::amp: Opc = BinaryOperator::And; break;
1597 case tok::caret: Opc = BinaryOperator::Xor; break;
1598 case tok::pipe: Opc = BinaryOperator::Or; break;
1599 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1600 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1601 case tok::equal: Opc = BinaryOperator::Assign; break;
1602 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1603 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1604 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1605 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1606 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1607 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1608 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1609 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1610 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1611 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1612 case tok::comma: Opc = BinaryOperator::Comma; break;
1613 }
1614 return Opc;
1615}
1616
1617static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1618 tok::TokenKind Kind) {
1619 UnaryOperator::Opcode Opc;
1620 switch (Kind) {
1621 default: assert(0 && "Unknown unary op!");
1622 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1623 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1624 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1625 case tok::star: Opc = UnaryOperator::Deref; break;
1626 case tok::plus: Opc = UnaryOperator::Plus; break;
1627 case tok::minus: Opc = UnaryOperator::Minus; break;
1628 case tok::tilde: Opc = UnaryOperator::Not; break;
1629 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1630 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1631 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1632 case tok::kw___real: Opc = UnaryOperator::Real; break;
1633 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1634 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1635 }
1636 return Opc;
1637}
1638
1639// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001640Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001641 ExprTy *LHS, ExprTy *RHS) {
1642 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1643 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1644
Steve Naroff87d58b42007-09-16 03:34:24 +00001645 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1646 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001647
1648 QualType ResultTy; // Result type of the binary operator.
1649 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1650
1651 switch (Opc) {
1652 default:
1653 assert(0 && "Unknown binary expr!");
1654 case BinaryOperator::Assign:
1655 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1656 break;
1657 case BinaryOperator::Mul:
1658 case BinaryOperator::Div:
1659 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1660 break;
1661 case BinaryOperator::Rem:
1662 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1663 break;
1664 case BinaryOperator::Add:
1665 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1666 break;
1667 case BinaryOperator::Sub:
1668 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1669 break;
1670 case BinaryOperator::Shl:
1671 case BinaryOperator::Shr:
1672 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1673 break;
1674 case BinaryOperator::LE:
1675 case BinaryOperator::LT:
1676 case BinaryOperator::GE:
1677 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001678 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001679 break;
1680 case BinaryOperator::EQ:
1681 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001682 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001683 break;
1684 case BinaryOperator::And:
1685 case BinaryOperator::Xor:
1686 case BinaryOperator::Or:
1687 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1688 break;
1689 case BinaryOperator::LAnd:
1690 case BinaryOperator::LOr:
1691 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1692 break;
1693 case BinaryOperator::MulAssign:
1694 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001695 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001696 if (!CompTy.isNull())
1697 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1698 break;
1699 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001700 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001701 if (!CompTy.isNull())
1702 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1703 break;
1704 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001705 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001706 if (!CompTy.isNull())
1707 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1708 break;
1709 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001710 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001711 if (!CompTy.isNull())
1712 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1713 break;
1714 case BinaryOperator::ShlAssign:
1715 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001716 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001717 if (!CompTy.isNull())
1718 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1719 break;
1720 case BinaryOperator::AndAssign:
1721 case BinaryOperator::XorAssign:
1722 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001723 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001724 if (!CompTy.isNull())
1725 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1726 break;
1727 case BinaryOperator::Comma:
1728 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1729 break;
1730 }
1731 if (ResultTy.isNull())
1732 return true;
1733 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001734 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001735 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001736 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001737}
1738
1739// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001740Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001741 ExprTy *input) {
1742 Expr *Input = (Expr*)input;
1743 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1744 QualType resultType;
1745 switch (Opc) {
1746 default:
1747 assert(0 && "Unimplemented unary expr!");
1748 case UnaryOperator::PreInc:
1749 case UnaryOperator::PreDec:
1750 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1751 break;
1752 case UnaryOperator::AddrOf:
1753 resultType = CheckAddressOfOperand(Input, OpLoc);
1754 break;
1755 case UnaryOperator::Deref:
1756 resultType = CheckIndirectionOperand(Input, OpLoc);
1757 break;
1758 case UnaryOperator::Plus:
1759 case UnaryOperator::Minus:
1760 UsualUnaryConversions(Input);
1761 resultType = Input->getType();
1762 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1763 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1764 resultType.getAsString());
1765 break;
1766 case UnaryOperator::Not: // bitwise complement
1767 UsualUnaryConversions(Input);
1768 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001769 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1770 if (!resultType->isIntegerType()) {
1771 if (resultType->isComplexType())
1772 // C99 does not support '~' for complex conjugation.
1773 Diag(OpLoc, diag::ext_integer_complement_complex,
1774 resultType.getAsString());
1775 else
1776 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1777 resultType.getAsString());
1778 }
Chris Lattner4b009652007-07-25 00:24:17 +00001779 break;
1780 case UnaryOperator::LNot: // logical negation
1781 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1782 DefaultFunctionArrayConversion(Input);
1783 resultType = Input->getType();
1784 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1785 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1786 resultType.getAsString());
1787 // LNot always has type int. C99 6.5.3.3p5.
1788 resultType = Context.IntTy;
1789 break;
1790 case UnaryOperator::SizeOf:
1791 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1792 break;
1793 case UnaryOperator::AlignOf:
1794 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1795 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001796 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001797 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001798 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001799 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001800 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001801 resultType = Input->getType();
1802 break;
1803 }
1804 if (resultType.isNull())
1805 return true;
1806 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1807}
1808
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001809/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1810Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001811 SourceLocation LabLoc,
1812 IdentifierInfo *LabelII) {
1813 // Look up the record for this label identifier.
1814 LabelStmt *&LabelDecl = LabelMap[LabelII];
1815
1816 // If we haven't seen this label yet, create a forward reference.
1817 if (LabelDecl == 0)
1818 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1819
1820 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001821 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1822 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001823}
1824
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001825Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001826 SourceLocation RPLoc) { // "({..})"
1827 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1828 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1829 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1830
1831 // FIXME: there are a variety of strange constraints to enforce here, for
1832 // example, it is not possible to goto into a stmt expression apparently.
1833 // More semantic analysis is needed.
1834
1835 // FIXME: the last statement in the compount stmt has its value used. We
1836 // should not warn about it being unused.
1837
1838 // If there are sub stmts in the compound stmt, take the type of the last one
1839 // as the type of the stmtexpr.
1840 QualType Ty = Context.VoidTy;
1841
1842 if (!Compound->body_empty())
1843 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1844 Ty = LastExpr->getType();
1845
1846 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1847}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001848
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001849Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001850 SourceLocation TypeLoc,
1851 TypeTy *argty,
1852 OffsetOfComponent *CompPtr,
1853 unsigned NumComponents,
1854 SourceLocation RPLoc) {
1855 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1856 assert(!ArgTy.isNull() && "Missing type argument!");
1857
1858 // We must have at least one component that refers to the type, and the first
1859 // one is known to be a field designator. Verify that the ArgTy represents
1860 // a struct/union/class.
1861 if (!ArgTy->isRecordType())
1862 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1863
1864 // Otherwise, create a compound literal expression as the base, and
1865 // iteratively process the offsetof designators.
1866 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1867
Chris Lattnerb37522e2007-08-31 21:49:13 +00001868 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1869 // GCC extension, diagnose them.
1870 if (NumComponents != 1)
1871 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1872 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1873
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001874 for (unsigned i = 0; i != NumComponents; ++i) {
1875 const OffsetOfComponent &OC = CompPtr[i];
1876 if (OC.isBrackets) {
1877 // Offset of an array sub-field. TODO: Should we allow vector elements?
1878 const ArrayType *AT = Res->getType()->getAsArrayType();
1879 if (!AT) {
1880 delete Res;
1881 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1882 Res->getType().getAsString());
1883 }
1884
Chris Lattner2af6a802007-08-30 17:59:59 +00001885 // FIXME: C++: Verify that operator[] isn't overloaded.
1886
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001887 // C99 6.5.2.1p1
1888 Expr *Idx = static_cast<Expr*>(OC.U.E);
1889 if (!Idx->getType()->isIntegerType())
1890 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1891 Idx->getSourceRange());
1892
1893 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1894 continue;
1895 }
1896
1897 const RecordType *RC = Res->getType()->getAsRecordType();
1898 if (!RC) {
1899 delete Res;
1900 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1901 Res->getType().getAsString());
1902 }
1903
1904 // Get the decl corresponding to this.
1905 RecordDecl *RD = RC->getDecl();
1906 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1907 if (!MemberDecl)
1908 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1909 OC.U.IdentInfo->getName(),
1910 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001911
1912 // FIXME: C++: Verify that MemberDecl isn't a static field.
1913 // FIXME: Verify that MemberDecl isn't a bitfield.
1914
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001915 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1916 }
1917
1918 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1919 BuiltinLoc);
1920}
1921
1922
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001923Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001924 TypeTy *arg1, TypeTy *arg2,
1925 SourceLocation RPLoc) {
1926 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1927 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1928
1929 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1930
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001931 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001932}
1933
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001934Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00001935 ExprTy *expr1, ExprTy *expr2,
1936 SourceLocation RPLoc) {
1937 Expr *CondExpr = static_cast<Expr*>(cond);
1938 Expr *LHSExpr = static_cast<Expr*>(expr1);
1939 Expr *RHSExpr = static_cast<Expr*>(expr2);
1940
1941 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1942
1943 // The conditional expression is required to be a constant expression.
1944 llvm::APSInt condEval(32);
1945 SourceLocation ExpLoc;
1946 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1947 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1948 CondExpr->getSourceRange());
1949
1950 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1951 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1952 RHSExpr->getType();
1953 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1954}
1955
Anders Carlsson36760332007-10-15 20:28:48 +00001956Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
1957 ExprTy *expr, TypeTy *type,
1958 SourceLocation RPLoc)
1959{
1960 Expr *E = static_cast<Expr*>(expr);
1961 QualType T = QualType::getFromOpaquePtr(type);
1962
1963 InitBuiltinVaListType();
1964
1965 Sema::AssignmentCheckResult result;
1966
1967 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
1968 E->getType());
1969 if (result != Compatible)
1970 return Diag(E->getLocStart(),
1971 diag::err_first_argument_to_va_arg_not_of_type_va_list,
1972 E->getType().getAsString(),
1973 E->getSourceRange());
1974
1975 // FIXME: Warn if a non-POD type is passed in.
1976
1977 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
1978}
1979
Anders Carlssona66cad42007-08-21 17:43:55 +00001980// TODO: Move this to SemaObjC.cpp
Steve Naroff0add5d22007-11-03 11:27:19 +00001981Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation AtLoc,
1982 ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001983 StringLiteral* S = static_cast<StringLiteral *>(string);
1984
1985 if (CheckBuiltinCFStringArgument(S))
1986 return true;
1987
Steve Narofff2e30312007-10-15 23:35:17 +00001988 if (Context.getObjcConstantStringInterface().isNull()) {
1989 // Initialize the constant string interface lazily. This assumes
1990 // the NSConstantString interface is seen in this translation unit.
1991 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
1992 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
1993 SourceLocation(), TUScope);
Steve Naroff134c3502007-10-16 00:00:18 +00001994 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff96f136d2007-10-18 23:53:51 +00001995 if (!strIFace)
1996 return Diag(S->getLocStart(), diag::err_undef_interface,
1997 NSIdent->getName());
Steve Naroff134c3502007-10-16 00:00:18 +00001998 Context.setObjcConstantStringInterface(strIFace);
Steve Narofff2e30312007-10-15 23:35:17 +00001999 }
2000 QualType t = Context.getObjcConstantStringInterface();
Anders Carlssona66cad42007-08-21 17:43:55 +00002001 t = Context.getPointerType(t);
Steve Naroff0add5d22007-11-03 11:27:19 +00002002 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlssona66cad42007-08-21 17:43:55 +00002003}
Anders Carlsson8be1d402007-08-22 15:14:15 +00002004
2005Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattnercfd61c82007-10-16 22:51:17 +00002006 SourceLocation EncodeLoc,
Anders Carlsson8be1d402007-08-22 15:14:15 +00002007 SourceLocation LParenLoc,
2008 TypeTy *Ty,
2009 SourceLocation RParenLoc) {
2010 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2011
2012 QualType t = Context.getPointerType(Context.CharTy);
2013 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2014}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002015
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002016Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2017 SourceLocation AtLoc,
Fariborz Jahanian957448a2007-10-16 23:21:02 +00002018 SourceLocation SelLoc,
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002019 SourceLocation LParenLoc,
2020 SourceLocation RParenLoc) {
Steve Naroffae84af82007-10-31 18:42:27 +00002021 QualType t = Context.getObjcSelType();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002022 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2023}
2024
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002025Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2026 SourceLocation AtLoc,
2027 SourceLocation ProtoLoc,
2028 SourceLocation LParenLoc,
2029 SourceLocation RParenLoc) {
2030 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2031 if (!PDecl) {
2032 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2033 return true;
2034 }
2035
2036 QualType t = GetObjcProtoType(AtLoc);
Fariborz Jahanian20b40e42007-10-18 22:59:23 +00002037 if (t.isNull())
2038 return true;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002039 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2040}
Steve Naroff52664182007-10-16 23:12:48 +00002041
2042bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2043 ObjcMethodDecl *Method) {
2044 bool anyIncompatibleArgs = false;
2045
2046 for (unsigned i = 0; i < NumArgs; i++) {
2047 Expr *argExpr = Args[i];
2048 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2049
2050 QualType lhsType = Method->getParamDecl(i)->getType();
2051 QualType rhsType = argExpr->getType();
2052
2053 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2054 if (const ArrayType *ary = lhsType->getAsArrayType())
2055 lhsType = Context.getPointerType(ary->getElementType());
2056 else if (lhsType->isFunctionType())
2057 lhsType = Context.getPointerType(lhsType);
2058
2059 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2060 argExpr);
2061 if (Args[i] != argExpr) // The expression was converted.
2062 Args[i] = argExpr; // Make sure we store the converted expression.
2063 SourceLocation l = argExpr->getLocStart();
2064
2065 // decode the result (notice that AST's are still created for extensions).
2066 switch (result) {
2067 case Compatible:
2068 break;
2069 case PointerFromInt:
2070 // check for null pointer constant (C99 6.3.2.3p3)
2071 if (!argExpr->isNullPointerConstant(Context)) {
2072 Diag(l, diag::ext_typecheck_sending_pointer_int,
2073 lhsType.getAsString(), rhsType.getAsString(),
2074 argExpr->getSourceRange());
2075 }
2076 break;
2077 case IntFromPointer:
2078 Diag(l, diag::ext_typecheck_sending_pointer_int,
2079 lhsType.getAsString(), rhsType.getAsString(),
2080 argExpr->getSourceRange());
2081 break;
2082 case IncompatiblePointer:
2083 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2084 rhsType.getAsString(), lhsType.getAsString(),
2085 argExpr->getSourceRange());
2086 break;
2087 case CompatiblePointerDiscardsQualifiers:
2088 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2089 rhsType.getAsString(), lhsType.getAsString(),
2090 argExpr->getSourceRange());
2091 break;
2092 case Incompatible:
2093 Diag(l, diag::err_typecheck_sending_incompatible,
2094 rhsType.getAsString(), lhsType.getAsString(),
2095 argExpr->getSourceRange());
2096 anyIncompatibleArgs = true;
2097 }
2098 }
2099 return anyIncompatibleArgs;
2100}
2101
Steve Naroff4ed9d662007-09-27 14:38:14 +00002102// ActOnClassMessage - used for both unary and keyword messages.
2103// ArgExprs is optional - if it is present, the number of expressions
2104// is obtained from Sel.getNumArgs().
2105Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002106 Scope *S,
Steve Narofffa465d12007-10-02 20:01:56 +00002107 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002108 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002109{
Steve Narofffa465d12007-10-02 20:01:56 +00002110 assert(receiverName && "missing receiver class name");
Steve Naroffc39ca262007-09-18 23:55:05 +00002111
Steve Naroff52664182007-10-16 23:12:48 +00002112 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002113 ObjcInterfaceDecl* ClassDecl = 0;
2114 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2115 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahanian342f3602007-11-12 20:20:37 +00002116 if (ClassDecl && CurMethodDecl->isInstance()) {
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002117 IdentifierInfo &II = Context.Idents.get("self");
2118 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II,
2119 false);
2120 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2121 superTy = Context.getPointerType(superTy);
2122 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2123 SourceLocation(), ReceiverExpr.Val);
2124
2125 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002126 Args, NumArgs);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002127 }
2128 // class method
2129 if (ClassDecl)
2130 receiverName = ClassDecl->getIdentifier();
2131 }
2132 else
2133 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Narofffa465d12007-10-02 20:01:56 +00002134 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002135 QualType returnType;
Steve Naroff75c4baf2007-11-05 15:27:52 +00002136
2137 // Before we give up, check if the selector is an instance method.
2138 if (!Method)
2139 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002140 if (!Method) {
2141 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2142 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002143 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002144 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002145 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002146 if (Sel.getNumArgs()) {
2147 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2148 return true;
2149 }
Steve Naroff7e461452007-10-16 20:39:36 +00002150 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002151 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff9f176d12007-11-15 13:05:42 +00002152 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002153}
2154
Steve Naroff4ed9d662007-09-27 14:38:14 +00002155// ActOnInstanceMessage - used for both unary and keyword messages.
2156// ArgExprs is optional - if it is present, the number of expressions
2157// is obtained from Sel.getNumArgs().
2158Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroff6cb1d362007-09-28 22:22:11 +00002159 ExprTy *receiver, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002160 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff4ed9d662007-09-27 14:38:14 +00002161{
Steve Naroffc39ca262007-09-18 23:55:05 +00002162 assert(receiver && "missing receiver expression");
2163
Steve Naroff52664182007-10-16 23:12:48 +00002164 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroffc39ca262007-09-18 23:55:05 +00002165 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Narofffa465d12007-10-02 20:01:56 +00002166 QualType receiverType = RExpr->getType();
Steve Naroffee1de132007-10-10 21:53:07 +00002167 QualType returnType;
Steve Naroff1e1c3912007-11-03 16:37:59 +00002168 ObjcMethodDecl *Method;
Steve Naroffee1de132007-10-10 21:53:07 +00002169
Steve Naroff0091d142007-11-11 17:52:25 +00002170 if (receiverType == Context.getObjcIdType() ||
2171 receiverType == Context.getObjcClassType()) {
Steve Naroff1e1c3912007-11-03 16:37:59 +00002172 Method = InstanceMethodPool[Sel].Method;
Steve Naroffd0cfcd02007-11-13 04:10:18 +00002173 // If we didn't find an public method, look for a private one.
2174 if (!Method && CurMethodDecl) {
2175 NamedDecl *impCxt = CurMethodDecl->getMethodContext();
2176 if (ObjcImplementationDecl *IMD =
2177 dyn_cast<ObjcImplementationDecl>(impCxt)) {
2178 if (receiverType == Context.getObjcIdType())
2179 Method = IMD->lookupInstanceMethod(Sel);
2180 else
2181 Method = IMD->lookupClassMethod(Sel);
2182 } else if (ObjcCategoryImplDecl *CID =
2183 dyn_cast<ObjcCategoryImplDecl>(impCxt)) {
2184 if (receiverType == Context.getObjcIdType())
2185 Method = CID->lookupInstanceMethod(Sel);
2186 else
2187 Method = CID->lookupClassMethod(Sel);
2188 }
2189 }
Steve Naroff7e461452007-10-16 20:39:36 +00002190 if (!Method) {
2191 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2192 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002193 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002194 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002195 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002196 if (Sel.getNumArgs())
2197 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2198 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002199 }
Steve Naroffee1de132007-10-10 21:53:07 +00002200 } else {
Chris Lattner71c01112007-10-10 23:42:28 +00002201 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2202 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroffee1de132007-10-10 21:53:07 +00002203 while (receiverType->isPointerType()) {
Chris Lattner71c01112007-10-10 23:42:28 +00002204 PointerType *pointerType =
2205 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroffee1de132007-10-10 21:53:07 +00002206 receiverType = pointerType->getPointeeType();
2207 }
Chris Lattner71c01112007-10-10 23:42:28 +00002208 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2209 "bad receiver type");
Steve Naroffee1de132007-10-10 21:53:07 +00002210 ObjcInterfaceDecl* ClassDecl = static_cast<ObjcInterfaceType*>(
2211 receiverType.getTypePtr())->getDecl();
Steve Naroff7e461452007-10-16 20:39:36 +00002212 // FIXME: consider using InstanceMethodPool, since it will be faster
2213 // than the following method (which can do *many* linear searches). The
2214 // idea is to add class info to InstanceMethodPool...
Steve Naroff1e1c3912007-11-03 16:37:59 +00002215 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002216 if (!Method) {
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002217 // If we have an implementation in scope, check "private" methods.
2218 if (ObjcImplementationDecl *ImpDecl =
2219 ObjcImplementations[ClassDecl->getIdentifier()])
2220 Method = ImpDecl->lookupInstanceMethod(Sel);
2221 }
2222 if (!Method) {
Steve Naroff7e461452007-10-16 20:39:36 +00002223 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2224 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002225 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002226 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002227 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002228 if (Sel.getNumArgs())
2229 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2230 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002231 }
Steve Narofffa465d12007-10-02 20:01:56 +00002232 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002233 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002234 ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002235}