blob: 6c3b06e0155f61669fb4c59bdd07dcfdd3f44bca [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"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
Steve Narofffa465d12007-10-02 20:01:56 +000017#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000019#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
26#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000027#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29
Steve Naroff87d58b42007-09-16 03:34:24 +000030/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000031/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
32/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
33/// multiple tokens. However, the common case is that StringToks points to one
34/// string.
35///
36Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000037Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000038 assert(NumStringToks && "Must have at least one string!");
39
40 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
41 if (Literal.hadError)
42 return ExprResult(true);
43
44 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
45 for (unsigned i = 0; i != NumStringToks; ++i)
46 StringTokLocs.push_back(StringToks[i].getLocation());
47
48 // FIXME: handle wchar_t
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000049 QualType t;
50
51 if (Literal.Pascal)
52 t = Context.getPointerType(Context.UnsignedCharTy);
53 else
54 t = Context.getPointerType(Context.CharTy);
55
56 if (Literal.Pascal && Literal.GetStringLength() > 256)
57 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
58 SourceRange(StringToks[0].getLocation(),
59 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000060
61 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
62 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000063 Literal.AnyWide, t,
64 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000065 StringToks[NumStringToks-1].getLocation());
66}
67
68
Steve Naroff0acc9c92007-09-15 18:49:24 +000069/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000070/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
71/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000072Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000073 IdentifierInfo &II,
74 bool HasTrailingLParen) {
75 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000076 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000077 if (D == 0) {
78 // Otherwise, this could be an implicitly declared function reference (legal
79 // in C90, extension in C99).
80 if (HasTrailingLParen &&
81 // Not in C++.
82 !getLangOptions().CPlusPlus)
83 D = ImplicitlyDefineFunction(Loc, II, S);
84 else {
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000085 if (CurMethodDecl) {
86 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
87 ObjcInterfaceDecl *clsDeclared;
Steve Naroff6b759ce2007-11-15 02:58:25 +000088 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
89 IdentifierInfo &II = Context.Idents.get("self");
90 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
91 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
92 static_cast<Expr*>(SelfExpr.Val), true, true);
93 }
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000094 }
Chris Lattner4b009652007-07-25 00:24:17 +000095 // If this name wasn't predeclared and if this is not a function call,
96 // diagnose the problem.
97 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
98 }
99 }
Steve Naroff91b03f72007-08-28 03:03:08 +0000100 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +0000101 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000102 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000103 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000104 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000105 }
Chris Lattner4b009652007-07-25 00:24:17 +0000106 if (isa<TypedefDecl>(D))
107 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
108
109 assert(0 && "Invalid decl");
110 abort();
111}
112
Steve Naroff87d58b42007-09-16 03:34:24 +0000113Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000114 tok::TokenKind Kind) {
115 PreDefinedExpr::IdentType IT;
116
117 switch (Kind) {
118 default:
119 assert(0 && "Unknown simple primary expr!");
120 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
121 IT = PreDefinedExpr::Func;
122 break;
123 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
124 IT = PreDefinedExpr::Function;
125 break;
126 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
127 IT = PreDefinedExpr::PrettyFunction;
128 break;
129 }
130
131 // Pre-defined identifiers are always of type char *.
132 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
133}
134
Steve Naroff87d58b42007-09-16 03:34:24 +0000135Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000136 llvm::SmallString<16> CharBuffer;
137 CharBuffer.resize(Tok.getLength());
138 const char *ThisTokBegin = &CharBuffer[0];
139 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
140
141 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
142 Tok.getLocation(), PP);
143 if (Literal.hadError())
144 return ExprResult(true);
145 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
146 Tok.getLocation());
147}
148
Steve Naroff87d58b42007-09-16 03:34:24 +0000149Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000150 // fast path for a single digit (which is quite common). A single digit
151 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
152 if (Tok.getLength() == 1) {
153 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
154
Chris Lattner3496d522007-09-04 02:45:27 +0000155 unsigned IntSize = static_cast<unsigned>(
156 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000157 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
158 Context.IntTy,
159 Tok.getLocation()));
160 }
161 llvm::SmallString<512> IntegerBuffer;
162 IntegerBuffer.resize(Tok.getLength());
163 const char *ThisTokBegin = &IntegerBuffer[0];
164
165 // Get the spelling of the token, which eliminates trigraphs, etc.
166 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
167 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
168 Tok.getLocation(), PP);
169 if (Literal.hadError)
170 return ExprResult(true);
171
Chris Lattner1de66eb2007-08-26 03:42:43 +0000172 Expr *Res;
173
174 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000175 QualType Ty;
176 const llvm::fltSemantics *Format;
177 uint64_t Size; unsigned Align;
178
179 if (Literal.isFloat) {
180 Ty = Context.FloatTy;
181 Context.Target.getFloatInfo(Size, Align, Format, Tok.getLocation());
182 } else if (Literal.isLong) {
183 Ty = Context.LongDoubleTy;
184 Context.Target.getLongDoubleInfo(Size, Align, Format, Tok.getLocation());
185 } else {
186 Ty = Context.DoubleTy;
187 Context.Target.getDoubleInfo(Size, Align, Format, Tok.getLocation());
188 }
189
190 Res = new FloatingLiteral(Literal.GetFloatValue(*Format), Ty,
191 Tok.getLocation());
Chris Lattner1de66eb2007-08-26 03:42:43 +0000192 } else if (!Literal.isIntegerLiteral()) {
193 return ExprResult(true);
194 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000195 QualType t;
196
Neil Booth7421e9c2007-08-29 22:00:19 +0000197 // long long is a C99 feature.
198 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000199 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000200 Diag(Tok.getLocation(), diag::ext_longlong);
201
Chris Lattner4b009652007-07-25 00:24:17 +0000202 // Get the value in the widest-possible width.
203 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
204
205 if (Literal.GetIntegerValue(ResultVal)) {
206 // If this value didn't fit into uintmax_t, warn and force to ull.
207 Diag(Tok.getLocation(), diag::warn_integer_too_large);
208 t = Context.UnsignedLongLongTy;
209 assert(Context.getTypeSize(t, Tok.getLocation()) ==
210 ResultVal.getBitWidth() && "long long is not intmax_t?");
211 } else {
212 // If this value fits into a ULL, try to figure out what else it fits into
213 // according to the rules of C99 6.4.4.1p5.
214
215 // Octal, Hexadecimal, and integers with a U suffix are allowed to
216 // be an unsigned int.
217 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
218
219 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000220 if (!Literal.isLong && !Literal.isLongLong) {
221 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000222 unsigned IntSize = static_cast<unsigned>(
223 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000224 // Does it fit in a unsigned int?
225 if (ResultVal.isIntN(IntSize)) {
226 // Does it fit in a signed int?
227 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
228 t = Context.IntTy;
229 else if (AllowUnsigned)
230 t = Context.UnsignedIntTy;
231 }
232
233 if (!t.isNull())
234 ResultVal.trunc(IntSize);
235 }
236
237 // Are long/unsigned long possibilities?
238 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000239 unsigned LongSize = static_cast<unsigned>(
240 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000241
242 // Does it fit in a unsigned long?
243 if (ResultVal.isIntN(LongSize)) {
244 // Does it fit in a signed long?
245 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
246 t = Context.LongTy;
247 else if (AllowUnsigned)
248 t = Context.UnsignedLongTy;
249 }
250 if (!t.isNull())
251 ResultVal.trunc(LongSize);
252 }
253
254 // Finally, check long long if needed.
255 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000256 unsigned LongLongSize = static_cast<unsigned>(
257 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000258
259 // Does it fit in a unsigned long long?
260 if (ResultVal.isIntN(LongLongSize)) {
261 // Does it fit in a signed long long?
262 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
263 t = Context.LongLongTy;
264 else if (AllowUnsigned)
265 t = Context.UnsignedLongLongTy;
266 }
267 }
268
269 // If we still couldn't decide a type, we probably have something that
270 // does not fit in a signed long long, but has no U suffix.
271 if (t.isNull()) {
272 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
273 t = Context.UnsignedLongLongTy;
274 }
275 }
276
Chris Lattner1de66eb2007-08-26 03:42:43 +0000277 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000278 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000279
280 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
281 if (Literal.isImaginary)
282 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
283
284 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000285}
286
Steve Naroff87d58b42007-09-16 03:34:24 +0000287Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000288 ExprTy *Val) {
289 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000290 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000291 return new ParenExpr(L, R, e);
292}
293
294/// The UsualUnaryConversions() function is *not* called by this routine.
295/// See C99 6.3.2.1p[2-4] for more details.
296QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
297 SourceLocation OpLoc, bool isSizeof) {
298 // C99 6.5.3.4p1:
299 if (isa<FunctionType>(exprType) && isSizeof)
300 // alignof(function) is allowed.
301 Diag(OpLoc, diag::ext_sizeof_function_type);
302 else if (exprType->isVoidType())
303 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
304 else if (exprType->isIncompleteType()) {
305 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
306 diag::err_alignof_incomplete_type,
307 exprType.getAsString());
308 return QualType(); // error
309 }
310 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
311 return Context.getSizeType();
312}
313
314Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000315ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000316 SourceLocation LPLoc, TypeTy *Ty,
317 SourceLocation RPLoc) {
318 // If error parsing type, ignore.
319 if (Ty == 0) return true;
320
321 // Verify that this is a valid expression.
322 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
323
324 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
325
326 if (resultType.isNull())
327 return true;
328 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
329}
330
Chris Lattner5110ad52007-08-24 21:41:10 +0000331QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000332 DefaultFunctionArrayConversion(V);
333
Chris Lattnera16e42d2007-08-26 05:39:26 +0000334 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000335 if (const ComplexType *CT = V->getType()->getAsComplexType())
336 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000337
338 // Otherwise they pass through real integer and floating point types here.
339 if (V->getType()->isArithmeticType())
340 return V->getType();
341
342 // Reject anything else.
343 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
344 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000345}
346
347
Chris Lattner4b009652007-07-25 00:24:17 +0000348
Steve Naroff87d58b42007-09-16 03:34:24 +0000349Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000350 tok::TokenKind Kind,
351 ExprTy *Input) {
352 UnaryOperator::Opcode Opc;
353 switch (Kind) {
354 default: assert(0 && "Unknown unary op!");
355 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
356 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
357 }
358 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
359 if (result.isNull())
360 return true;
361 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
362}
363
364Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000365ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000366 ExprTy *Idx, SourceLocation RLoc) {
367 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
368
369 // Perform default conversions.
370 DefaultFunctionArrayConversion(LHSExp);
371 DefaultFunctionArrayConversion(RHSExp);
372
373 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
374
375 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000376 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000377 // in the subscript position. As a result, we need to derive the array base
378 // and index from the expression types.
379 Expr *BaseExpr, *IndexExpr;
380 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000381 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000382 BaseExpr = LHSExp;
383 IndexExpr = RHSExp;
384 // FIXME: need to deal with const...
385 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000386 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000387 // Handle the uncommon case of "123[Ptr]".
388 BaseExpr = RHSExp;
389 IndexExpr = LHSExp;
390 // FIXME: need to deal with const...
391 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000392 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
393 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000394 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000395
396 // Component access limited to variables (reject vec4.rg[1]).
397 if (!isa<DeclRefExpr>(BaseExpr))
398 return Diag(LLoc, diag::err_ocuvector_component_access,
399 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000400 // FIXME: need to deal with const...
401 ResultType = VTy->getElementType();
402 } else {
403 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
404 RHSExp->getSourceRange());
405 }
406 // C99 6.5.2.1p1
407 if (!IndexExpr->getType()->isIntegerType())
408 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
409 IndexExpr->getSourceRange());
410
411 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
412 // the following check catches trying to index a pointer to a function (e.g.
413 // void (*)(int)). Functions are not objects in C99.
414 if (!ResultType->isObjectType())
415 return Diag(BaseExpr->getLocStart(),
416 diag::err_typecheck_subscript_not_object,
417 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
418
419 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
420}
421
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000422QualType Sema::
423CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
424 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000425 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000426
427 // The vector accessor can't exceed the number of elements.
428 const char *compStr = CompName.getName();
429 if (strlen(compStr) > vecType->getNumElements()) {
430 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
431 baseType.getAsString(), SourceRange(CompLoc));
432 return QualType();
433 }
434 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000435 if (vecType->getPointAccessorIdx(*compStr) != -1) {
436 do
437 compStr++;
438 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
439 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
440 do
441 compStr++;
442 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
443 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
444 do
445 compStr++;
446 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
447 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000448
449 if (*compStr) {
450 // We didn't get to the end of the string. This means the component names
451 // didn't come from the same set *or* we encountered an illegal name.
452 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
453 std::string(compStr,compStr+1), SourceRange(CompLoc));
454 return QualType();
455 }
456 // Each component accessor can't exceed the vector type.
457 compStr = CompName.getName();
458 while (*compStr) {
459 if (vecType->isAccessorWithinNumElements(*compStr))
460 compStr++;
461 else
462 break;
463 }
464 if (*compStr) {
465 // We didn't get to the end of the string. This means a component accessor
466 // exceeds the number of elements in the vector.
467 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
468 baseType.getAsString(), SourceRange(CompLoc));
469 return QualType();
470 }
471 // The component accessor looks fine - now we need to compute the actual type.
472 // The vector type is implied by the component accessor. For example,
473 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
474 unsigned CompSize = strlen(CompName.getName());
475 if (CompSize == 1)
476 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000477
478 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
479 // Now look up the TypeDefDecl from the vector type. Without this,
480 // diagostics look bad. We want OCU vector types to appear built-in.
481 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
482 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
483 return Context.getTypedefType(OCUVectorDecls[i]);
484 }
485 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000486}
487
Chris Lattner4b009652007-07-25 00:24:17 +0000488Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000489ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000490 tok::TokenKind OpKind, SourceLocation MemberLoc,
491 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000492 Expr *BaseExpr = static_cast<Expr *>(Base);
493 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000494
Steve Naroff2cb66382007-07-26 03:11:44 +0000495 QualType BaseType = BaseExpr->getType();
496 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000497
Chris Lattner4b009652007-07-25 00:24:17 +0000498 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000499 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000500 BaseType = PT->getPointeeType();
501 else
502 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
503 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000504 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000505 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000506 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000507 RecordDecl *RDecl = RTy->getDecl();
508 if (RTy->isIncompleteType())
509 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
510 BaseExpr->getSourceRange());
511 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000512 FieldDecl *MemberDecl = RDecl->getMember(&Member);
513 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000514 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
515 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000516 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
517 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000518 // Component access limited to variables (reject vec4.rg.g).
519 if (!isa<DeclRefExpr>(BaseExpr))
520 return Diag(OpLoc, diag::err_ocuvector_component_access,
521 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000522 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
523 if (ret.isNull())
524 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000525 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000526 } else if (BaseType->isObjcInterfaceType()) {
527 ObjcInterfaceDecl *IFace;
528 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
529 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
530 else
531 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)
532 ->getInterfaceType()->getDecl();
533 ObjcInterfaceDecl *clsDeclared;
534 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
535 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
536 OpKind==tok::arrow);
537 }
538 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
539 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000540}
541
Steve Naroff87d58b42007-09-16 03:34:24 +0000542/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000543/// This provides the location of the left/right parens and a list of comma
544/// locations.
545Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000546ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000547 ExprTy **args, unsigned NumArgsInCall,
548 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
549 Expr *Fn = static_cast<Expr *>(fn);
550 Expr **Args = reinterpret_cast<Expr**>(args);
551 assert(Fn && "no function call expression");
552
553 UsualUnaryConversions(Fn);
554 QualType funcType = Fn->getType();
555
556 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
557 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000558 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000559 if (PT == 0)
560 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
561 SourceRange(Fn->getLocStart(), RParenLoc));
562
Chris Lattner71225142007-07-31 21:27:01 +0000563 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000564 if (funcT == 0)
565 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
566 SourceRange(Fn->getLocStart(), RParenLoc));
567
568 // If a prototype isn't declared, the parser implicitly defines a func decl
569 QualType resultType = funcT->getResultType();
570
571 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
572 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
573 // assignment, to the types of the corresponding parameter, ...
574
575 unsigned NumArgsInProto = proto->getNumArgs();
576 unsigned NumArgsToCheck = NumArgsInCall;
577
578 if (NumArgsInCall < NumArgsInProto)
579 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
580 Fn->getSourceRange());
581 else if (NumArgsInCall > NumArgsInProto) {
582 if (!proto->isVariadic()) {
583 Diag(Args[NumArgsInProto]->getLocStart(),
584 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
585 SourceRange(Args[NumArgsInProto]->getLocStart(),
586 Args[NumArgsInCall-1]->getLocEnd()));
587 }
588 NumArgsToCheck = NumArgsInProto;
589 }
590 // Continue to check argument types (even if we have too few/many args).
591 for (unsigned i = 0; i < NumArgsToCheck; i++) {
592 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000593 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000594
595 QualType lhsType = proto->getArgType(i);
596 QualType rhsType = argExpr->getType();
597
Steve Naroff75644062007-07-25 20:45:33 +0000598 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000599 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000600 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000601 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000602 lhsType = Context.getPointerType(lhsType);
603
604 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
605 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000606 if (Args[i] != argExpr) // The expression was converted.
607 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000608 SourceLocation l = argExpr->getLocStart();
609
610 // decode the result (notice that AST's are still created for extensions).
611 switch (result) {
612 case Compatible:
613 break;
614 case PointerFromInt:
615 // check for null pointer constant (C99 6.3.2.3p3)
616 if (!argExpr->isNullPointerConstant(Context)) {
617 Diag(l, diag::ext_typecheck_passing_pointer_int,
618 lhsType.getAsString(), rhsType.getAsString(),
619 Fn->getSourceRange(), argExpr->getSourceRange());
620 }
621 break;
622 case IntFromPointer:
623 Diag(l, diag::ext_typecheck_passing_pointer_int,
624 lhsType.getAsString(), rhsType.getAsString(),
625 Fn->getSourceRange(), argExpr->getSourceRange());
626 break;
627 case IncompatiblePointer:
628 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
629 rhsType.getAsString(), lhsType.getAsString(),
630 Fn->getSourceRange(), argExpr->getSourceRange());
631 break;
632 case CompatiblePointerDiscardsQualifiers:
633 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
634 rhsType.getAsString(), lhsType.getAsString(),
635 Fn->getSourceRange(), argExpr->getSourceRange());
636 break;
637 case Incompatible:
638 return Diag(l, diag::err_typecheck_passing_incompatible,
639 rhsType.getAsString(), lhsType.getAsString(),
640 Fn->getSourceRange(), argExpr->getSourceRange());
641 }
642 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000643 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
644 // Promote the arguments (C99 6.5.2.2p7).
645 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
646 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000647 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000648
649 DefaultArgumentPromotion(argExpr);
650 if (Args[i] != argExpr) // The expression was converted.
651 Args[i] = argExpr; // Make sure we store the converted expression.
652 }
653 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
654 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000655 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000656 }
657 } else if (isa<FunctionTypeNoProto>(funcT)) {
658 // Promote the arguments (C99 6.5.2.2p6).
659 for (unsigned i = 0; i < NumArgsInCall; i++) {
660 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000661 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000662
663 DefaultArgumentPromotion(argExpr);
664 if (Args[i] != argExpr) // The expression was converted.
665 Args[i] = argExpr; // Make sure we store the converted expression.
666 }
Chris Lattner4b009652007-07-25 00:24:17 +0000667 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000668 // Do special checking on direct calls to functions.
669 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
670 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
671 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000672 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
673 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000674 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000675
Chris Lattner4b009652007-07-25 00:24:17 +0000676 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
677}
678
679Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000680ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000681 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000682 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000683 QualType literalType = QualType::getFromOpaquePtr(Ty);
684 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000685 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000686 Expr *literalExpr = static_cast<Expr*>(InitExpr);
687
688 // FIXME: add semantic analysis (C99 6.5.2.5).
689 return new CompoundLiteralExpr(literalType, literalExpr);
690}
691
692Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000693ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000694 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000695 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000696
Steve Naroff0acc9c92007-09-15 18:49:24 +0000697 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000698 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000699
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000700 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
701 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
702 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000703}
704
705Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000706ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000707 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000708 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000709
710 Expr *castExpr = static_cast<Expr*>(Op);
711 QualType castType = QualType::getFromOpaquePtr(Ty);
712
Steve Naroff68adb482007-08-31 00:32:44 +0000713 UsualUnaryConversions(castExpr);
714
Chris Lattner4b009652007-07-25 00:24:17 +0000715 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
716 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000717 if (!castType->isVoidType()) { // Cast to void allows any expr type.
718 if (!castType->isScalarType())
719 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
720 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
721 if (!castExpr->getType()->isScalarType()) {
722 return Diag(castExpr->getLocStart(),
723 diag::err_typecheck_expect_scalar_operand,
724 castExpr->getType().getAsString(),castExpr->getSourceRange());
725 }
Chris Lattner4b009652007-07-25 00:24:17 +0000726 }
727 return new CastExpr(castType, castExpr, LParenLoc);
728}
729
Steve Naroff144667e2007-10-18 05:13:08 +0000730// promoteExprToType - a helper function to ensure we create exactly one
731// ImplicitCastExpr.
732static void promoteExprToType(Expr *&expr, QualType type) {
733 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
734 impCast->setType(type);
735 else
736 expr = new ImplicitCastExpr(type, expr);
737 return;
738}
739
Chris Lattner4b009652007-07-25 00:24:17 +0000740inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
741 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
742 UsualUnaryConversions(cond);
743 UsualUnaryConversions(lex);
744 UsualUnaryConversions(rex);
745 QualType condT = cond->getType();
746 QualType lexT = lex->getType();
747 QualType rexT = rex->getType();
748
749 // first, check the condition.
750 if (!condT->isScalarType()) { // C99 6.5.15p2
751 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
752 condT.getAsString());
753 return QualType();
754 }
755 // now check the two expressions.
756 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
757 UsualArithmeticConversions(lex, rex);
758 return lex->getType();
759 }
Chris Lattner71225142007-07-31 21:27:01 +0000760 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
761 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
762
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000763 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
Chris Lattner71225142007-07-31 21:27:01 +0000764 return lexT;
765
Chris Lattner4b009652007-07-25 00:24:17 +0000766 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
767 lexT.getAsString(), rexT.getAsString(),
768 lex->getSourceRange(), rex->getSourceRange());
769 return QualType();
770 }
771 }
772 // C99 6.5.15p3
Steve Naroff144667e2007-10-18 05:13:08 +0000773 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
774 promoteExprToType(rex, lexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000775 return lexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000776 }
777 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
778 promoteExprToType(lex, rexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000779 return rexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000780 }
Chris Lattner71225142007-07-31 21:27:01 +0000781 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
782 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
783 // get the "pointed to" types
784 QualType lhptee = LHSPT->getPointeeType();
785 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000786
Chris Lattner71225142007-07-31 21:27:01 +0000787 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
788 if (lhptee->isVoidType() &&
789 (rhptee->isObjectType() || rhptee->isIncompleteType()))
790 return lexT;
791 if (rhptee->isVoidType() &&
792 (lhptee->isObjectType() || lhptee->isIncompleteType()))
793 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000794
Steve Naroff85f0dc52007-10-15 20:41:53 +0000795 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
796 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000797 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
798 lexT.getAsString(), rexT.getAsString(),
799 lex->getSourceRange(), rex->getSourceRange());
800 return lexT; // FIXME: this is an _ext - is this return o.k?
801 }
802 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000803 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
804 // differently qualified versions of compatible types, the result type is
805 // a pointer to an appropriately qualified version of the *composite*
806 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000807 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000808 }
Chris Lattner4b009652007-07-25 00:24:17 +0000809 }
Chris Lattner71225142007-07-31 21:27:01 +0000810
Chris Lattner4b009652007-07-25 00:24:17 +0000811 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
812 return lexT;
813
814 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
815 lexT.getAsString(), rexT.getAsString(),
816 lex->getSourceRange(), rex->getSourceRange());
817 return QualType();
818}
819
Steve Naroff87d58b42007-09-16 03:34:24 +0000820/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000821/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000822Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000823 SourceLocation ColonLoc,
824 ExprTy *Cond, ExprTy *LHS,
825 ExprTy *RHS) {
826 Expr *CondExpr = (Expr *) Cond;
827 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
828 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
829 RHSExpr, QuestionLoc);
830 if (result.isNull())
831 return true;
832 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
833}
834
Steve Naroffdb65e052007-08-28 23:30:39 +0000835/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
836/// do not have a prototype. Integer promotions are performed on each
837/// argument, and arguments that have type float are promoted to double.
838void Sema::DefaultArgumentPromotion(Expr *&expr) {
839 QualType t = expr->getType();
840 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
841
842 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
843 promoteExprToType(expr, Context.IntTy);
844 if (t == Context.FloatTy)
845 promoteExprToType(expr, Context.DoubleTy);
846}
847
Chris Lattner4b009652007-07-25 00:24:17 +0000848/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
849void Sema::DefaultFunctionArrayConversion(Expr *&e) {
850 QualType t = e->getType();
851 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
852
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000853 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000854 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
855 t = e->getType();
856 }
857 if (t->isFunctionType())
858 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000859 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000860 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
861}
862
863/// UsualUnaryConversion - Performs various conversions that are common to most
864/// operators (C99 6.3). The conversions of array and function types are
865/// sometimes surpressed. For example, the array->pointer conversion doesn't
866/// apply if the array is an argument to the sizeof or address (&) operators.
867/// In these instances, this routine should *not* be called.
868void Sema::UsualUnaryConversions(Expr *&expr) {
869 QualType t = expr->getType();
870 assert(!t.isNull() && "UsualUnaryConversions - missing type");
871
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000872 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000873 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
874 t = expr->getType();
875 }
876 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
877 promoteExprToType(expr, Context.IntTy);
878 else
879 DefaultFunctionArrayConversion(expr);
880}
881
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000882/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000883/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
884/// routine returns the first non-arithmetic type found. The client is
885/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000886QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
887 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000888 if (!isCompAssign) {
889 UsualUnaryConversions(lhsExpr);
890 UsualUnaryConversions(rhsExpr);
891 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000892 // For conversion purposes, we ignore any qualifiers.
893 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000894 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
895 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000896
897 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000898 if (lhs == rhs)
899 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000900
901 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
902 // The caller can deal with this (e.g. pointer + int).
903 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000904 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000905
906 // At this point, we have two different arithmetic types.
907
908 // Handle complex types first (C99 6.3.1.8p1).
909 if (lhs->isComplexType() || rhs->isComplexType()) {
910 // if we have an integer operand, the result is the complex type.
911 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000912 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
913 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000914 }
915 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000916 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
917 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000918 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000919 // This handles complex/complex, complex/float, or float/complex.
920 // When both operands are complex, the shorter operand is converted to the
921 // type of the longer, and that is the type of the result. This corresponds
922 // to what is done when combining two real floating-point operands.
923 // The fun begins when size promotion occur across type domains.
924 // From H&S 6.3.4: When one operand is complex and the other is a real
925 // floating-point type, the less precise type is converted, within it's
926 // real or complex domain, to the precision of the other type. For example,
927 // when combining a "long double" with a "double _Complex", the
928 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000929 int result = Context.compareFloatingType(lhs, rhs);
930
931 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000932 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
933 if (!isCompAssign)
934 promoteExprToType(rhsExpr, rhs);
935 } else if (result < 0) { // The right side is bigger, convert lhs.
936 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
937 if (!isCompAssign)
938 promoteExprToType(lhsExpr, lhs);
939 }
940 // At this point, lhs and rhs have the same rank/size. Now, make sure the
941 // domains match. This is a requirement for our implementation, C99
942 // does not require this promotion.
943 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
944 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000945 if (!isCompAssign)
946 promoteExprToType(lhsExpr, rhs);
947 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000948 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000949 if (!isCompAssign)
950 promoteExprToType(rhsExpr, lhs);
951 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000952 }
Chris Lattner4b009652007-07-25 00:24:17 +0000953 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000954 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000955 }
956 // Now handle "real" floating types (i.e. float, double, long double).
957 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
958 // if we have an integer operand, the result is the real floating type.
959 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000960 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
961 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000962 }
963 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000964 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
965 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000966 }
967 // We have two real floating types, float/complex combos were handled above.
968 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +0000969 int result = Context.compareFloatingType(lhs, rhs);
970
971 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000972 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
973 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000974 }
Steve Naroff45fc9822007-08-27 15:30:22 +0000975 if (result < 0) { // convert the lhs
976 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
977 return rhs;
978 }
979 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +0000980 }
981 // Finally, we have two differing integer types.
982 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000983 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
984 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000985 }
Steve Naroff8f708362007-08-24 19:07:16 +0000986 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
987 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000988}
989
990// CheckPointerTypesForAssignment - This is a very tricky routine (despite
991// being closely modeled after the C99 spec:-). The odd characteristic of this
992// routine is it effectively iqnores the qualifiers on the top level pointee.
993// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
994// FIXME: add a couple examples in this comment.
995Sema::AssignmentCheckResult
996Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
997 QualType lhptee, rhptee;
998
999 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001000 lhptee = lhsType->getAsPointerType()->getPointeeType();
1001 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001002
1003 // make sure we operate on the canonical type
1004 lhptee = lhptee.getCanonicalType();
1005 rhptee = rhptee.getCanonicalType();
1006
1007 AssignmentCheckResult r = Compatible;
1008
1009 // C99 6.5.16.1p1: This following citation is common to constraints
1010 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1011 // qualifiers of the type *pointed to* by the right;
1012 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1013 rhptee.getQualifiers())
1014 r = CompatiblePointerDiscardsQualifiers;
1015
1016 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1017 // incomplete type and the other is a pointer to a qualified or unqualified
1018 // version of void...
1019 if (lhptee.getUnqualifiedType()->isVoidType() &&
1020 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1021 ;
1022 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1023 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1024 ;
1025 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1026 // unqualified versions of compatible types, ...
Steve Naroff85f0dc52007-10-15 20:41:53 +00001027 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1028 rhptee.getUnqualifiedType()))
Chris Lattner4b009652007-07-25 00:24:17 +00001029 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1030 return r;
1031}
1032
1033/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1034/// has code to accommodate several GCC extensions when type checking
1035/// pointers. Here are some objectionable examples that GCC considers warnings:
1036///
1037/// int a, *pint;
1038/// short *pshort;
1039/// struct foo *pfoo;
1040///
1041/// pint = pshort; // warning: assignment from incompatible pointer type
1042/// a = pint; // warning: assignment makes integer from pointer without a cast
1043/// pint = a; // warning: assignment makes pointer from integer without a cast
1044/// pint = pfoo; // warning: assignment from incompatible pointer type
1045///
1046/// As a result, the code for dealing with pointers is more complex than the
1047/// C99 spec dictates.
1048/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1049///
1050Sema::AssignmentCheckResult
1051Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroffeed76842007-11-13 00:31:42 +00001052 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1053 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattnera703c2e2007-10-29 05:15:40 +00001054 return Compatible; // common case, fast path...
Chris Lattner4b009652007-07-25 00:24:17 +00001055
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001056 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001057 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001058 return Compatible;
1059 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001060 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1061 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1062 return Incompatible;
1063 }
1064 return Compatible;
1065 } else if (lhsType->isPointerType()) {
1066 if (rhsType->isIntegerType())
1067 return PointerFromInt;
1068
1069 if (rhsType->isPointerType())
1070 return CheckPointerTypesForAssignment(lhsType, rhsType);
1071 } else if (rhsType->isPointerType()) {
1072 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1073 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1074 return IntFromPointer;
1075
1076 if (lhsType->isPointerType())
1077 return CheckPointerTypesForAssignment(lhsType, rhsType);
1078 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001079 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001080 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001081 }
1082 return Incompatible;
1083}
1084
1085Sema::AssignmentCheckResult
1086Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Chris Lattner5f505bf2007-10-16 02:55:40 +00001087 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001088 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001089 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001090 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001091 //
1092 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1093 // are better understood.
1094 if (!lhsType->isReferenceType())
1095 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001096
1097 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001098
Steve Naroff0f32f432007-08-24 22:33:52 +00001099 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1100
1101 // C99 6.5.16.1p2: The value of the right operand is converted to the
1102 // type of the assignment expression.
1103 if (rExpr->getType() != lhsType)
1104 promoteExprToType(rExpr, lhsType);
1105 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001106}
1107
1108Sema::AssignmentCheckResult
1109Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1110 return CheckAssignmentConstraints(lhsType, rhsType);
1111}
1112
1113inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1114 Diag(loc, diag::err_typecheck_invalid_operands,
1115 lex->getType().getAsString(), rex->getType().getAsString(),
1116 lex->getSourceRange(), rex->getSourceRange());
1117}
1118
1119inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1120 Expr *&rex) {
1121 QualType lhsType = lex->getType(), rhsType = rex->getType();
1122
1123 // make sure the vector types are identical.
1124 if (lhsType == rhsType)
1125 return lhsType;
1126 // You cannot convert between vector values of different size.
1127 Diag(loc, diag::err_typecheck_vector_not_convertable,
1128 lex->getType().getAsString(), rex->getType().getAsString(),
1129 lex->getSourceRange(), rex->getSourceRange());
1130 return QualType();
1131}
1132
1133inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001134 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001135{
1136 QualType lhsType = lex->getType(), rhsType = rex->getType();
1137
1138 if (lhsType->isVectorType() || rhsType->isVectorType())
1139 return CheckVectorOperands(loc, lex, rex);
1140
Steve Naroff8f708362007-08-24 19:07:16 +00001141 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001142
Chris Lattner4b009652007-07-25 00:24:17 +00001143 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001144 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001145 InvalidOperands(loc, lex, rex);
1146 return QualType();
1147}
1148
1149inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001150 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001151{
1152 QualType lhsType = lex->getType(), rhsType = rex->getType();
1153
Steve Naroff8f708362007-08-24 19:07:16 +00001154 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001155
Chris Lattner4b009652007-07-25 00:24:17 +00001156 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001157 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001158 InvalidOperands(loc, lex, rex);
1159 return QualType();
1160}
1161
1162inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001163 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001164{
1165 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1166 return CheckVectorOperands(loc, lex, rex);
1167
Steve Naroff8f708362007-08-24 19:07:16 +00001168 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001169
1170 // handle the common case first (both operands are arithmetic).
1171 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001172 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001173
1174 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1175 return lex->getType();
1176 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1177 return rex->getType();
1178 InvalidOperands(loc, lex, rex);
1179 return QualType();
1180}
1181
1182inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001183 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001184{
1185 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1186 return CheckVectorOperands(loc, lex, rex);
1187
Steve Naroff8f708362007-08-24 19:07:16 +00001188 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001189
1190 // handle the common case first (both operands are arithmetic).
1191 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001192 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001193
1194 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001195 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001196 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1197 return Context.getPointerDiffType();
1198 InvalidOperands(loc, lex, rex);
1199 return QualType();
1200}
1201
1202inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001203 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001204{
1205 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1206 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001207 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001208
1209 // handle the common case first (both operands are arithmetic).
1210 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001211 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001212 InvalidOperands(loc, lex, rex);
1213 return QualType();
1214}
1215
Ted Kremenekdbb14ce2007-10-29 16:45:23 +00001216// Utility method to plow through parentheses to get the first nested
1217// non-ParenExpr expr.
1218static inline Expr* IgnoreParen(Expr* E) {
Ted Kremenek193c1252007-10-30 21:03:09 +00001219 while (ParenExpr* P = dyn_cast<ParenExpr>(E))
1220 E = P->getSubExpr();
Ted Kremenekdbb14ce2007-10-29 16:45:23 +00001221
1222 return E;
1223}
1224
Ted Kremenek0d054eb2007-11-13 19:17:00 +00001225// Utility method to plow through parenthesis and casts.
1226static inline Expr* IgnoreParenCasts(Expr* E) {
1227 while(true) {
1228 if (ParenExpr* P = dyn_cast<ParenExpr>(E))
1229 E = P->getSubExpr();
1230 else if (CastExpr* P = dyn_cast<CastExpr>(E))
1231 E = P->getSubExpr();
1232 else if (ImplicitCastExpr* P = dyn_cast<ImplicitCastExpr>(E))
1233 E = P->getSubExpr();
1234 else
1235 break;
1236 }
1237
1238 return E;
1239}
1240
1241// Utility method to determine if a CallExpr is a call to a builtin.
1242static inline bool isCallBuiltin(CallExpr* cexp) {
1243 Expr* sub = IgnoreParenCasts(cexp->getCallee());
1244
1245 if (DeclRefExpr* E = dyn_cast<DeclRefExpr>(sub))
1246 if (E->getDecl()->getIdentifier()->getBuiltinID() > 0)
1247 return true;
1248
1249 return false;
1250}
1251
Chris Lattner254f3bc2007-08-26 01:18:55 +00001252inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1253 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001254{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001255 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001256 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1257 UsualArithmeticConversions(lex, rex);
1258 else {
1259 UsualUnaryConversions(lex);
1260 UsualUnaryConversions(rex);
1261 }
Chris Lattner4b009652007-07-25 00:24:17 +00001262 QualType lType = lex->getType();
1263 QualType rType = rex->getType();
1264
Ted Kremenek486509e2007-10-29 17:13:39 +00001265 // For non-floating point types, check for self-comparisons of the form
1266 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1267 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001268 if (!lType->isFloatingType()) {
1269 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1270 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1271 if (DRL->getDecl() == DRR->getDecl())
1272 Diag(loc, diag::warn_selfcomparison);
1273 }
1274
Chris Lattner254f3bc2007-08-26 01:18:55 +00001275 if (isRelational) {
1276 if (lType->isRealType() && rType->isRealType())
1277 return Context.IntTy;
1278 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001279 // Check for comparisons of floating point operands using != and ==.
1280 // Issue a warning if these are no self-comparisons, as they are not likely
1281 // to do what the programmer intended.
1282 if (lType->isFloatingType()) {
1283 assert (rType->isFloatingType());
1284
Ted Kremenek75439142007-10-29 16:40:01 +00001285 // Special case: check for x == x (which is OK).
1286 bool EmitWarning = true;
1287
Ted Kremenek0d054eb2007-11-13 19:17:00 +00001288 Expr* LeftExprSansParen = IgnoreParen(lex);
1289 Expr* RightExprSansParen = IgnoreParen(rex);
1290
1291 // Look for x == x. Do not emit warnings for such cases.
1292 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1293 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
Ted Kremenek75439142007-10-29 16:40:01 +00001294 if (DRL->getDecl() == DRR->getDecl())
1295 EmitWarning = false;
Ted Kremenek0d054eb2007-11-13 19:17:00 +00001296
1297 // Check for comparisons with builtin types.
1298 if (EmitWarning)
1299 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1300 if (isCallBuiltin(CL))
1301 EmitWarning = false;
Ted Kremenek75439142007-10-29 16:40:01 +00001302
Ted Kremenek0d054eb2007-11-13 19:17:00 +00001303 if (EmitWarning)
1304 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1305 if (isCallBuiltin(CR))
1306 EmitWarning = false;
1307
1308 // Emit the diagnostic.
Ted Kremenek75439142007-10-29 16:40:01 +00001309 if (EmitWarning)
Ted Kremeneke12201e2007-11-13 18:40:33 +00001310 Diag(loc, diag::warn_floatingpoint_eq,
1311 lex->getSourceRange(),rex->getSourceRange());
Ted Kremenek75439142007-10-29 16:40:01 +00001312 }
1313
Chris Lattner254f3bc2007-08-26 01:18:55 +00001314 if (lType->isArithmeticType() && rType->isArithmeticType())
1315 return Context.IntTy;
1316 }
Chris Lattner4b009652007-07-25 00:24:17 +00001317
Chris Lattner22be8422007-08-26 01:10:14 +00001318 bool LHSIsNull = lex->isNullPointerConstant(Context);
1319 bool RHSIsNull = rex->isNullPointerConstant(Context);
1320
Chris Lattner254f3bc2007-08-26 01:18:55 +00001321 // All of the following pointer related warnings are GCC extensions, except
1322 // when handling null pointer constants. One day, we can consider making them
1323 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001324 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001325
1326 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1327 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1328 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001329 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1330 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001331 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1332 lType.getAsString(), rType.getAsString(),
1333 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001334 }
Chris Lattner22be8422007-08-26 01:10:14 +00001335 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001336 return Context.IntTy;
1337 }
1338 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001339 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001340 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1341 lType.getAsString(), rType.getAsString(),
1342 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001343 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001344 return Context.IntTy;
1345 }
1346 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001347 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001348 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1349 lType.getAsString(), rType.getAsString(),
1350 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001351 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001352 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001353 }
1354 InvalidOperands(loc, lex, rex);
1355 return QualType();
1356}
1357
Chris Lattner4b009652007-07-25 00:24:17 +00001358inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001359 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001360{
1361 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1362 return CheckVectorOperands(loc, lex, rex);
1363
Steve Naroff8f708362007-08-24 19:07:16 +00001364 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001365
1366 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001367 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001368 InvalidOperands(loc, lex, rex);
1369 return QualType();
1370}
1371
1372inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1373 Expr *&lex, Expr *&rex, SourceLocation loc)
1374{
1375 UsualUnaryConversions(lex);
1376 UsualUnaryConversions(rex);
1377
1378 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1379 return Context.IntTy;
1380 InvalidOperands(loc, lex, rex);
1381 return QualType();
1382}
1383
1384inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001385 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001386{
1387 QualType lhsType = lex->getType();
1388 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1389 bool hadError = false;
1390 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1391
1392 switch (mlval) { // C99 6.5.16p2
1393 case Expr::MLV_Valid:
1394 break;
1395 case Expr::MLV_ConstQualified:
1396 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1397 hadError = true;
1398 break;
1399 case Expr::MLV_ArrayType:
1400 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1401 lhsType.getAsString(), lex->getSourceRange());
1402 return QualType();
1403 case Expr::MLV_NotObjectType:
1404 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1405 lhsType.getAsString(), lex->getSourceRange());
1406 return QualType();
1407 case Expr::MLV_InvalidExpression:
1408 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1409 lex->getSourceRange());
1410 return QualType();
1411 case Expr::MLV_IncompleteType:
1412 case Expr::MLV_IncompleteVoidType:
1413 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1414 lhsType.getAsString(), lex->getSourceRange());
1415 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001416 case Expr::MLV_DuplicateVectorComponents:
1417 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1418 lex->getSourceRange());
1419 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001420 }
1421 AssignmentCheckResult result;
1422
1423 if (compoundType.isNull())
1424 result = CheckSingleAssignmentConstraints(lhsType, rex);
1425 else
1426 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001427
Chris Lattner4b009652007-07-25 00:24:17 +00001428 // decode the result (notice that extensions still return a type).
1429 switch (result) {
1430 case Compatible:
1431 break;
1432 case Incompatible:
1433 Diag(loc, diag::err_typecheck_assign_incompatible,
1434 lhsType.getAsString(), rhsType.getAsString(),
1435 lex->getSourceRange(), rex->getSourceRange());
1436 hadError = true;
1437 break;
1438 case PointerFromInt:
1439 // check for null pointer constant (C99 6.3.2.3p3)
1440 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1441 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1442 lhsType.getAsString(), rhsType.getAsString(),
1443 lex->getSourceRange(), rex->getSourceRange());
1444 }
1445 break;
1446 case IntFromPointer:
1447 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1448 lhsType.getAsString(), rhsType.getAsString(),
1449 lex->getSourceRange(), rex->getSourceRange());
1450 break;
1451 case IncompatiblePointer:
1452 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1453 lhsType.getAsString(), rhsType.getAsString(),
1454 lex->getSourceRange(), rex->getSourceRange());
1455 break;
1456 case CompatiblePointerDiscardsQualifiers:
1457 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1458 lhsType.getAsString(), rhsType.getAsString(),
1459 lex->getSourceRange(), rex->getSourceRange());
1460 break;
1461 }
1462 // C99 6.5.16p3: The type of an assignment expression is the type of the
1463 // left operand unless the left operand has qualified type, in which case
1464 // it is the unqualified version of the type of the left operand.
1465 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1466 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001467 // C++ 5.17p1: the type of the assignment expression is that of its left
1468 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001469 return hadError ? QualType() : lhsType.getUnqualifiedType();
1470}
1471
1472inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1473 Expr *&lex, Expr *&rex, SourceLocation loc) {
1474 UsualUnaryConversions(rex);
1475 return rex->getType();
1476}
1477
1478/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1479/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1480QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1481 QualType resType = op->getType();
1482 assert(!resType.isNull() && "no type for increment/decrement expression");
1483
Steve Naroffd30e1932007-08-24 17:20:07 +00001484 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001485 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001486 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1487 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1488 resType.getAsString(), op->getSourceRange());
1489 return QualType();
1490 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001491 } else if (!resType->isRealType()) {
1492 if (resType->isComplexType())
1493 // C99 does not support ++/-- on complex types.
1494 Diag(OpLoc, diag::ext_integer_increment_complex,
1495 resType.getAsString(), op->getSourceRange());
1496 else {
1497 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1498 resType.getAsString(), op->getSourceRange());
1499 return QualType();
1500 }
Chris Lattner4b009652007-07-25 00:24:17 +00001501 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001502 // At this point, we know we have a real, complex or pointer type.
1503 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001504 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1505 if (mlval != Expr::MLV_Valid) {
1506 // FIXME: emit a more precise diagnostic...
1507 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1508 op->getSourceRange());
1509 return QualType();
1510 }
1511 return resType;
1512}
1513
1514/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1515/// This routine allows us to typecheck complex/recursive expressions
1516/// where the declaration is needed for type checking. Here are some
1517/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1518static Decl *getPrimaryDeclaration(Expr *e) {
1519 switch (e->getStmtClass()) {
1520 case Stmt::DeclRefExprClass:
1521 return cast<DeclRefExpr>(e)->getDecl();
1522 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001523 // Fields cannot be declared with a 'register' storage class.
1524 // &X->f is always ok, even if X is declared register.
1525 if (cast<MemberExpr>(e)->isArrow())
1526 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001527 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1528 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001529 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001530 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001531 case Stmt::UnaryOperatorClass:
1532 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1533 case Stmt::ParenExprClass:
1534 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001535 case Stmt::ImplicitCastExprClass:
1536 // &X[4] when X is an array, has an implicit cast from array to pointer.
1537 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001538 default:
1539 return 0;
1540 }
1541}
1542
1543/// CheckAddressOfOperand - The operand of & must be either a function
1544/// designator or an lvalue designating an object. If it is an lvalue, the
1545/// object cannot be declared with storage class register or be a bit field.
1546/// Note: The usual conversions are *not* applied to the operand of the &
1547/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1548QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1549 Decl *dcl = getPrimaryDeclaration(op);
1550 Expr::isLvalueResult lval = op->isLvalue();
1551
1552 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001553 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1554 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001555 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1556 op->getSourceRange());
1557 return QualType();
1558 }
1559 } else if (dcl) {
1560 // We have an lvalue with a decl. Make sure the decl is not declared
1561 // with the register storage-class specifier.
1562 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1563 if (vd->getStorageClass() == VarDecl::Register) {
1564 Diag(OpLoc, diag::err_typecheck_address_of_register,
1565 op->getSourceRange());
1566 return QualType();
1567 }
1568 } else
1569 assert(0 && "Unknown/unexpected decl type");
1570
1571 // FIXME: add check for bitfields!
1572 }
1573 // If the operand has type "type", the result has type "pointer to type".
1574 return Context.getPointerType(op->getType());
1575}
1576
1577QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1578 UsualUnaryConversions(op);
1579 QualType qType = op->getType();
1580
Chris Lattner7931f4a2007-07-31 16:53:04 +00001581 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001582 QualType ptype = PT->getPointeeType();
1583 // C99 6.5.3.2p4. "if it points to an object,...".
1584 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1585 // GCC compat: special case 'void *' (treat as warning).
1586 if (ptype->isVoidType()) {
1587 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1588 qType.getAsString(), op->getSourceRange());
1589 } else {
1590 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1591 ptype.getAsString(), op->getSourceRange());
1592 return QualType();
1593 }
1594 }
1595 return ptype;
1596 }
1597 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1598 qType.getAsString(), op->getSourceRange());
1599 return QualType();
1600}
1601
1602static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1603 tok::TokenKind Kind) {
1604 BinaryOperator::Opcode Opc;
1605 switch (Kind) {
1606 default: assert(0 && "Unknown binop!");
1607 case tok::star: Opc = BinaryOperator::Mul; break;
1608 case tok::slash: Opc = BinaryOperator::Div; break;
1609 case tok::percent: Opc = BinaryOperator::Rem; break;
1610 case tok::plus: Opc = BinaryOperator::Add; break;
1611 case tok::minus: Opc = BinaryOperator::Sub; break;
1612 case tok::lessless: Opc = BinaryOperator::Shl; break;
1613 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1614 case tok::lessequal: Opc = BinaryOperator::LE; break;
1615 case tok::less: Opc = BinaryOperator::LT; break;
1616 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1617 case tok::greater: Opc = BinaryOperator::GT; break;
1618 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1619 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1620 case tok::amp: Opc = BinaryOperator::And; break;
1621 case tok::caret: Opc = BinaryOperator::Xor; break;
1622 case tok::pipe: Opc = BinaryOperator::Or; break;
1623 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1624 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1625 case tok::equal: Opc = BinaryOperator::Assign; break;
1626 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1627 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1628 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1629 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1630 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1631 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1632 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1633 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1634 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1635 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1636 case tok::comma: Opc = BinaryOperator::Comma; break;
1637 }
1638 return Opc;
1639}
1640
1641static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1642 tok::TokenKind Kind) {
1643 UnaryOperator::Opcode Opc;
1644 switch (Kind) {
1645 default: assert(0 && "Unknown unary op!");
1646 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1647 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1648 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1649 case tok::star: Opc = UnaryOperator::Deref; break;
1650 case tok::plus: Opc = UnaryOperator::Plus; break;
1651 case tok::minus: Opc = UnaryOperator::Minus; break;
1652 case tok::tilde: Opc = UnaryOperator::Not; break;
1653 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1654 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1655 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1656 case tok::kw___real: Opc = UnaryOperator::Real; break;
1657 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1658 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1659 }
1660 return Opc;
1661}
1662
1663// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001664Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001665 ExprTy *LHS, ExprTy *RHS) {
1666 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1667 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1668
Steve Naroff87d58b42007-09-16 03:34:24 +00001669 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1670 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001671
1672 QualType ResultTy; // Result type of the binary operator.
1673 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1674
1675 switch (Opc) {
1676 default:
1677 assert(0 && "Unknown binary expr!");
1678 case BinaryOperator::Assign:
1679 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1680 break;
1681 case BinaryOperator::Mul:
1682 case BinaryOperator::Div:
1683 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1684 break;
1685 case BinaryOperator::Rem:
1686 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1687 break;
1688 case BinaryOperator::Add:
1689 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1690 break;
1691 case BinaryOperator::Sub:
1692 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1693 break;
1694 case BinaryOperator::Shl:
1695 case BinaryOperator::Shr:
1696 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1697 break;
1698 case BinaryOperator::LE:
1699 case BinaryOperator::LT:
1700 case BinaryOperator::GE:
1701 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001702 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001703 break;
1704 case BinaryOperator::EQ:
1705 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001706 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001707 break;
1708 case BinaryOperator::And:
1709 case BinaryOperator::Xor:
1710 case BinaryOperator::Or:
1711 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1712 break;
1713 case BinaryOperator::LAnd:
1714 case BinaryOperator::LOr:
1715 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1716 break;
1717 case BinaryOperator::MulAssign:
1718 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001719 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001720 if (!CompTy.isNull())
1721 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1722 break;
1723 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001724 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001725 if (!CompTy.isNull())
1726 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1727 break;
1728 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001729 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001730 if (!CompTy.isNull())
1731 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1732 break;
1733 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001734 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001735 if (!CompTy.isNull())
1736 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1737 break;
1738 case BinaryOperator::ShlAssign:
1739 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001740 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001741 if (!CompTy.isNull())
1742 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1743 break;
1744 case BinaryOperator::AndAssign:
1745 case BinaryOperator::XorAssign:
1746 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001747 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001748 if (!CompTy.isNull())
1749 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1750 break;
1751 case BinaryOperator::Comma:
1752 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1753 break;
1754 }
1755 if (ResultTy.isNull())
1756 return true;
1757 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001758 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001759 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001760 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001761}
1762
1763// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001764Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001765 ExprTy *input) {
1766 Expr *Input = (Expr*)input;
1767 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1768 QualType resultType;
1769 switch (Opc) {
1770 default:
1771 assert(0 && "Unimplemented unary expr!");
1772 case UnaryOperator::PreInc:
1773 case UnaryOperator::PreDec:
1774 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1775 break;
1776 case UnaryOperator::AddrOf:
1777 resultType = CheckAddressOfOperand(Input, OpLoc);
1778 break;
1779 case UnaryOperator::Deref:
1780 resultType = CheckIndirectionOperand(Input, OpLoc);
1781 break;
1782 case UnaryOperator::Plus:
1783 case UnaryOperator::Minus:
1784 UsualUnaryConversions(Input);
1785 resultType = Input->getType();
1786 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1787 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1788 resultType.getAsString());
1789 break;
1790 case UnaryOperator::Not: // bitwise complement
1791 UsualUnaryConversions(Input);
1792 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001793 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1794 if (!resultType->isIntegerType()) {
1795 if (resultType->isComplexType())
1796 // C99 does not support '~' for complex conjugation.
1797 Diag(OpLoc, diag::ext_integer_complement_complex,
1798 resultType.getAsString());
1799 else
1800 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1801 resultType.getAsString());
1802 }
Chris Lattner4b009652007-07-25 00:24:17 +00001803 break;
1804 case UnaryOperator::LNot: // logical negation
1805 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1806 DefaultFunctionArrayConversion(Input);
1807 resultType = Input->getType();
1808 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1809 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1810 resultType.getAsString());
1811 // LNot always has type int. C99 6.5.3.3p5.
1812 resultType = Context.IntTy;
1813 break;
1814 case UnaryOperator::SizeOf:
1815 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1816 break;
1817 case UnaryOperator::AlignOf:
1818 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1819 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001820 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001821 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001822 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001823 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001824 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001825 resultType = Input->getType();
1826 break;
1827 }
1828 if (resultType.isNull())
1829 return true;
1830 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1831}
1832
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001833/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1834Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001835 SourceLocation LabLoc,
1836 IdentifierInfo *LabelII) {
1837 // Look up the record for this label identifier.
1838 LabelStmt *&LabelDecl = LabelMap[LabelII];
1839
1840 // If we haven't seen this label yet, create a forward reference.
1841 if (LabelDecl == 0)
1842 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1843
1844 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001845 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1846 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001847}
1848
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001849Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001850 SourceLocation RPLoc) { // "({..})"
1851 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1852 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1853 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1854
1855 // FIXME: there are a variety of strange constraints to enforce here, for
1856 // example, it is not possible to goto into a stmt expression apparently.
1857 // More semantic analysis is needed.
1858
1859 // FIXME: the last statement in the compount stmt has its value used. We
1860 // should not warn about it being unused.
1861
1862 // If there are sub stmts in the compound stmt, take the type of the last one
1863 // as the type of the stmtexpr.
1864 QualType Ty = Context.VoidTy;
1865
1866 if (!Compound->body_empty())
1867 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1868 Ty = LastExpr->getType();
1869
1870 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1871}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001872
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001873Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001874 SourceLocation TypeLoc,
1875 TypeTy *argty,
1876 OffsetOfComponent *CompPtr,
1877 unsigned NumComponents,
1878 SourceLocation RPLoc) {
1879 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1880 assert(!ArgTy.isNull() && "Missing type argument!");
1881
1882 // We must have at least one component that refers to the type, and the first
1883 // one is known to be a field designator. Verify that the ArgTy represents
1884 // a struct/union/class.
1885 if (!ArgTy->isRecordType())
1886 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1887
1888 // Otherwise, create a compound literal expression as the base, and
1889 // iteratively process the offsetof designators.
1890 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1891
Chris Lattnerb37522e2007-08-31 21:49:13 +00001892 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1893 // GCC extension, diagnose them.
1894 if (NumComponents != 1)
1895 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1896 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1897
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001898 for (unsigned i = 0; i != NumComponents; ++i) {
1899 const OffsetOfComponent &OC = CompPtr[i];
1900 if (OC.isBrackets) {
1901 // Offset of an array sub-field. TODO: Should we allow vector elements?
1902 const ArrayType *AT = Res->getType()->getAsArrayType();
1903 if (!AT) {
1904 delete Res;
1905 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1906 Res->getType().getAsString());
1907 }
1908
Chris Lattner2af6a802007-08-30 17:59:59 +00001909 // FIXME: C++: Verify that operator[] isn't overloaded.
1910
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001911 // C99 6.5.2.1p1
1912 Expr *Idx = static_cast<Expr*>(OC.U.E);
1913 if (!Idx->getType()->isIntegerType())
1914 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1915 Idx->getSourceRange());
1916
1917 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1918 continue;
1919 }
1920
1921 const RecordType *RC = Res->getType()->getAsRecordType();
1922 if (!RC) {
1923 delete Res;
1924 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1925 Res->getType().getAsString());
1926 }
1927
1928 // Get the decl corresponding to this.
1929 RecordDecl *RD = RC->getDecl();
1930 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1931 if (!MemberDecl)
1932 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1933 OC.U.IdentInfo->getName(),
1934 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001935
1936 // FIXME: C++: Verify that MemberDecl isn't a static field.
1937 // FIXME: Verify that MemberDecl isn't a bitfield.
1938
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001939 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1940 }
1941
1942 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1943 BuiltinLoc);
1944}
1945
1946
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001947Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001948 TypeTy *arg1, TypeTy *arg2,
1949 SourceLocation RPLoc) {
1950 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1951 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1952
1953 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1954
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001955 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001956}
1957
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001958Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00001959 ExprTy *expr1, ExprTy *expr2,
1960 SourceLocation RPLoc) {
1961 Expr *CondExpr = static_cast<Expr*>(cond);
1962 Expr *LHSExpr = static_cast<Expr*>(expr1);
1963 Expr *RHSExpr = static_cast<Expr*>(expr2);
1964
1965 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1966
1967 // The conditional expression is required to be a constant expression.
1968 llvm::APSInt condEval(32);
1969 SourceLocation ExpLoc;
1970 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1971 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1972 CondExpr->getSourceRange());
1973
1974 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1975 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1976 RHSExpr->getType();
1977 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1978}
1979
Anders Carlsson36760332007-10-15 20:28:48 +00001980Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
1981 ExprTy *expr, TypeTy *type,
1982 SourceLocation RPLoc)
1983{
1984 Expr *E = static_cast<Expr*>(expr);
1985 QualType T = QualType::getFromOpaquePtr(type);
1986
1987 InitBuiltinVaListType();
1988
1989 Sema::AssignmentCheckResult result;
1990
1991 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
1992 E->getType());
1993 if (result != Compatible)
1994 return Diag(E->getLocStart(),
1995 diag::err_first_argument_to_va_arg_not_of_type_va_list,
1996 E->getType().getAsString(),
1997 E->getSourceRange());
1998
1999 // FIXME: Warn if a non-POD type is passed in.
2000
2001 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2002}
2003
Anders Carlssona66cad42007-08-21 17:43:55 +00002004// TODO: Move this to SemaObjC.cpp
Steve Naroff0add5d22007-11-03 11:27:19 +00002005Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation AtLoc,
2006 ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00002007 StringLiteral* S = static_cast<StringLiteral *>(string);
2008
2009 if (CheckBuiltinCFStringArgument(S))
2010 return true;
2011
Steve Narofff2e30312007-10-15 23:35:17 +00002012 if (Context.getObjcConstantStringInterface().isNull()) {
2013 // Initialize the constant string interface lazily. This assumes
2014 // the NSConstantString interface is seen in this translation unit.
2015 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
2016 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
2017 SourceLocation(), TUScope);
Steve Naroff134c3502007-10-16 00:00:18 +00002018 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff96f136d2007-10-18 23:53:51 +00002019 if (!strIFace)
2020 return Diag(S->getLocStart(), diag::err_undef_interface,
2021 NSIdent->getName());
Steve Naroff134c3502007-10-16 00:00:18 +00002022 Context.setObjcConstantStringInterface(strIFace);
Steve Narofff2e30312007-10-15 23:35:17 +00002023 }
2024 QualType t = Context.getObjcConstantStringInterface();
Anders Carlssona66cad42007-08-21 17:43:55 +00002025 t = Context.getPointerType(t);
Steve Naroff0add5d22007-11-03 11:27:19 +00002026 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlssona66cad42007-08-21 17:43:55 +00002027}
Anders Carlsson8be1d402007-08-22 15:14:15 +00002028
2029Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattnercfd61c82007-10-16 22:51:17 +00002030 SourceLocation EncodeLoc,
Anders Carlsson8be1d402007-08-22 15:14:15 +00002031 SourceLocation LParenLoc,
2032 TypeTy *Ty,
2033 SourceLocation RParenLoc) {
2034 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2035
2036 QualType t = Context.getPointerType(Context.CharTy);
2037 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2038}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002039
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002040Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2041 SourceLocation AtLoc,
Fariborz Jahanian957448a2007-10-16 23:21:02 +00002042 SourceLocation SelLoc,
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002043 SourceLocation LParenLoc,
2044 SourceLocation RParenLoc) {
Steve Naroffae84af82007-10-31 18:42:27 +00002045 QualType t = Context.getObjcSelType();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002046 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2047}
2048
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002049Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2050 SourceLocation AtLoc,
2051 SourceLocation ProtoLoc,
2052 SourceLocation LParenLoc,
2053 SourceLocation RParenLoc) {
2054 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2055 if (!PDecl) {
2056 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2057 return true;
2058 }
2059
2060 QualType t = GetObjcProtoType(AtLoc);
Fariborz Jahanian20b40e42007-10-18 22:59:23 +00002061 if (t.isNull())
2062 return true;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002063 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2064}
Steve Naroff52664182007-10-16 23:12:48 +00002065
2066bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2067 ObjcMethodDecl *Method) {
2068 bool anyIncompatibleArgs = false;
2069
2070 for (unsigned i = 0; i < NumArgs; i++) {
2071 Expr *argExpr = Args[i];
2072 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2073
2074 QualType lhsType = Method->getParamDecl(i)->getType();
2075 QualType rhsType = argExpr->getType();
2076
2077 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2078 if (const ArrayType *ary = lhsType->getAsArrayType())
2079 lhsType = Context.getPointerType(ary->getElementType());
2080 else if (lhsType->isFunctionType())
2081 lhsType = Context.getPointerType(lhsType);
2082
2083 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2084 argExpr);
2085 if (Args[i] != argExpr) // The expression was converted.
2086 Args[i] = argExpr; // Make sure we store the converted expression.
2087 SourceLocation l = argExpr->getLocStart();
2088
2089 // decode the result (notice that AST's are still created for extensions).
2090 switch (result) {
2091 case Compatible:
2092 break;
2093 case PointerFromInt:
2094 // check for null pointer constant (C99 6.3.2.3p3)
2095 if (!argExpr->isNullPointerConstant(Context)) {
2096 Diag(l, diag::ext_typecheck_sending_pointer_int,
2097 lhsType.getAsString(), rhsType.getAsString(),
2098 argExpr->getSourceRange());
2099 }
2100 break;
2101 case IntFromPointer:
2102 Diag(l, diag::ext_typecheck_sending_pointer_int,
2103 lhsType.getAsString(), rhsType.getAsString(),
2104 argExpr->getSourceRange());
2105 break;
2106 case IncompatiblePointer:
2107 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2108 rhsType.getAsString(), lhsType.getAsString(),
2109 argExpr->getSourceRange());
2110 break;
2111 case CompatiblePointerDiscardsQualifiers:
2112 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2113 rhsType.getAsString(), lhsType.getAsString(),
2114 argExpr->getSourceRange());
2115 break;
2116 case Incompatible:
2117 Diag(l, diag::err_typecheck_sending_incompatible,
2118 rhsType.getAsString(), lhsType.getAsString(),
2119 argExpr->getSourceRange());
2120 anyIncompatibleArgs = true;
2121 }
2122 }
2123 return anyIncompatibleArgs;
2124}
2125
Steve Naroff4ed9d662007-09-27 14:38:14 +00002126// ActOnClassMessage - used for both unary and keyword messages.
2127// ArgExprs is optional - if it is present, the number of expressions
2128// is obtained from Sel.getNumArgs().
2129Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002130 Scope *S,
Steve Narofffa465d12007-10-02 20:01:56 +00002131 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002132 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002133{
Steve Narofffa465d12007-10-02 20:01:56 +00002134 assert(receiverName && "missing receiver class name");
Steve Naroffc39ca262007-09-18 23:55:05 +00002135
Steve Naroff52664182007-10-16 23:12:48 +00002136 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002137 ObjcInterfaceDecl* ClassDecl = 0;
2138 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2139 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahanian342f3602007-11-12 20:20:37 +00002140 if (ClassDecl && CurMethodDecl->isInstance()) {
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002141 IdentifierInfo &II = Context.Idents.get("self");
2142 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II,
2143 false);
2144 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2145 superTy = Context.getPointerType(superTy);
2146 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2147 SourceLocation(), ReceiverExpr.Val);
2148
2149 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002150 Args, NumArgs);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002151 }
2152 // class method
2153 if (ClassDecl)
2154 receiverName = ClassDecl->getIdentifier();
2155 }
2156 else
2157 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Narofffa465d12007-10-02 20:01:56 +00002158 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002159 QualType returnType;
Steve Naroff75c4baf2007-11-05 15:27:52 +00002160
2161 // Before we give up, check if the selector is an instance method.
2162 if (!Method)
2163 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002164 if (!Method) {
2165 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2166 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002167 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002168 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002169 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002170 if (Sel.getNumArgs()) {
2171 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2172 return true;
2173 }
Steve Naroff7e461452007-10-16 20:39:36 +00002174 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002175 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff9f176d12007-11-15 13:05:42 +00002176 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002177}
2178
Steve Naroff4ed9d662007-09-27 14:38:14 +00002179// ActOnInstanceMessage - used for both unary and keyword messages.
2180// ArgExprs is optional - if it is present, the number of expressions
2181// is obtained from Sel.getNumArgs().
2182Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroff6cb1d362007-09-28 22:22:11 +00002183 ExprTy *receiver, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002184 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff4ed9d662007-09-27 14:38:14 +00002185{
Steve Naroffc39ca262007-09-18 23:55:05 +00002186 assert(receiver && "missing receiver expression");
2187
Steve Naroff52664182007-10-16 23:12:48 +00002188 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroffc39ca262007-09-18 23:55:05 +00002189 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Narofffa465d12007-10-02 20:01:56 +00002190 QualType receiverType = RExpr->getType();
Steve Naroffee1de132007-10-10 21:53:07 +00002191 QualType returnType;
Steve Naroff1e1c3912007-11-03 16:37:59 +00002192 ObjcMethodDecl *Method;
Steve Naroffee1de132007-10-10 21:53:07 +00002193
Steve Naroff0091d142007-11-11 17:52:25 +00002194 if (receiverType == Context.getObjcIdType() ||
2195 receiverType == Context.getObjcClassType()) {
Steve Naroff1e1c3912007-11-03 16:37:59 +00002196 Method = InstanceMethodPool[Sel].Method;
Steve Naroffd0cfcd02007-11-13 04:10:18 +00002197 // If we didn't find an public method, look for a private one.
2198 if (!Method && CurMethodDecl) {
2199 NamedDecl *impCxt = CurMethodDecl->getMethodContext();
2200 if (ObjcImplementationDecl *IMD =
2201 dyn_cast<ObjcImplementationDecl>(impCxt)) {
2202 if (receiverType == Context.getObjcIdType())
2203 Method = IMD->lookupInstanceMethod(Sel);
2204 else
2205 Method = IMD->lookupClassMethod(Sel);
2206 } else if (ObjcCategoryImplDecl *CID =
2207 dyn_cast<ObjcCategoryImplDecl>(impCxt)) {
2208 if (receiverType == Context.getObjcIdType())
2209 Method = CID->lookupInstanceMethod(Sel);
2210 else
2211 Method = CID->lookupClassMethod(Sel);
2212 }
2213 }
Steve Naroff7e461452007-10-16 20:39:36 +00002214 if (!Method) {
2215 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2216 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002217 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002218 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002219 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002220 if (Sel.getNumArgs())
2221 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2222 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002223 }
Steve Naroffee1de132007-10-10 21:53:07 +00002224 } else {
Chris Lattner71c01112007-10-10 23:42:28 +00002225 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2226 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroffee1de132007-10-10 21:53:07 +00002227 while (receiverType->isPointerType()) {
Chris Lattner71c01112007-10-10 23:42:28 +00002228 PointerType *pointerType =
2229 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroffee1de132007-10-10 21:53:07 +00002230 receiverType = pointerType->getPointeeType();
2231 }
Chris Lattner71c01112007-10-10 23:42:28 +00002232 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2233 "bad receiver type");
Steve Naroffee1de132007-10-10 21:53:07 +00002234 ObjcInterfaceDecl* ClassDecl = static_cast<ObjcInterfaceType*>(
2235 receiverType.getTypePtr())->getDecl();
Steve Naroff7e461452007-10-16 20:39:36 +00002236 // FIXME: consider using InstanceMethodPool, since it will be faster
2237 // than the following method (which can do *many* linear searches). The
2238 // idea is to add class info to InstanceMethodPool...
Steve Naroff1e1c3912007-11-03 16:37:59 +00002239 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002240 if (!Method) {
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002241 // If we have an implementation in scope, check "private" methods.
2242 if (ObjcImplementationDecl *ImpDecl =
2243 ObjcImplementations[ClassDecl->getIdentifier()])
2244 Method = ImpDecl->lookupInstanceMethod(Sel);
2245 }
2246 if (!Method) {
Steve Naroff7e461452007-10-16 20:39:36 +00002247 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2248 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002249 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002250 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002251 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002252 if (Sel.getNumArgs())
2253 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2254 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002255 }
Steve Narofffa465d12007-10-02 20:01:56 +00002256 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002257 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002258 ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002259}