blob: b08695ff76fe1d36bf0b7ede3b86b4ed86883cbd [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
Ted Kremenekddedbe22007-11-29 00:56:49 +0000191 // isExact will be set by GetFloatValue().
192 bool isExact = false;
193
194 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
195 Ty, Tok.getLocation());
196
Chris Lattner1de66eb2007-08-26 03:42:43 +0000197 } else if (!Literal.isIntegerLiteral()) {
198 return ExprResult(true);
199 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000200 QualType t;
201
Neil Booth7421e9c2007-08-29 22:00:19 +0000202 // long long is a C99 feature.
203 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000204 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000205 Diag(Tok.getLocation(), diag::ext_longlong);
206
Chris Lattner4b009652007-07-25 00:24:17 +0000207 // Get the value in the widest-possible width.
208 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
209
210 if (Literal.GetIntegerValue(ResultVal)) {
211 // If this value didn't fit into uintmax_t, warn and force to ull.
212 Diag(Tok.getLocation(), diag::warn_integer_too_large);
213 t = Context.UnsignedLongLongTy;
214 assert(Context.getTypeSize(t, Tok.getLocation()) ==
215 ResultVal.getBitWidth() && "long long is not intmax_t?");
216 } else {
217 // If this value fits into a ULL, try to figure out what else it fits into
218 // according to the rules of C99 6.4.4.1p5.
219
220 // Octal, Hexadecimal, and integers with a U suffix are allowed to
221 // be an unsigned int.
222 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
223
224 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000225 if (!Literal.isLong && !Literal.isLongLong) {
226 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000227 unsigned IntSize = static_cast<unsigned>(
228 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000229 // Does it fit in a unsigned int?
230 if (ResultVal.isIntN(IntSize)) {
231 // Does it fit in a signed int?
232 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
233 t = Context.IntTy;
234 else if (AllowUnsigned)
235 t = Context.UnsignedIntTy;
236 }
237
238 if (!t.isNull())
239 ResultVal.trunc(IntSize);
240 }
241
242 // Are long/unsigned long possibilities?
243 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000244 unsigned LongSize = static_cast<unsigned>(
245 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000246
247 // Does it fit in a unsigned long?
248 if (ResultVal.isIntN(LongSize)) {
249 // Does it fit in a signed long?
250 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
251 t = Context.LongTy;
252 else if (AllowUnsigned)
253 t = Context.UnsignedLongTy;
254 }
255 if (!t.isNull())
256 ResultVal.trunc(LongSize);
257 }
258
259 // Finally, check long long if needed.
260 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000261 unsigned LongLongSize = static_cast<unsigned>(
262 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000263
264 // Does it fit in a unsigned long long?
265 if (ResultVal.isIntN(LongLongSize)) {
266 // Does it fit in a signed long long?
267 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
268 t = Context.LongLongTy;
269 else if (AllowUnsigned)
270 t = Context.UnsignedLongLongTy;
271 }
272 }
273
274 // If we still couldn't decide a type, we probably have something that
275 // does not fit in a signed long long, but has no U suffix.
276 if (t.isNull()) {
277 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
278 t = Context.UnsignedLongLongTy;
279 }
280 }
281
Chris Lattner1de66eb2007-08-26 03:42:43 +0000282 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000283 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000284
285 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
286 if (Literal.isImaginary)
287 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
288
289 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000290}
291
Steve Naroff87d58b42007-09-16 03:34:24 +0000292Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000293 ExprTy *Val) {
294 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000295 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000296 return new ParenExpr(L, R, e);
297}
298
299/// The UsualUnaryConversions() function is *not* called by this routine.
300/// See C99 6.3.2.1p[2-4] for more details.
301QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
302 SourceLocation OpLoc, bool isSizeof) {
303 // C99 6.5.3.4p1:
304 if (isa<FunctionType>(exprType) && isSizeof)
305 // alignof(function) is allowed.
306 Diag(OpLoc, diag::ext_sizeof_function_type);
307 else if (exprType->isVoidType())
308 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
309 else if (exprType->isIncompleteType()) {
310 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
311 diag::err_alignof_incomplete_type,
312 exprType.getAsString());
313 return QualType(); // error
314 }
315 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
316 return Context.getSizeType();
317}
318
319Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000320ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000321 SourceLocation LPLoc, TypeTy *Ty,
322 SourceLocation RPLoc) {
323 // If error parsing type, ignore.
324 if (Ty == 0) return true;
325
326 // Verify that this is a valid expression.
327 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
328
329 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
330
331 if (resultType.isNull())
332 return true;
333 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
334}
335
Chris Lattner5110ad52007-08-24 21:41:10 +0000336QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000337 DefaultFunctionArrayConversion(V);
338
Chris Lattnera16e42d2007-08-26 05:39:26 +0000339 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000340 if (const ComplexType *CT = V->getType()->getAsComplexType())
341 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000342
343 // Otherwise they pass through real integer and floating point types here.
344 if (V->getType()->isArithmeticType())
345 return V->getType();
346
347 // Reject anything else.
348 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
349 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000350}
351
352
Chris Lattner4b009652007-07-25 00:24:17 +0000353
Steve Naroff87d58b42007-09-16 03:34:24 +0000354Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000355 tok::TokenKind Kind,
356 ExprTy *Input) {
357 UnaryOperator::Opcode Opc;
358 switch (Kind) {
359 default: assert(0 && "Unknown unary op!");
360 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
361 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
362 }
363 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
364 if (result.isNull())
365 return true;
366 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
367}
368
369Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000370ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000371 ExprTy *Idx, SourceLocation RLoc) {
372 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
373
374 // Perform default conversions.
375 DefaultFunctionArrayConversion(LHSExp);
376 DefaultFunctionArrayConversion(RHSExp);
377
378 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
379
380 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000381 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000382 // in the subscript position. As a result, we need to derive the array base
383 // and index from the expression types.
384 Expr *BaseExpr, *IndexExpr;
385 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000386 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000387 BaseExpr = LHSExp;
388 IndexExpr = RHSExp;
389 // FIXME: need to deal with const...
390 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000391 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000392 // Handle the uncommon case of "123[Ptr]".
393 BaseExpr = RHSExp;
394 IndexExpr = LHSExp;
395 // FIXME: need to deal with const...
396 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000397 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
398 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000399 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000400
401 // Component access limited to variables (reject vec4.rg[1]).
402 if (!isa<DeclRefExpr>(BaseExpr))
403 return Diag(LLoc, diag::err_ocuvector_component_access,
404 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000405 // FIXME: need to deal with const...
406 ResultType = VTy->getElementType();
407 } else {
408 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
409 RHSExp->getSourceRange());
410 }
411 // C99 6.5.2.1p1
412 if (!IndexExpr->getType()->isIntegerType())
413 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
414 IndexExpr->getSourceRange());
415
416 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
417 // the following check catches trying to index a pointer to a function (e.g.
418 // void (*)(int)). Functions are not objects in C99.
419 if (!ResultType->isObjectType())
420 return Diag(BaseExpr->getLocStart(),
421 diag::err_typecheck_subscript_not_object,
422 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
423
424 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
425}
426
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000427QualType Sema::
428CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
429 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000430 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000431
432 // The vector accessor can't exceed the number of elements.
433 const char *compStr = CompName.getName();
434 if (strlen(compStr) > vecType->getNumElements()) {
435 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
436 baseType.getAsString(), SourceRange(CompLoc));
437 return QualType();
438 }
439 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000440 if (vecType->getPointAccessorIdx(*compStr) != -1) {
441 do
442 compStr++;
443 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
444 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
445 do
446 compStr++;
447 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
448 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
449 do
450 compStr++;
451 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
452 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000453
454 if (*compStr) {
455 // We didn't get to the end of the string. This means the component names
456 // didn't come from the same set *or* we encountered an illegal name.
457 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
458 std::string(compStr,compStr+1), SourceRange(CompLoc));
459 return QualType();
460 }
461 // Each component accessor can't exceed the vector type.
462 compStr = CompName.getName();
463 while (*compStr) {
464 if (vecType->isAccessorWithinNumElements(*compStr))
465 compStr++;
466 else
467 break;
468 }
469 if (*compStr) {
470 // We didn't get to the end of the string. This means a component accessor
471 // exceeds the number of elements in the vector.
472 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
473 baseType.getAsString(), SourceRange(CompLoc));
474 return QualType();
475 }
476 // The component accessor looks fine - now we need to compute the actual type.
477 // The vector type is implied by the component accessor. For example,
478 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
479 unsigned CompSize = strlen(CompName.getName());
480 if (CompSize == 1)
481 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000482
483 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
484 // Now look up the TypeDefDecl from the vector type. Without this,
485 // diagostics look bad. We want OCU vector types to appear built-in.
486 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
487 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
488 return Context.getTypedefType(OCUVectorDecls[i]);
489 }
490 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000491}
492
Chris Lattner4b009652007-07-25 00:24:17 +0000493Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000494ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000495 tok::TokenKind OpKind, SourceLocation MemberLoc,
496 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000497 Expr *BaseExpr = static_cast<Expr *>(Base);
498 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000499
Steve Naroff2cb66382007-07-26 03:11:44 +0000500 QualType BaseType = BaseExpr->getType();
501 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000502
Chris Lattner4b009652007-07-25 00:24:17 +0000503 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000504 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000505 BaseType = PT->getPointeeType();
506 else
507 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
508 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000509 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000510 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000511 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000512 RecordDecl *RDecl = RTy->getDecl();
513 if (RTy->isIncompleteType())
514 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
515 BaseExpr->getSourceRange());
516 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000517 FieldDecl *MemberDecl = RDecl->getMember(&Member);
518 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000519 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
520 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000521 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
522 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000523 // Component access limited to variables (reject vec4.rg.g).
524 if (!isa<DeclRefExpr>(BaseExpr))
525 return Diag(OpLoc, diag::err_ocuvector_component_access,
526 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000527 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
528 if (ret.isNull())
529 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000530 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000531 } else if (BaseType->isObjcInterfaceType()) {
532 ObjcInterfaceDecl *IFace;
533 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
534 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
535 else
536 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)
537 ->getInterfaceType()->getDecl();
538 ObjcInterfaceDecl *clsDeclared;
539 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
540 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
541 OpKind==tok::arrow);
542 }
543 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
544 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000545}
546
Steve Naroff87d58b42007-09-16 03:34:24 +0000547/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000548/// This provides the location of the left/right parens and a list of comma
549/// locations.
550Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000551ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000552 ExprTy **args, unsigned NumArgsInCall,
553 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
554 Expr *Fn = static_cast<Expr *>(fn);
555 Expr **Args = reinterpret_cast<Expr**>(args);
556 assert(Fn && "no function call expression");
557
558 UsualUnaryConversions(Fn);
559 QualType funcType = Fn->getType();
560
561 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
562 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000563 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000564 if (PT == 0)
565 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
566 SourceRange(Fn->getLocStart(), RParenLoc));
567
Chris Lattner71225142007-07-31 21:27:01 +0000568 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000569 if (funcT == 0)
570 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
571 SourceRange(Fn->getLocStart(), RParenLoc));
572
573 // If a prototype isn't declared, the parser implicitly defines a func decl
574 QualType resultType = funcT->getResultType();
575
576 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
577 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
578 // assignment, to the types of the corresponding parameter, ...
579
580 unsigned NumArgsInProto = proto->getNumArgs();
581 unsigned NumArgsToCheck = NumArgsInCall;
582
583 if (NumArgsInCall < NumArgsInProto)
584 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
585 Fn->getSourceRange());
586 else if (NumArgsInCall > NumArgsInProto) {
587 if (!proto->isVariadic()) {
588 Diag(Args[NumArgsInProto]->getLocStart(),
589 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
590 SourceRange(Args[NumArgsInProto]->getLocStart(),
591 Args[NumArgsInCall-1]->getLocEnd()));
592 }
593 NumArgsToCheck = NumArgsInProto;
594 }
595 // Continue to check argument types (even if we have too few/many args).
596 for (unsigned i = 0; i < NumArgsToCheck; i++) {
597 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000598 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000599
600 QualType lhsType = proto->getArgType(i);
601 QualType rhsType = argExpr->getType();
602
Steve Naroff75644062007-07-25 20:45:33 +0000603 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000604 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000605 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000606 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000607 lhsType = Context.getPointerType(lhsType);
608
609 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
610 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000611 if (Args[i] != argExpr) // The expression was converted.
612 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000613 SourceLocation l = argExpr->getLocStart();
614
615 // decode the result (notice that AST's are still created for extensions).
616 switch (result) {
617 case Compatible:
618 break;
619 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +0000620 Diag(l, diag::ext_typecheck_passing_pointer_int,
621 lhsType.getAsString(), rhsType.getAsString(),
622 Fn->getSourceRange(), argExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000623 break;
624 case IntFromPointer:
625 Diag(l, diag::ext_typecheck_passing_pointer_int,
626 lhsType.getAsString(), rhsType.getAsString(),
627 Fn->getSourceRange(), argExpr->getSourceRange());
628 break;
629 case IncompatiblePointer:
630 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
631 rhsType.getAsString(), lhsType.getAsString(),
632 Fn->getSourceRange(), argExpr->getSourceRange());
633 break;
634 case CompatiblePointerDiscardsQualifiers:
635 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
636 rhsType.getAsString(), lhsType.getAsString(),
637 Fn->getSourceRange(), argExpr->getSourceRange());
638 break;
639 case Incompatible:
640 return Diag(l, diag::err_typecheck_passing_incompatible,
641 rhsType.getAsString(), lhsType.getAsString(),
642 Fn->getSourceRange(), argExpr->getSourceRange());
643 }
644 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000645 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
646 // Promote the arguments (C99 6.5.2.2p7).
647 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
648 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000649 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000650
651 DefaultArgumentPromotion(argExpr);
652 if (Args[i] != argExpr) // The expression was converted.
653 Args[i] = argExpr; // Make sure we store the converted expression.
654 }
655 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
656 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000657 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000658 }
659 } else if (isa<FunctionTypeNoProto>(funcT)) {
660 // Promote the arguments (C99 6.5.2.2p6).
661 for (unsigned i = 0; i < NumArgsInCall; i++) {
662 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000663 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000664
665 DefaultArgumentPromotion(argExpr);
666 if (Args[i] != argExpr) // The expression was converted.
667 Args[i] = argExpr; // Make sure we store the converted expression.
668 }
Chris Lattner4b009652007-07-25 00:24:17 +0000669 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000670 // Do special checking on direct calls to functions.
671 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
672 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
673 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000674 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
675 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000676 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000677
Chris Lattner4b009652007-07-25 00:24:17 +0000678 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
679}
680
681Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000682ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000683 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000684 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000685 QualType literalType = QualType::getFromOpaquePtr(Ty);
686 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000687 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000688 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000689
690 // FIXME: add more semantic analysis (C99 6.5.2.5).
691 if (CheckInitializer(literalExpr, literalType, false))
692 return 0;
693
Chris Lattner4b009652007-07-25 00:24:17 +0000694 return new CompoundLiteralExpr(literalType, literalExpr);
695}
696
697Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000698ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000699 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000700 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000701
Steve Naroff0acc9c92007-09-15 18:49:24 +0000702 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000703 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000704
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000705 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
706 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
707 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000708}
709
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000710bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty)
711{
712 assert(VectorTy->isVectorType() && "Not a vector type!");
713
714 if (Ty->isVectorType() || Ty->isIntegerType()) {
715 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
716 Context.getTypeSize(Ty, SourceLocation()))
717 return Diag(R.getBegin(),
718 Ty->isVectorType() ?
719 diag::err_invalid_conversion_between_vectors :
720 diag::err_invalid_conversion_between_vector_and_integer,
721 VectorTy.getAsString().c_str(),
722 Ty.getAsString().c_str(), R);
723 } else
724 return Diag(R.getBegin(),
725 diag::err_invalid_conversion_between_vector_and_scalar,
726 VectorTy.getAsString().c_str(),
727 Ty.getAsString().c_str(), R);
728
729 return false;
730}
731
Chris Lattner4b009652007-07-25 00:24:17 +0000732Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000733ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000734 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000735 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000736
737 Expr *castExpr = static_cast<Expr*>(Op);
738 QualType castType = QualType::getFromOpaquePtr(Ty);
739
Steve Naroff68adb482007-08-31 00:32:44 +0000740 UsualUnaryConversions(castExpr);
741
Chris Lattner4b009652007-07-25 00:24:17 +0000742 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
743 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000744 if (!castType->isVoidType()) { // Cast to void allows any expr type.
745 if (!castType->isScalarType())
746 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
747 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000748 if (!castExpr->getType()->isScalarType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000749 return Diag(castExpr->getLocStart(),
750 diag::err_typecheck_expect_scalar_operand,
751 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000752
753 if (castExpr->getType()->isVectorType()) {
754 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
755 castExpr->getType(), castType))
756 return true;
757 } else if (castType->isVectorType()) {
758 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
759 castType, castExpr->getType()))
760 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000761 }
Chris Lattner4b009652007-07-25 00:24:17 +0000762 }
763 return new CastExpr(castType, castExpr, LParenLoc);
764}
765
Steve Naroff144667e2007-10-18 05:13:08 +0000766// promoteExprToType - a helper function to ensure we create exactly one
767// ImplicitCastExpr.
768static void promoteExprToType(Expr *&expr, QualType type) {
769 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
770 impCast->setType(type);
771 else
772 expr = new ImplicitCastExpr(type, expr);
773 return;
774}
775
Chris Lattner98a425c2007-11-26 01:40:58 +0000776/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
777/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000778inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
779 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
780 UsualUnaryConversions(cond);
781 UsualUnaryConversions(lex);
782 UsualUnaryConversions(rex);
783 QualType condT = cond->getType();
784 QualType lexT = lex->getType();
785 QualType rexT = rex->getType();
786
787 // first, check the condition.
788 if (!condT->isScalarType()) { // C99 6.5.15p2
789 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
790 condT.getAsString());
791 return QualType();
792 }
793 // now check the two expressions.
794 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
795 UsualArithmeticConversions(lex, rex);
796 return lex->getType();
797 }
Chris Lattner71225142007-07-31 21:27:01 +0000798 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
799 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattner98a425c2007-11-26 01:40:58 +0000800 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner71225142007-07-31 21:27:01 +0000801 return lexT;
802
Chris Lattner4b009652007-07-25 00:24:17 +0000803 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
804 lexT.getAsString(), rexT.getAsString(),
805 lex->getSourceRange(), rex->getSourceRange());
806 return QualType();
807 }
808 }
809 // C99 6.5.15p3
Steve Naroff144667e2007-10-18 05:13:08 +0000810 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
811 promoteExprToType(rex, lexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000812 return lexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000813 }
814 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
815 promoteExprToType(lex, rexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000816 return rexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000817 }
Chris Lattner71225142007-07-31 21:27:01 +0000818 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
819 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
820 // get the "pointed to" types
821 QualType lhptee = LHSPT->getPointeeType();
822 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000823
Chris Lattner71225142007-07-31 21:27:01 +0000824 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
825 if (lhptee->isVoidType() &&
826 (rhptee->isObjectType() || rhptee->isIncompleteType()))
827 return lexT;
828 if (rhptee->isVoidType() &&
829 (lhptee->isObjectType() || lhptee->isIncompleteType()))
830 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000831
Steve Naroff85f0dc52007-10-15 20:41:53 +0000832 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
833 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000834 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
835 lexT.getAsString(), rexT.getAsString(),
836 lex->getSourceRange(), rex->getSourceRange());
837 return lexT; // FIXME: this is an _ext - is this return o.k?
838 }
839 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000840 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
841 // differently qualified versions of compatible types, the result type is
842 // a pointer to an appropriately qualified version of the *composite*
843 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000844 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000845 }
Chris Lattner4b009652007-07-25 00:24:17 +0000846 }
Chris Lattner71225142007-07-31 21:27:01 +0000847
Chris Lattner4b009652007-07-25 00:24:17 +0000848 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
849 return lexT;
850
851 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
852 lexT.getAsString(), rexT.getAsString(),
853 lex->getSourceRange(), rex->getSourceRange());
854 return QualType();
855}
856
Steve Naroff87d58b42007-09-16 03:34:24 +0000857/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000858/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000859Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000860 SourceLocation ColonLoc,
861 ExprTy *Cond, ExprTy *LHS,
862 ExprTy *RHS) {
863 Expr *CondExpr = (Expr *) Cond;
864 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000865
866 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
867 // was the condition.
868 bool isLHSNull = LHSExpr == 0;
869 if (isLHSNull)
870 LHSExpr = CondExpr;
871
Chris Lattner4b009652007-07-25 00:24:17 +0000872 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
873 RHSExpr, QuestionLoc);
874 if (result.isNull())
875 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000876 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
877 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000878}
879
Steve Naroffdb65e052007-08-28 23:30:39 +0000880/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
881/// do not have a prototype. Integer promotions are performed on each
882/// argument, and arguments that have type float are promoted to double.
883void Sema::DefaultArgumentPromotion(Expr *&expr) {
884 QualType t = expr->getType();
885 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
886
887 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
888 promoteExprToType(expr, Context.IntTy);
889 if (t == Context.FloatTy)
890 promoteExprToType(expr, Context.DoubleTy);
891}
892
Chris Lattner4b009652007-07-25 00:24:17 +0000893/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
894void Sema::DefaultFunctionArrayConversion(Expr *&e) {
895 QualType t = e->getType();
896 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
897
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000898 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000899 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
900 t = e->getType();
901 }
902 if (t->isFunctionType())
903 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000904 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000905 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
906}
907
908/// UsualUnaryConversion - Performs various conversions that are common to most
909/// operators (C99 6.3). The conversions of array and function types are
910/// sometimes surpressed. For example, the array->pointer conversion doesn't
911/// apply if the array is an argument to the sizeof or address (&) operators.
912/// In these instances, this routine should *not* be called.
913void Sema::UsualUnaryConversions(Expr *&expr) {
914 QualType t = expr->getType();
915 assert(!t.isNull() && "UsualUnaryConversions - missing type");
916
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000917 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000918 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
919 t = expr->getType();
920 }
921 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
922 promoteExprToType(expr, Context.IntTy);
923 else
924 DefaultFunctionArrayConversion(expr);
925}
926
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000927/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000928/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
929/// routine returns the first non-arithmetic type found. The client is
930/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000931QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
932 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000933 if (!isCompAssign) {
934 UsualUnaryConversions(lhsExpr);
935 UsualUnaryConversions(rhsExpr);
936 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000937 // For conversion purposes, we ignore any qualifiers.
938 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000939 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
940 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000941
942 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000943 if (lhs == rhs)
944 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000945
946 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
947 // The caller can deal with this (e.g. pointer + int).
948 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000949 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000950
951 // At this point, we have two different arithmetic types.
952
953 // Handle complex types first (C99 6.3.1.8p1).
954 if (lhs->isComplexType() || rhs->isComplexType()) {
955 // if we have an integer operand, the result is the complex type.
956 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000957 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
958 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000959 }
960 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000961 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
962 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000963 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000964 // This handles complex/complex, complex/float, or float/complex.
965 // When both operands are complex, the shorter operand is converted to the
966 // type of the longer, and that is the type of the result. This corresponds
967 // to what is done when combining two real floating-point operands.
968 // The fun begins when size promotion occur across type domains.
969 // From H&S 6.3.4: When one operand is complex and the other is a real
970 // floating-point type, the less precise type is converted, within it's
971 // real or complex domain, to the precision of the other type. For example,
972 // when combining a "long double" with a "double _Complex", the
973 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000974 int result = Context.compareFloatingType(lhs, rhs);
975
976 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000977 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
978 if (!isCompAssign)
979 promoteExprToType(rhsExpr, rhs);
980 } else if (result < 0) { // The right side is bigger, convert lhs.
981 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
982 if (!isCompAssign)
983 promoteExprToType(lhsExpr, lhs);
984 }
985 // At this point, lhs and rhs have the same rank/size. Now, make sure the
986 // domains match. This is a requirement for our implementation, C99
987 // does not require this promotion.
988 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
989 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000990 if (!isCompAssign)
991 promoteExprToType(lhsExpr, rhs);
992 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000993 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000994 if (!isCompAssign)
995 promoteExprToType(rhsExpr, lhs);
996 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000997 }
Chris Lattner4b009652007-07-25 00:24:17 +0000998 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000999 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001000 }
1001 // Now handle "real" floating types (i.e. float, double, long double).
1002 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1003 // if we have an integer operand, the result is the real floating type.
1004 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001005 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1006 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001007 }
1008 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001009 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1010 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001011 }
1012 // We have two real floating types, float/complex combos were handled above.
1013 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001014 int result = Context.compareFloatingType(lhs, rhs);
1015
1016 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001017 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1018 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001019 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001020 if (result < 0) { // convert the lhs
1021 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1022 return rhs;
1023 }
1024 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001025 }
1026 // Finally, we have two differing integer types.
1027 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001028 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1029 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001030 }
Steve Naroff8f708362007-08-24 19:07:16 +00001031 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1032 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001033}
1034
1035// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1036// being closely modeled after the C99 spec:-). The odd characteristic of this
1037// routine is it effectively iqnores the qualifiers on the top level pointee.
1038// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1039// FIXME: add a couple examples in this comment.
1040Sema::AssignmentCheckResult
1041Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1042 QualType lhptee, rhptee;
1043
1044 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001045 lhptee = lhsType->getAsPointerType()->getPointeeType();
1046 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001047
1048 // make sure we operate on the canonical type
1049 lhptee = lhptee.getCanonicalType();
1050 rhptee = rhptee.getCanonicalType();
1051
1052 AssignmentCheckResult r = Compatible;
1053
1054 // C99 6.5.16.1p1: This following citation is common to constraints
1055 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1056 // qualifiers of the type *pointed to* by the right;
1057 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1058 rhptee.getQualifiers())
1059 r = CompatiblePointerDiscardsQualifiers;
1060
1061 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1062 // incomplete type and the other is a pointer to a qualified or unqualified
1063 // version of void...
1064 if (lhptee.getUnqualifiedType()->isVoidType() &&
1065 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1066 ;
1067 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1068 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1069 ;
1070 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1071 // unqualified versions of compatible types, ...
Steve Naroff85f0dc52007-10-15 20:41:53 +00001072 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1073 rhptee.getUnqualifiedType()))
Chris Lattner4b009652007-07-25 00:24:17 +00001074 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1075 return r;
1076}
1077
1078/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1079/// has code to accommodate several GCC extensions when type checking
1080/// pointers. Here are some objectionable examples that GCC considers warnings:
1081///
1082/// int a, *pint;
1083/// short *pshort;
1084/// struct foo *pfoo;
1085///
1086/// pint = pshort; // warning: assignment from incompatible pointer type
1087/// a = pint; // warning: assignment makes integer from pointer without a cast
1088/// pint = a; // warning: assignment makes pointer from integer without a cast
1089/// pint = pfoo; // warning: assignment from incompatible pointer type
1090///
1091/// As a result, the code for dealing with pointers is more complex than the
1092/// C99 spec dictates.
1093/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1094///
1095Sema::AssignmentCheckResult
1096Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroffeed76842007-11-13 00:31:42 +00001097 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1098 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattnera703c2e2007-10-29 05:15:40 +00001099 return Compatible; // common case, fast path...
Chris Lattner4b009652007-07-25 00:24:17 +00001100
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001101 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001102 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001103 return Compatible;
1104 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001105 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Anders Carlssone87cd982007-11-30 04:21:22 +00001106 if (!getLangOptions().LaxVectorConversions) {
1107 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1108 return Incompatible;
1109 } else {
1110 if (lhsType->isVectorType() && rhsType->isVectorType()) {
1111 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1112 (lhsType->isRealFloatingType() &&
1113 rhsType->isRealFloatingType())) {
1114 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1115 Context.getTypeSize(rhsType, SourceLocation()))
1116 return Compatible;
1117 }
1118 }
Chris Lattner4b009652007-07-25 00:24:17 +00001119 return Incompatible;
Anders Carlssone87cd982007-11-30 04:21:22 +00001120 }
1121 }
Chris Lattner4b009652007-07-25 00:24:17 +00001122 return Compatible;
1123 } else if (lhsType->isPointerType()) {
1124 if (rhsType->isIntegerType())
1125 return PointerFromInt;
1126
1127 if (rhsType->isPointerType())
1128 return CheckPointerTypesForAssignment(lhsType, rhsType);
1129 } else if (rhsType->isPointerType()) {
1130 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1131 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1132 return IntFromPointer;
1133
1134 if (lhsType->isPointerType())
1135 return CheckPointerTypesForAssignment(lhsType, rhsType);
1136 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001137 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001138 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001139 }
1140 return Incompatible;
1141}
1142
1143Sema::AssignmentCheckResult
1144Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001145 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1146 // a null pointer constant.
1147 if (lhsType->isPointerType() && rExpr->isNullPointerConstant(Context)) {
1148 promoteExprToType(rExpr, lhsType);
1149 return Compatible;
1150 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001151 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001152 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001153 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001154 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001155 //
1156 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1157 // are better understood.
1158 if (!lhsType->isReferenceType())
1159 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001160
1161 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001162
Steve Naroff0f32f432007-08-24 22:33:52 +00001163 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1164
1165 // C99 6.5.16.1p2: The value of the right operand is converted to the
1166 // type of the assignment expression.
1167 if (rExpr->getType() != lhsType)
1168 promoteExprToType(rExpr, lhsType);
1169 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001170}
1171
1172Sema::AssignmentCheckResult
1173Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1174 return CheckAssignmentConstraints(lhsType, rhsType);
1175}
1176
1177inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1178 Diag(loc, diag::err_typecheck_invalid_operands,
1179 lex->getType().getAsString(), rex->getType().getAsString(),
1180 lex->getSourceRange(), rex->getSourceRange());
1181}
1182
1183inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1184 Expr *&rex) {
1185 QualType lhsType = lex->getType(), rhsType = rex->getType();
1186
1187 // make sure the vector types are identical.
1188 if (lhsType == rhsType)
1189 return lhsType;
1190 // You cannot convert between vector values of different size.
1191 Diag(loc, diag::err_typecheck_vector_not_convertable,
1192 lex->getType().getAsString(), rex->getType().getAsString(),
1193 lex->getSourceRange(), rex->getSourceRange());
1194 return QualType();
1195}
1196
1197inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001198 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001199{
1200 QualType lhsType = lex->getType(), rhsType = rex->getType();
1201
1202 if (lhsType->isVectorType() || rhsType->isVectorType())
1203 return CheckVectorOperands(loc, lex, rex);
1204
Steve Naroff8f708362007-08-24 19:07:16 +00001205 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001206
Chris Lattner4b009652007-07-25 00:24:17 +00001207 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001208 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001209 InvalidOperands(loc, lex, rex);
1210 return QualType();
1211}
1212
1213inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001214 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001215{
1216 QualType lhsType = lex->getType(), rhsType = rex->getType();
1217
Steve Naroff8f708362007-08-24 19:07:16 +00001218 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001219
Chris Lattner4b009652007-07-25 00:24:17 +00001220 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001221 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001222 InvalidOperands(loc, lex, rex);
1223 return QualType();
1224}
1225
1226inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001227 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001228{
1229 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1230 return CheckVectorOperands(loc, lex, rex);
1231
Steve Naroff8f708362007-08-24 19:07:16 +00001232 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001233
1234 // handle the common case first (both operands are arithmetic).
1235 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001236 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001237
1238 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1239 return lex->getType();
1240 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1241 return rex->getType();
1242 InvalidOperands(loc, lex, rex);
1243 return QualType();
1244}
1245
1246inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001247 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001248{
1249 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1250 return CheckVectorOperands(loc, lex, rex);
1251
Steve Naroff8f708362007-08-24 19:07:16 +00001252 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001253
1254 // handle the common case first (both operands are arithmetic).
1255 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001256 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001257
1258 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001259 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001260 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1261 return Context.getPointerDiffType();
1262 InvalidOperands(loc, lex, rex);
1263 return QualType();
1264}
1265
1266inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001267 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001268{
1269 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1270 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001271 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001272
1273 // handle the common case first (both operands are arithmetic).
1274 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001275 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001276 InvalidOperands(loc, lex, rex);
1277 return QualType();
1278}
1279
Chris Lattner254f3bc2007-08-26 01:18:55 +00001280inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1281 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001282{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001283 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001284 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1285 UsualArithmeticConversions(lex, rex);
1286 else {
1287 UsualUnaryConversions(lex);
1288 UsualUnaryConversions(rex);
1289 }
Chris Lattner4b009652007-07-25 00:24:17 +00001290 QualType lType = lex->getType();
1291 QualType rType = rex->getType();
1292
Ted Kremenek486509e2007-10-29 17:13:39 +00001293 // For non-floating point types, check for self-comparisons of the form
1294 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1295 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001296 if (!lType->isFloatingType()) {
1297 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1298 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1299 if (DRL->getDecl() == DRR->getDecl())
1300 Diag(loc, diag::warn_selfcomparison);
1301 }
1302
Chris Lattner254f3bc2007-08-26 01:18:55 +00001303 if (isRelational) {
1304 if (lType->isRealType() && rType->isRealType())
1305 return Context.IntTy;
1306 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001307 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001308 if (lType->isFloatingType()) {
1309 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001310 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001311 }
1312
Chris Lattner254f3bc2007-08-26 01:18:55 +00001313 if (lType->isArithmeticType() && rType->isArithmeticType())
1314 return Context.IntTy;
1315 }
Chris Lattner4b009652007-07-25 00:24:17 +00001316
Chris Lattner22be8422007-08-26 01:10:14 +00001317 bool LHSIsNull = lex->isNullPointerConstant(Context);
1318 bool RHSIsNull = rex->isNullPointerConstant(Context);
1319
Chris Lattner254f3bc2007-08-26 01:18:55 +00001320 // All of the following pointer related warnings are GCC extensions, except
1321 // when handling null pointer constants. One day, we can consider making them
1322 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001323 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001324
1325 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1326 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1327 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001328 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1329 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001330 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1331 lType.getAsString(), rType.getAsString(),
1332 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001333 }
Chris Lattner22be8422007-08-26 01:10:14 +00001334 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001335 return Context.IntTy;
1336 }
1337 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001338 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001339 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1340 lType.getAsString(), rType.getAsString(),
1341 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001342 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001343 return Context.IntTy;
1344 }
1345 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001346 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001347 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1348 lType.getAsString(), rType.getAsString(),
1349 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001350 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001351 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001352 }
1353 InvalidOperands(loc, lex, rex);
1354 return QualType();
1355}
1356
Chris Lattner4b009652007-07-25 00:24:17 +00001357inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001358 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001359{
1360 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1361 return CheckVectorOperands(loc, lex, rex);
1362
Steve Naroff8f708362007-08-24 19:07:16 +00001363 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001364
1365 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001366 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001367 InvalidOperands(loc, lex, rex);
1368 return QualType();
1369}
1370
1371inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1372 Expr *&lex, Expr *&rex, SourceLocation loc)
1373{
1374 UsualUnaryConversions(lex);
1375 UsualUnaryConversions(rex);
1376
1377 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1378 return Context.IntTy;
1379 InvalidOperands(loc, lex, rex);
1380 return QualType();
1381}
1382
1383inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001384 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001385{
1386 QualType lhsType = lex->getType();
1387 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1388 bool hadError = false;
1389 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1390
1391 switch (mlval) { // C99 6.5.16p2
1392 case Expr::MLV_Valid:
1393 break;
1394 case Expr::MLV_ConstQualified:
1395 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1396 hadError = true;
1397 break;
1398 case Expr::MLV_ArrayType:
1399 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1400 lhsType.getAsString(), lex->getSourceRange());
1401 return QualType();
1402 case Expr::MLV_NotObjectType:
1403 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1404 lhsType.getAsString(), lex->getSourceRange());
1405 return QualType();
1406 case Expr::MLV_InvalidExpression:
1407 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1408 lex->getSourceRange());
1409 return QualType();
1410 case Expr::MLV_IncompleteType:
1411 case Expr::MLV_IncompleteVoidType:
1412 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1413 lhsType.getAsString(), lex->getSourceRange());
1414 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001415 case Expr::MLV_DuplicateVectorComponents:
1416 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1417 lex->getSourceRange());
1418 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001419 }
1420 AssignmentCheckResult result;
1421
1422 if (compoundType.isNull())
1423 result = CheckSingleAssignmentConstraints(lhsType, rex);
1424 else
1425 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001426
Chris Lattner4b009652007-07-25 00:24:17 +00001427 // decode the result (notice that extensions still return a type).
1428 switch (result) {
1429 case Compatible:
1430 break;
1431 case Incompatible:
1432 Diag(loc, diag::err_typecheck_assign_incompatible,
1433 lhsType.getAsString(), rhsType.getAsString(),
1434 lex->getSourceRange(), rex->getSourceRange());
1435 hadError = true;
1436 break;
1437 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00001438 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1439 lhsType.getAsString(), rhsType.getAsString(),
1440 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001441 break;
1442 case IntFromPointer:
1443 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1444 lhsType.getAsString(), rhsType.getAsString(),
1445 lex->getSourceRange(), rex->getSourceRange());
1446 break;
1447 case IncompatiblePointer:
1448 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1449 lhsType.getAsString(), rhsType.getAsString(),
1450 lex->getSourceRange(), rex->getSourceRange());
1451 break;
1452 case CompatiblePointerDiscardsQualifiers:
1453 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1454 lhsType.getAsString(), rhsType.getAsString(),
1455 lex->getSourceRange(), rex->getSourceRange());
1456 break;
1457 }
1458 // C99 6.5.16p3: The type of an assignment expression is the type of the
1459 // left operand unless the left operand has qualified type, in which case
1460 // it is the unqualified version of the type of the left operand.
1461 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1462 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001463 // C++ 5.17p1: the type of the assignment expression is that of its left
1464 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001465 return hadError ? QualType() : lhsType.getUnqualifiedType();
1466}
1467
1468inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1469 Expr *&lex, Expr *&rex, SourceLocation loc) {
1470 UsualUnaryConversions(rex);
1471 return rex->getType();
1472}
1473
1474/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1475/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1476QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1477 QualType resType = op->getType();
1478 assert(!resType.isNull() && "no type for increment/decrement expression");
1479
Steve Naroffd30e1932007-08-24 17:20:07 +00001480 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001481 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001482 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1483 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1484 resType.getAsString(), op->getSourceRange());
1485 return QualType();
1486 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001487 } else if (!resType->isRealType()) {
1488 if (resType->isComplexType())
1489 // C99 does not support ++/-- on complex types.
1490 Diag(OpLoc, diag::ext_integer_increment_complex,
1491 resType.getAsString(), op->getSourceRange());
1492 else {
1493 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1494 resType.getAsString(), op->getSourceRange());
1495 return QualType();
1496 }
Chris Lattner4b009652007-07-25 00:24:17 +00001497 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001498 // At this point, we know we have a real, complex or pointer type.
1499 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001500 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1501 if (mlval != Expr::MLV_Valid) {
1502 // FIXME: emit a more precise diagnostic...
1503 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1504 op->getSourceRange());
1505 return QualType();
1506 }
1507 return resType;
1508}
1509
1510/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1511/// This routine allows us to typecheck complex/recursive expressions
1512/// where the declaration is needed for type checking. Here are some
1513/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1514static Decl *getPrimaryDeclaration(Expr *e) {
1515 switch (e->getStmtClass()) {
1516 case Stmt::DeclRefExprClass:
1517 return cast<DeclRefExpr>(e)->getDecl();
1518 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001519 // Fields cannot be declared with a 'register' storage class.
1520 // &X->f is always ok, even if X is declared register.
1521 if (cast<MemberExpr>(e)->isArrow())
1522 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001523 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1524 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001525 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001526 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001527 case Stmt::UnaryOperatorClass:
1528 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1529 case Stmt::ParenExprClass:
1530 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001531 case Stmt::ImplicitCastExprClass:
1532 // &X[4] when X is an array, has an implicit cast from array to pointer.
1533 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001534 default:
1535 return 0;
1536 }
1537}
1538
1539/// CheckAddressOfOperand - The operand of & must be either a function
1540/// designator or an lvalue designating an object. If it is an lvalue, the
1541/// object cannot be declared with storage class register or be a bit field.
1542/// Note: The usual conversions are *not* applied to the operand of the &
1543/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1544QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1545 Decl *dcl = getPrimaryDeclaration(op);
1546 Expr::isLvalueResult lval = op->isLvalue();
1547
1548 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001549 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1550 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001551 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1552 op->getSourceRange());
1553 return QualType();
1554 }
1555 } else if (dcl) {
1556 // We have an lvalue with a decl. Make sure the decl is not declared
1557 // with the register storage-class specifier.
1558 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1559 if (vd->getStorageClass() == VarDecl::Register) {
1560 Diag(OpLoc, diag::err_typecheck_address_of_register,
1561 op->getSourceRange());
1562 return QualType();
1563 }
1564 } else
1565 assert(0 && "Unknown/unexpected decl type");
1566
1567 // FIXME: add check for bitfields!
1568 }
1569 // If the operand has type "type", the result has type "pointer to type".
1570 return Context.getPointerType(op->getType());
1571}
1572
1573QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1574 UsualUnaryConversions(op);
1575 QualType qType = op->getType();
1576
Chris Lattner7931f4a2007-07-31 16:53:04 +00001577 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001578 QualType ptype = PT->getPointeeType();
1579 // C99 6.5.3.2p4. "if it points to an object,...".
1580 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1581 // GCC compat: special case 'void *' (treat as warning).
1582 if (ptype->isVoidType()) {
1583 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1584 qType.getAsString(), op->getSourceRange());
1585 } else {
1586 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1587 ptype.getAsString(), op->getSourceRange());
1588 return QualType();
1589 }
1590 }
1591 return ptype;
1592 }
1593 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1594 qType.getAsString(), op->getSourceRange());
1595 return QualType();
1596}
1597
1598static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1599 tok::TokenKind Kind) {
1600 BinaryOperator::Opcode Opc;
1601 switch (Kind) {
1602 default: assert(0 && "Unknown binop!");
1603 case tok::star: Opc = BinaryOperator::Mul; break;
1604 case tok::slash: Opc = BinaryOperator::Div; break;
1605 case tok::percent: Opc = BinaryOperator::Rem; break;
1606 case tok::plus: Opc = BinaryOperator::Add; break;
1607 case tok::minus: Opc = BinaryOperator::Sub; break;
1608 case tok::lessless: Opc = BinaryOperator::Shl; break;
1609 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1610 case tok::lessequal: Opc = BinaryOperator::LE; break;
1611 case tok::less: Opc = BinaryOperator::LT; break;
1612 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1613 case tok::greater: Opc = BinaryOperator::GT; break;
1614 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1615 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1616 case tok::amp: Opc = BinaryOperator::And; break;
1617 case tok::caret: Opc = BinaryOperator::Xor; break;
1618 case tok::pipe: Opc = BinaryOperator::Or; break;
1619 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1620 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1621 case tok::equal: Opc = BinaryOperator::Assign; break;
1622 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1623 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1624 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1625 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1626 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1627 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1628 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1629 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1630 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1631 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1632 case tok::comma: Opc = BinaryOperator::Comma; break;
1633 }
1634 return Opc;
1635}
1636
1637static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1638 tok::TokenKind Kind) {
1639 UnaryOperator::Opcode Opc;
1640 switch (Kind) {
1641 default: assert(0 && "Unknown unary op!");
1642 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1643 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1644 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1645 case tok::star: Opc = UnaryOperator::Deref; break;
1646 case tok::plus: Opc = UnaryOperator::Plus; break;
1647 case tok::minus: Opc = UnaryOperator::Minus; break;
1648 case tok::tilde: Opc = UnaryOperator::Not; break;
1649 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1650 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1651 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1652 case tok::kw___real: Opc = UnaryOperator::Real; break;
1653 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1654 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1655 }
1656 return Opc;
1657}
1658
1659// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001660Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001661 ExprTy *LHS, ExprTy *RHS) {
1662 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1663 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1664
Steve Naroff87d58b42007-09-16 03:34:24 +00001665 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1666 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001667
1668 QualType ResultTy; // Result type of the binary operator.
1669 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1670
1671 switch (Opc) {
1672 default:
1673 assert(0 && "Unknown binary expr!");
1674 case BinaryOperator::Assign:
1675 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1676 break;
1677 case BinaryOperator::Mul:
1678 case BinaryOperator::Div:
1679 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1680 break;
1681 case BinaryOperator::Rem:
1682 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1683 break;
1684 case BinaryOperator::Add:
1685 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1686 break;
1687 case BinaryOperator::Sub:
1688 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1689 break;
1690 case BinaryOperator::Shl:
1691 case BinaryOperator::Shr:
1692 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1693 break;
1694 case BinaryOperator::LE:
1695 case BinaryOperator::LT:
1696 case BinaryOperator::GE:
1697 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001698 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001699 break;
1700 case BinaryOperator::EQ:
1701 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001702 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001703 break;
1704 case BinaryOperator::And:
1705 case BinaryOperator::Xor:
1706 case BinaryOperator::Or:
1707 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1708 break;
1709 case BinaryOperator::LAnd:
1710 case BinaryOperator::LOr:
1711 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1712 break;
1713 case BinaryOperator::MulAssign:
1714 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001715 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001716 if (!CompTy.isNull())
1717 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1718 break;
1719 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001720 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001721 if (!CompTy.isNull())
1722 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1723 break;
1724 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001725 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001726 if (!CompTy.isNull())
1727 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1728 break;
1729 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001730 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001731 if (!CompTy.isNull())
1732 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1733 break;
1734 case BinaryOperator::ShlAssign:
1735 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001736 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001737 if (!CompTy.isNull())
1738 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1739 break;
1740 case BinaryOperator::AndAssign:
1741 case BinaryOperator::XorAssign:
1742 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001743 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001744 if (!CompTy.isNull())
1745 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1746 break;
1747 case BinaryOperator::Comma:
1748 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1749 break;
1750 }
1751 if (ResultTy.isNull())
1752 return true;
1753 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001754 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001755 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001756 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001757}
1758
1759// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001760Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001761 ExprTy *input) {
1762 Expr *Input = (Expr*)input;
1763 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1764 QualType resultType;
1765 switch (Opc) {
1766 default:
1767 assert(0 && "Unimplemented unary expr!");
1768 case UnaryOperator::PreInc:
1769 case UnaryOperator::PreDec:
1770 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1771 break;
1772 case UnaryOperator::AddrOf:
1773 resultType = CheckAddressOfOperand(Input, OpLoc);
1774 break;
1775 case UnaryOperator::Deref:
1776 resultType = CheckIndirectionOperand(Input, OpLoc);
1777 break;
1778 case UnaryOperator::Plus:
1779 case UnaryOperator::Minus:
1780 UsualUnaryConversions(Input);
1781 resultType = Input->getType();
1782 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1783 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1784 resultType.getAsString());
1785 break;
1786 case UnaryOperator::Not: // bitwise complement
1787 UsualUnaryConversions(Input);
1788 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001789 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1790 if (!resultType->isIntegerType()) {
1791 if (resultType->isComplexType())
1792 // C99 does not support '~' for complex conjugation.
1793 Diag(OpLoc, diag::ext_integer_complement_complex,
1794 resultType.getAsString());
1795 else
1796 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1797 resultType.getAsString());
1798 }
Chris Lattner4b009652007-07-25 00:24:17 +00001799 break;
1800 case UnaryOperator::LNot: // logical negation
1801 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1802 DefaultFunctionArrayConversion(Input);
1803 resultType = Input->getType();
1804 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1805 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1806 resultType.getAsString());
1807 // LNot always has type int. C99 6.5.3.3p5.
1808 resultType = Context.IntTy;
1809 break;
1810 case UnaryOperator::SizeOf:
1811 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1812 break;
1813 case UnaryOperator::AlignOf:
1814 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1815 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001816 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001817 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001818 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001819 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001820 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001821 resultType = Input->getType();
1822 break;
1823 }
1824 if (resultType.isNull())
1825 return true;
1826 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1827}
1828
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001829/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1830Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001831 SourceLocation LabLoc,
1832 IdentifierInfo *LabelII) {
1833 // Look up the record for this label identifier.
1834 LabelStmt *&LabelDecl = LabelMap[LabelII];
1835
1836 // If we haven't seen this label yet, create a forward reference.
1837 if (LabelDecl == 0)
1838 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1839
1840 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001841 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1842 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001843}
1844
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001845Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001846 SourceLocation RPLoc) { // "({..})"
1847 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1848 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1849 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1850
1851 // FIXME: there are a variety of strange constraints to enforce here, for
1852 // example, it is not possible to goto into a stmt expression apparently.
1853 // More semantic analysis is needed.
1854
1855 // FIXME: the last statement in the compount stmt has its value used. We
1856 // should not warn about it being unused.
1857
1858 // If there are sub stmts in the compound stmt, take the type of the last one
1859 // as the type of the stmtexpr.
1860 QualType Ty = Context.VoidTy;
1861
1862 if (!Compound->body_empty())
1863 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1864 Ty = LastExpr->getType();
1865
1866 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1867}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001868
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001869Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001870 SourceLocation TypeLoc,
1871 TypeTy *argty,
1872 OffsetOfComponent *CompPtr,
1873 unsigned NumComponents,
1874 SourceLocation RPLoc) {
1875 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1876 assert(!ArgTy.isNull() && "Missing type argument!");
1877
1878 // We must have at least one component that refers to the type, and the first
1879 // one is known to be a field designator. Verify that the ArgTy represents
1880 // a struct/union/class.
1881 if (!ArgTy->isRecordType())
1882 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1883
1884 // Otherwise, create a compound literal expression as the base, and
1885 // iteratively process the offsetof designators.
1886 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1887
Chris Lattnerb37522e2007-08-31 21:49:13 +00001888 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1889 // GCC extension, diagnose them.
1890 if (NumComponents != 1)
1891 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1892 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1893
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001894 for (unsigned i = 0; i != NumComponents; ++i) {
1895 const OffsetOfComponent &OC = CompPtr[i];
1896 if (OC.isBrackets) {
1897 // Offset of an array sub-field. TODO: Should we allow vector elements?
1898 const ArrayType *AT = Res->getType()->getAsArrayType();
1899 if (!AT) {
1900 delete Res;
1901 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1902 Res->getType().getAsString());
1903 }
1904
Chris Lattner2af6a802007-08-30 17:59:59 +00001905 // FIXME: C++: Verify that operator[] isn't overloaded.
1906
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001907 // C99 6.5.2.1p1
1908 Expr *Idx = static_cast<Expr*>(OC.U.E);
1909 if (!Idx->getType()->isIntegerType())
1910 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1911 Idx->getSourceRange());
1912
1913 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1914 continue;
1915 }
1916
1917 const RecordType *RC = Res->getType()->getAsRecordType();
1918 if (!RC) {
1919 delete Res;
1920 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1921 Res->getType().getAsString());
1922 }
1923
1924 // Get the decl corresponding to this.
1925 RecordDecl *RD = RC->getDecl();
1926 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1927 if (!MemberDecl)
1928 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1929 OC.U.IdentInfo->getName(),
1930 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001931
1932 // FIXME: C++: Verify that MemberDecl isn't a static field.
1933 // FIXME: Verify that MemberDecl isn't a bitfield.
1934
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001935 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1936 }
1937
1938 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1939 BuiltinLoc);
1940}
1941
1942
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001943Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001944 TypeTy *arg1, TypeTy *arg2,
1945 SourceLocation RPLoc) {
1946 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1947 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1948
1949 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1950
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001951 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001952}
1953
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001954Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00001955 ExprTy *expr1, ExprTy *expr2,
1956 SourceLocation RPLoc) {
1957 Expr *CondExpr = static_cast<Expr*>(cond);
1958 Expr *LHSExpr = static_cast<Expr*>(expr1);
1959 Expr *RHSExpr = static_cast<Expr*>(expr2);
1960
1961 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1962
1963 // The conditional expression is required to be a constant expression.
1964 llvm::APSInt condEval(32);
1965 SourceLocation ExpLoc;
1966 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1967 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1968 CondExpr->getSourceRange());
1969
1970 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1971 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1972 RHSExpr->getType();
1973 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1974}
1975
Anders Carlsson36760332007-10-15 20:28:48 +00001976Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
1977 ExprTy *expr, TypeTy *type,
1978 SourceLocation RPLoc)
1979{
1980 Expr *E = static_cast<Expr*>(expr);
1981 QualType T = QualType::getFromOpaquePtr(type);
1982
1983 InitBuiltinVaListType();
1984
1985 Sema::AssignmentCheckResult result;
1986
1987 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
1988 E->getType());
1989 if (result != Compatible)
1990 return Diag(E->getLocStart(),
1991 diag::err_first_argument_to_va_arg_not_of_type_va_list,
1992 E->getType().getAsString(),
1993 E->getSourceRange());
1994
1995 // FIXME: Warn if a non-POD type is passed in.
1996
1997 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
1998}
1999
Anders Carlssona66cad42007-08-21 17:43:55 +00002000// TODO: Move this to SemaObjC.cpp
Steve Naroff0add5d22007-11-03 11:27:19 +00002001Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation AtLoc,
2002 ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00002003 StringLiteral* S = static_cast<StringLiteral *>(string);
2004
2005 if (CheckBuiltinCFStringArgument(S))
2006 return true;
2007
Steve Narofff2e30312007-10-15 23:35:17 +00002008 if (Context.getObjcConstantStringInterface().isNull()) {
2009 // Initialize the constant string interface lazily. This assumes
2010 // the NSConstantString interface is seen in this translation unit.
2011 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
2012 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
2013 SourceLocation(), TUScope);
Steve Naroff134c3502007-10-16 00:00:18 +00002014 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff96f136d2007-10-18 23:53:51 +00002015 if (!strIFace)
2016 return Diag(S->getLocStart(), diag::err_undef_interface,
2017 NSIdent->getName());
Steve Naroff134c3502007-10-16 00:00:18 +00002018 Context.setObjcConstantStringInterface(strIFace);
Steve Narofff2e30312007-10-15 23:35:17 +00002019 }
2020 QualType t = Context.getObjcConstantStringInterface();
Anders Carlssona66cad42007-08-21 17:43:55 +00002021 t = Context.getPointerType(t);
Steve Naroff0add5d22007-11-03 11:27:19 +00002022 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlssona66cad42007-08-21 17:43:55 +00002023}
Anders Carlsson8be1d402007-08-22 15:14:15 +00002024
2025Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattnercfd61c82007-10-16 22:51:17 +00002026 SourceLocation EncodeLoc,
Anders Carlsson8be1d402007-08-22 15:14:15 +00002027 SourceLocation LParenLoc,
2028 TypeTy *Ty,
2029 SourceLocation RParenLoc) {
2030 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2031
2032 QualType t = Context.getPointerType(Context.CharTy);
2033 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2034}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002035
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002036Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2037 SourceLocation AtLoc,
Fariborz Jahanian957448a2007-10-16 23:21:02 +00002038 SourceLocation SelLoc,
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002039 SourceLocation LParenLoc,
2040 SourceLocation RParenLoc) {
Steve Naroffae84af82007-10-31 18:42:27 +00002041 QualType t = Context.getObjcSelType();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002042 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2043}
2044
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002045Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2046 SourceLocation AtLoc,
2047 SourceLocation ProtoLoc,
2048 SourceLocation LParenLoc,
2049 SourceLocation RParenLoc) {
2050 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2051 if (!PDecl) {
2052 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2053 return true;
2054 }
2055
2056 QualType t = GetObjcProtoType(AtLoc);
Fariborz Jahanian20b40e42007-10-18 22:59:23 +00002057 if (t.isNull())
2058 return true;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002059 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2060}
Steve Naroff52664182007-10-16 23:12:48 +00002061
2062bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2063 ObjcMethodDecl *Method) {
2064 bool anyIncompatibleArgs = false;
2065
2066 for (unsigned i = 0; i < NumArgs; i++) {
2067 Expr *argExpr = Args[i];
2068 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2069
2070 QualType lhsType = Method->getParamDecl(i)->getType();
2071 QualType rhsType = argExpr->getType();
2072
2073 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2074 if (const ArrayType *ary = lhsType->getAsArrayType())
2075 lhsType = Context.getPointerType(ary->getElementType());
2076 else if (lhsType->isFunctionType())
2077 lhsType = Context.getPointerType(lhsType);
2078
2079 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2080 argExpr);
2081 if (Args[i] != argExpr) // The expression was converted.
2082 Args[i] = argExpr; // Make sure we store the converted expression.
2083 SourceLocation l = argExpr->getLocStart();
2084
2085 // decode the result (notice that AST's are still created for extensions).
2086 switch (result) {
2087 case Compatible:
2088 break;
2089 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00002090 Diag(l, diag::ext_typecheck_sending_pointer_int,
2091 lhsType.getAsString(), rhsType.getAsString(),
2092 argExpr->getSourceRange());
Steve Naroff52664182007-10-16 23:12:48 +00002093 break;
2094 case IntFromPointer:
2095 Diag(l, diag::ext_typecheck_sending_pointer_int,
2096 lhsType.getAsString(), rhsType.getAsString(),
2097 argExpr->getSourceRange());
2098 break;
2099 case IncompatiblePointer:
2100 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2101 rhsType.getAsString(), lhsType.getAsString(),
2102 argExpr->getSourceRange());
2103 break;
2104 case CompatiblePointerDiscardsQualifiers:
2105 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2106 rhsType.getAsString(), lhsType.getAsString(),
2107 argExpr->getSourceRange());
2108 break;
2109 case Incompatible:
2110 Diag(l, diag::err_typecheck_sending_incompatible,
2111 rhsType.getAsString(), lhsType.getAsString(),
2112 argExpr->getSourceRange());
2113 anyIncompatibleArgs = true;
2114 }
2115 }
2116 return anyIncompatibleArgs;
2117}
2118
Steve Naroff4ed9d662007-09-27 14:38:14 +00002119// ActOnClassMessage - used for both unary and keyword messages.
2120// ArgExprs is optional - if it is present, the number of expressions
2121// is obtained from Sel.getNumArgs().
2122Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002123 Scope *S,
Steve Narofffa465d12007-10-02 20:01:56 +00002124 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002125 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002126{
Steve Narofffa465d12007-10-02 20:01:56 +00002127 assert(receiverName && "missing receiver class name");
Steve Naroffc39ca262007-09-18 23:55:05 +00002128
Steve Naroff52664182007-10-16 23:12:48 +00002129 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002130 ObjcInterfaceDecl* ClassDecl = 0;
2131 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2132 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahanian342f3602007-11-12 20:20:37 +00002133 if (ClassDecl && CurMethodDecl->isInstance()) {
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002134 IdentifierInfo &II = Context.Idents.get("self");
2135 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II,
2136 false);
2137 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2138 superTy = Context.getPointerType(superTy);
2139 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2140 SourceLocation(), ReceiverExpr.Val);
2141
2142 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002143 Args, NumArgs);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002144 }
2145 // class method
2146 if (ClassDecl)
2147 receiverName = ClassDecl->getIdentifier();
2148 }
2149 else
2150 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Narofffa465d12007-10-02 20:01:56 +00002151 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002152 QualType returnType;
Steve Naroff75c4baf2007-11-05 15:27:52 +00002153
2154 // Before we give up, check if the selector is an instance method.
2155 if (!Method)
2156 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002157 if (!Method) {
2158 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2159 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002160 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002161 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002162 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002163 if (Sel.getNumArgs()) {
2164 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2165 return true;
2166 }
Steve Naroff7e461452007-10-16 20:39:36 +00002167 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002168 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff9f176d12007-11-15 13:05:42 +00002169 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002170}
2171
Steve Naroff4ed9d662007-09-27 14:38:14 +00002172// ActOnInstanceMessage - used for both unary and keyword messages.
2173// ArgExprs is optional - if it is present, the number of expressions
2174// is obtained from Sel.getNumArgs().
2175Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroff6cb1d362007-09-28 22:22:11 +00002176 ExprTy *receiver, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002177 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff4ed9d662007-09-27 14:38:14 +00002178{
Steve Naroffc39ca262007-09-18 23:55:05 +00002179 assert(receiver && "missing receiver expression");
2180
Steve Naroff52664182007-10-16 23:12:48 +00002181 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroffc39ca262007-09-18 23:55:05 +00002182 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Narofffa465d12007-10-02 20:01:56 +00002183 QualType receiverType = RExpr->getType();
Steve Naroffee1de132007-10-10 21:53:07 +00002184 QualType returnType;
Steve Naroff1e1c3912007-11-03 16:37:59 +00002185 ObjcMethodDecl *Method;
Steve Naroffee1de132007-10-10 21:53:07 +00002186
Steve Naroff0091d142007-11-11 17:52:25 +00002187 if (receiverType == Context.getObjcIdType() ||
2188 receiverType == Context.getObjcClassType()) {
Steve Naroff1e1c3912007-11-03 16:37:59 +00002189 Method = InstanceMethodPool[Sel].Method;
Steve Naroffd0cfcd02007-11-13 04:10:18 +00002190 // If we didn't find an public method, look for a private one.
2191 if (!Method && CurMethodDecl) {
2192 NamedDecl *impCxt = CurMethodDecl->getMethodContext();
2193 if (ObjcImplementationDecl *IMD =
2194 dyn_cast<ObjcImplementationDecl>(impCxt)) {
2195 if (receiverType == Context.getObjcIdType())
2196 Method = IMD->lookupInstanceMethod(Sel);
2197 else
2198 Method = IMD->lookupClassMethod(Sel);
2199 } else if (ObjcCategoryImplDecl *CID =
2200 dyn_cast<ObjcCategoryImplDecl>(impCxt)) {
2201 if (receiverType == Context.getObjcIdType())
2202 Method = CID->lookupInstanceMethod(Sel);
2203 else
2204 Method = CID->lookupClassMethod(Sel);
2205 }
2206 }
Steve Naroff7e461452007-10-16 20:39:36 +00002207 if (!Method) {
2208 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2209 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002210 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002211 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002212 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002213 if (Sel.getNumArgs())
2214 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2215 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002216 }
Steve Naroffee1de132007-10-10 21:53:07 +00002217 } else {
Chris Lattner71c01112007-10-10 23:42:28 +00002218 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2219 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroffee1de132007-10-10 21:53:07 +00002220 while (receiverType->isPointerType()) {
Chris Lattner71c01112007-10-10 23:42:28 +00002221 PointerType *pointerType =
2222 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroffee1de132007-10-10 21:53:07 +00002223 receiverType = pointerType->getPointeeType();
2224 }
Chris Lattner71c01112007-10-10 23:42:28 +00002225 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2226 "bad receiver type");
Steve Naroffee1de132007-10-10 21:53:07 +00002227 ObjcInterfaceDecl* ClassDecl = static_cast<ObjcInterfaceType*>(
2228 receiverType.getTypePtr())->getDecl();
Steve Naroff7e461452007-10-16 20:39:36 +00002229 // FIXME: consider using InstanceMethodPool, since it will be faster
2230 // than the following method (which can do *many* linear searches). The
2231 // idea is to add class info to InstanceMethodPool...
Steve Naroff1e1c3912007-11-03 16:37:59 +00002232 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002233 if (!Method) {
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002234 // If we have an implementation in scope, check "private" methods.
2235 if (ObjcImplementationDecl *ImpDecl =
2236 ObjcImplementations[ClassDecl->getIdentifier()])
2237 Method = ImpDecl->lookupInstanceMethod(Sel);
2238 }
2239 if (!Method) {
Steve Naroff7e461452007-10-16 20:39:36 +00002240 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2241 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002242 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002243 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002244 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002245 if (Sel.getNumArgs())
2246 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2247 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002248 }
Steve Narofffa465d12007-10-02 20:01:56 +00002249 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002250 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002251 ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002252}