blob: 976069e669d586f2f8bf3c3b7ebfd6fea44db63f [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff6a8a9a42007-10-02 20:01:56 +000017#include "clang/AST/DeclObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/Expr.h"
Steve Naroff563477d2007-09-18 23:55:05 +000019#include "clang/Parse/DeclSpec.h"
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner59907c42007-08-10 20:18:51 +000027#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29
Steve Narofff69936d2007-09-16 03:34:24 +000030/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +000037Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Carlssonee98ac52007-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()));
Reid Spencer5f016e22007-07-11 17:01:13 +000060
61 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
62 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlssonee98ac52007-10-15 02:50:23 +000063 Literal.AnyWide, t,
64 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +000065 StringToks[NumStringToks-1].getLocation());
66}
67
68
Steve Naroff08d92e42007-09-15 18:49:24 +000069/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +000070/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
71/// identifier is used in an function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +000072Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +000073 IdentifierInfo &II,
74 bool HasTrailingLParen) {
75 // Could be enum-constant or decl.
Steve Naroff8c9f13e2007-09-16 16:16:00 +000076 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff7779db42007-11-12 14:29:37 +000085 if (CurMethodDecl) {
86 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
87 ObjcInterfaceDecl *clsDeclared;
88 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared))
89 return new ObjCIvarRefExpr(IV, IV->getType(), Loc);
90 }
Reid Spencer5f016e22007-07-11 17:01:13 +000091 // If this name wasn't predeclared and if this is not a function call,
92 // diagnose the problem.
93 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
94 }
95 }
Steve Naroffe1223f72007-08-28 03:03:08 +000096 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroff53a32342007-08-28 18:45:29 +000097 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +000098 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +000099 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +0000101 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 if (isa<TypedefDecl>(D))
103 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
104
105 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +0000106 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +0000107}
108
Steve Narofff69936d2007-09-16 03:34:24 +0000109Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000110 tok::TokenKind Kind) {
111 PreDefinedExpr::IdentType IT;
112
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 switch (Kind) {
114 default:
115 assert(0 && "Unknown simple primary expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
Anders Carlsson22742662007-07-21 05:21:51 +0000117 IT = PreDefinedExpr::Func;
118 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000120 IT = PreDefinedExpr::Function;
121 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000123 IT = PreDefinedExpr::PrettyFunction;
124 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 }
Anders Carlsson22742662007-07-21 05:21:51 +0000126
127 // Pre-defined identifiers are always of type char *.
128 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000129}
130
Steve Narofff69936d2007-09-16 03:34:24 +0000131Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 llvm::SmallString<16> CharBuffer;
133 CharBuffer.resize(Tok.getLength());
134 const char *ThisTokBegin = &CharBuffer[0];
135 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
136
137 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
138 Tok.getLocation(), PP);
139 if (Literal.hadError())
140 return ExprResult(true);
141 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
142 Tok.getLocation());
143}
144
Steve Narofff69936d2007-09-16 03:34:24 +0000145Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 // fast path for a single digit (which is quite common). A single digit
147 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
148 if (Tok.getLength() == 1) {
149 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
150
Chris Lattner701e5eb2007-09-04 02:45:27 +0000151 unsigned IntSize = static_cast<unsigned>(
152 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
154 Context.IntTy,
155 Tok.getLocation()));
156 }
157 llvm::SmallString<512> IntegerBuffer;
158 IntegerBuffer.resize(Tok.getLength());
159 const char *ThisTokBegin = &IntegerBuffer[0];
160
161 // Get the spelling of the token, which eliminates trigraphs, etc.
162 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
163 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
164 Tok.getLocation(), PP);
165 if (Literal.hadError)
166 return ExprResult(true);
167
Chris Lattner5d661452007-08-26 03:42:43 +0000168 Expr *Res;
169
170 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000171 QualType Ty;
172 const llvm::fltSemantics *Format;
173 uint64_t Size; unsigned Align;
174
175 if (Literal.isFloat) {
176 Ty = Context.FloatTy;
177 Context.Target.getFloatInfo(Size, Align, Format, Tok.getLocation());
178 } else if (Literal.isLong) {
179 Ty = Context.LongDoubleTy;
180 Context.Target.getLongDoubleInfo(Size, Align, Format, Tok.getLocation());
181 } else {
182 Ty = Context.DoubleTy;
183 Context.Target.getDoubleInfo(Size, Align, Format, Tok.getLocation());
184 }
185
186 Res = new FloatingLiteral(Literal.GetFloatValue(*Format), Ty,
187 Tok.getLocation());
Chris Lattner5d661452007-08-26 03:42:43 +0000188 } else if (!Literal.isIntegerLiteral()) {
189 return ExprResult(true);
190 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 QualType t;
192
Neil Boothb9449512007-08-29 22:00:19 +0000193 // long long is a C99 feature.
194 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000195 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000196 Diag(Tok.getLocation(), diag::ext_longlong);
197
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 // Get the value in the widest-possible width.
199 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
200
201 if (Literal.GetIntegerValue(ResultVal)) {
202 // If this value didn't fit into uintmax_t, warn and force to ull.
203 Diag(Tok.getLocation(), diag::warn_integer_too_large);
204 t = Context.UnsignedLongLongTy;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000205 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 ResultVal.getBitWidth() && "long long is not intmax_t?");
207 } else {
208 // If this value fits into a ULL, try to figure out what else it fits into
209 // according to the rules of C99 6.4.4.1p5.
210
211 // Octal, Hexadecimal, and integers with a U suffix are allowed to
212 // be an unsigned int.
213 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
214
215 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner97c51562007-08-23 21:58:08 +0000216 if (!Literal.isLong && !Literal.isLongLong) {
217 // Are int/unsigned possibilities?
Chris Lattner701e5eb2007-09-04 02:45:27 +0000218 unsigned IntSize = static_cast<unsigned>(
219 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000220 // Does it fit in a unsigned int?
221 if (ResultVal.isIntN(IntSize)) {
222 // Does it fit in a signed int?
223 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
224 t = Context.IntTy;
225 else if (AllowUnsigned)
226 t = Context.UnsignedIntTy;
227 }
228
229 if (!t.isNull())
230 ResultVal.trunc(IntSize);
231 }
232
233 // Are long/unsigned long possibilities?
234 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000235 unsigned LongSize = static_cast<unsigned>(
236 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000237
238 // Does it fit in a unsigned long?
239 if (ResultVal.isIntN(LongSize)) {
240 // Does it fit in a signed long?
241 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
242 t = Context.LongTy;
243 else if (AllowUnsigned)
244 t = Context.UnsignedLongTy;
245 }
246 if (!t.isNull())
247 ResultVal.trunc(LongSize);
248 }
249
250 // Finally, check long long if needed.
251 if (t.isNull()) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000252 unsigned LongLongSize = static_cast<unsigned>(
253 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000254
255 // Does it fit in a unsigned long long?
256 if (ResultVal.isIntN(LongLongSize)) {
257 // Does it fit in a signed long long?
258 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
259 t = Context.LongLongTy;
260 else if (AllowUnsigned)
261 t = Context.UnsignedLongLongTy;
262 }
263 }
264
265 // If we still couldn't decide a type, we probably have something that
266 // does not fit in a signed long long, but has no U suffix.
267 if (t.isNull()) {
268 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
269 t = Context.UnsignedLongLongTy;
270 }
271 }
272
Chris Lattner5d661452007-08-26 03:42:43 +0000273 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 }
Chris Lattner5d661452007-08-26 03:42:43 +0000275
276 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
277 if (Literal.isImaginary)
278 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
279
280 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000281}
282
Steve Narofff69936d2007-09-16 03:34:24 +0000283Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 ExprTy *Val) {
285 Expr *e = (Expr *)Val;
Steve Narofff69936d2007-09-16 03:34:24 +0000286 assert((e != 0) && "ActOnParenExpr() missing expr");
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 return new ParenExpr(L, R, e);
288}
289
290/// The UsualUnaryConversions() function is *not* called by this routine.
291/// See C99 6.3.2.1p[2-4] for more details.
292QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
293 SourceLocation OpLoc, bool isSizeof) {
294 // C99 6.5.3.4p1:
295 if (isa<FunctionType>(exprType) && isSizeof)
296 // alignof(function) is allowed.
297 Diag(OpLoc, diag::ext_sizeof_function_type);
298 else if (exprType->isVoidType())
299 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
300 else if (exprType->isIncompleteType()) {
301 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
302 diag::err_alignof_incomplete_type,
303 exprType.getAsString());
304 return QualType(); // error
305 }
306 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
307 return Context.getSizeType();
308}
309
310Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000311ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 SourceLocation LPLoc, TypeTy *Ty,
313 SourceLocation RPLoc) {
314 // If error parsing type, ignore.
315 if (Ty == 0) return true;
316
317 // Verify that this is a valid expression.
318 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
319
320 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
321
322 if (resultType.isNull())
323 return true;
324 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
325}
326
Chris Lattner5d794252007-08-24 21:41:10 +0000327QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000328 DefaultFunctionArrayConversion(V);
329
Chris Lattnercc26ed72007-08-26 05:39:26 +0000330 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000331 if (const ComplexType *CT = V->getType()->getAsComplexType())
332 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000333
334 // Otherwise they pass through real integer and floating point types here.
335 if (V->getType()->isArithmeticType())
336 return V->getType();
337
338 // Reject anything else.
339 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
340 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000341}
342
343
Reid Spencer5f016e22007-07-11 17:01:13 +0000344
Steve Narofff69936d2007-09-16 03:34:24 +0000345Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 tok::TokenKind Kind,
347 ExprTy *Input) {
348 UnaryOperator::Opcode Opc;
349 switch (Kind) {
350 default: assert(0 && "Unknown unary op!");
351 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
352 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
353 }
354 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
355 if (result.isNull())
356 return true;
357 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
358}
359
360Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000361ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000363 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000364
365 // Perform default conversions.
366 DefaultFunctionArrayConversion(LHSExp);
367 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000368
Chris Lattner12d9ff62007-07-16 00:14:47 +0000369 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000370
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000372 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 // in the subscript position. As a result, we need to derive the array base
374 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000375 Expr *BaseExpr, *IndexExpr;
376 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000377 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000378 BaseExpr = LHSExp;
379 IndexExpr = RHSExp;
380 // FIXME: need to deal with const...
381 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000382 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000383 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000384 BaseExpr = RHSExp;
385 IndexExpr = LHSExp;
386 // FIXME: need to deal with const...
387 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000388 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
389 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000390 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000391
392 // Component access limited to variables (reject vec4.rg[1]).
393 if (!isa<DeclRefExpr>(BaseExpr))
394 return Diag(LLoc, diag::err_ocuvector_component_access,
395 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000396 // FIXME: need to deal with const...
397 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000399 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
400 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 }
402 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000403 if (!IndexExpr->getType()->isIntegerType())
404 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
405 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000406
Chris Lattner12d9ff62007-07-16 00:14:47 +0000407 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
408 // the following check catches trying to index a pointer to a function (e.g.
409 // void (*)(int)). Functions are not objects in C99.
410 if (!ResultType->isObjectType())
411 return Diag(BaseExpr->getLocStart(),
412 diag::err_typecheck_subscript_not_object,
413 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
414
415 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000416}
417
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000418QualType Sema::
419CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
420 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnerc8629632007-07-31 19:29:30 +0000421 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000422
423 // The vector accessor can't exceed the number of elements.
424 const char *compStr = CompName.getName();
425 if (strlen(compStr) > vecType->getNumElements()) {
426 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
427 baseType.getAsString(), SourceRange(CompLoc));
428 return QualType();
429 }
430 // The component names must come from the same set.
Chris Lattner88dca042007-08-02 22:33:49 +0000431 if (vecType->getPointAccessorIdx(*compStr) != -1) {
432 do
433 compStr++;
434 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
435 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
436 do
437 compStr++;
438 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
439 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
440 do
441 compStr++;
442 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
443 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000444
445 if (*compStr) {
446 // We didn't get to the end of the string. This means the component names
447 // didn't come from the same set *or* we encountered an illegal name.
448 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
449 std::string(compStr,compStr+1), SourceRange(CompLoc));
450 return QualType();
451 }
452 // Each component accessor can't exceed the vector type.
453 compStr = CompName.getName();
454 while (*compStr) {
455 if (vecType->isAccessorWithinNumElements(*compStr))
456 compStr++;
457 else
458 break;
459 }
460 if (*compStr) {
461 // We didn't get to the end of the string. This means a component accessor
462 // exceeds the number of elements in the vector.
463 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
464 baseType.getAsString(), SourceRange(CompLoc));
465 return QualType();
466 }
467 // The component accessor looks fine - now we need to compute the actual type.
468 // The vector type is implied by the component accessor. For example,
469 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
470 unsigned CompSize = strlen(CompName.getName());
471 if (CompSize == 1)
472 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000473
474 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
475 // Now look up the TypeDefDecl from the vector type. Without this,
476 // diagostics look bad. We want OCU vector types to appear built-in.
477 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
478 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
479 return Context.getTypedefType(OCUVectorDecls[i]);
480 }
481 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000482}
483
Reid Spencer5f016e22007-07-11 17:01:13 +0000484Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000485ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 tok::TokenKind OpKind, SourceLocation MemberLoc,
487 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000488 Expr *BaseExpr = static_cast<Expr *>(Base);
489 assert(BaseExpr && "no record expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000490
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000491 QualType BaseType = BaseExpr->getType();
492 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000493
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000495 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000496 BaseType = PT->getPointeeType();
497 else
498 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
499 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000501 // The base type is either a record or an OCUVectorType.
Chris Lattnerc8629632007-07-31 19:29:30 +0000502 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000503 RecordDecl *RDecl = RTy->getDecl();
504 if (RTy->isIncompleteType())
505 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
506 BaseExpr->getSourceRange());
507 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000508 FieldDecl *MemberDecl = RDecl->getMember(&Member);
509 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000510 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
511 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000512 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
513 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff608e0ee2007-08-03 22:40:33 +0000514 // Component access limited to variables (reject vec4.rg.g).
515 if (!isa<DeclRefExpr>(BaseExpr))
516 return Diag(OpLoc, diag::err_ocuvector_component_access,
517 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000518 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
519 if (ret.isNull())
520 return true;
Chris Lattner6481a572007-08-03 17:31:20 +0000521 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000522 } else if (BaseType->isObjcInterfaceType()) {
523 ObjcInterfaceDecl *IFace;
524 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
525 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
526 else
527 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)
528 ->getInterfaceType()->getDecl();
529 ObjcInterfaceDecl *clsDeclared;
530 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
531 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
532 OpKind==tok::arrow);
533 }
534 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
535 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000536}
537
Steve Narofff69936d2007-09-16 03:34:24 +0000538/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000539/// This provides the location of the left/right parens and a list of comma
540/// locations.
541Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000542ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner74c469f2007-07-21 03:03:59 +0000543 ExprTy **args, unsigned NumArgsInCall,
Reid Spencer5f016e22007-07-11 17:01:13 +0000544 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000545 Expr *Fn = static_cast<Expr *>(fn);
546 Expr **Args = reinterpret_cast<Expr**>(args);
547 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000548
Chris Lattner74c469f2007-07-21 03:03:59 +0000549 UsualUnaryConversions(Fn);
550 QualType funcType = Fn->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000551
552 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
553 // type pointer to function".
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000554 const PointerType *PT = funcType->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000556 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
557 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000558
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000559 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 if (funcT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000561 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
562 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000563
564 // If a prototype isn't declared, the parser implicitly defines a func decl
565 QualType resultType = funcT->getResultType();
566
567 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
568 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
569 // assignment, to the types of the corresponding parameter, ...
570
571 unsigned NumArgsInProto = proto->getNumArgs();
572 unsigned NumArgsToCheck = NumArgsInCall;
573
574 if (NumArgsInCall < NumArgsInProto)
575 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
Chris Lattner74c469f2007-07-21 03:03:59 +0000576 Fn->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 else if (NumArgsInCall > NumArgsInProto) {
578 if (!proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000579 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000580 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000581 SourceRange(Args[NumArgsInProto]->getLocStart(),
582 Args[NumArgsInCall-1]->getLocEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 }
584 NumArgsToCheck = NumArgsInProto;
585 }
586 // Continue to check argument types (even if we have too few/many args).
587 for (unsigned i = 0; i < NumArgsToCheck; i++) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000588 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000589 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000590
591 QualType lhsType = proto->getArgType(i);
592 QualType rhsType = argExpr->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000593
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000594 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnerc8629632007-07-31 19:29:30 +0000595 if (const ArrayType *ary = lhsType->getAsArrayType())
Steve Naroff700204c2007-07-24 21:46:40 +0000596 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000597 else if (lhsType->isFunctionType())
Steve Naroff700204c2007-07-24 21:46:40 +0000598 lhsType = Context.getPointerType(lhsType);
599
Steve Naroff90045e82007-07-13 23:32:42 +0000600 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
601 argExpr);
Steve Narofff1120de2007-08-24 22:33:52 +0000602 if (Args[i] != argExpr) // The expression was converted.
603 Args[i] = argExpr; // Make sure we store the converted expression.
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 SourceLocation l = argExpr->getLocStart();
605
606 // decode the result (notice that AST's are still created for extensions).
607 switch (result) {
608 case Compatible:
609 break;
610 case PointerFromInt:
611 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +0000612 if (!argExpr->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000613 Diag(l, diag::ext_typecheck_passing_pointer_int,
614 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000615 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000616 }
617 break;
618 case IntFromPointer:
619 Diag(l, diag::ext_typecheck_passing_pointer_int,
620 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000621 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 break;
623 case IncompatiblePointer:
624 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
625 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000626 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000627 break;
628 case CompatiblePointerDiscardsQualifiers:
629 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
630 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000631 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 break;
633 case Incompatible:
634 return Diag(l, diag::err_typecheck_passing_incompatible,
635 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000636 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000637 }
638 }
Steve Naroffb291ab62007-08-28 23:30:39 +0000639 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
640 // Promote the arguments (C99 6.5.2.2p7).
641 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
642 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000643 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffb291ab62007-08-28 23:30:39 +0000644
645 DefaultArgumentPromotion(argExpr);
646 if (Args[i] != argExpr) // The expression was converted.
647 Args[i] = argExpr; // Make sure we store the converted expression.
648 }
649 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
650 // Even if the types checked, bail if the number of arguments don't match.
Reid Spencer5f016e22007-07-11 17:01:13 +0000651 return true;
Steve Naroffb291ab62007-08-28 23:30:39 +0000652 }
653 } else if (isa<FunctionTypeNoProto>(funcT)) {
654 // Promote the arguments (C99 6.5.2.2p6).
655 for (unsigned i = 0; i < NumArgsInCall; i++) {
656 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000657 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffb291ab62007-08-28 23:30:39 +0000658
659 DefaultArgumentPromotion(argExpr);
660 if (Args[i] != argExpr) // The expression was converted.
661 Args[i] = argExpr; // Make sure we store the converted expression.
662 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000663 }
Chris Lattner59907c42007-08-10 20:18:51 +0000664 // Do special checking on direct calls to functions.
665 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
666 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
667 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000668 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
669 NumArgsInCall))
Anders Carlsson71993dd2007-08-17 05:31:46 +0000670 return true;
Chris Lattner59907c42007-08-10 20:18:51 +0000671
Chris Lattner74c469f2007-07-21 03:03:59 +0000672 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000673}
674
675Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000676ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000677 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +0000678 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +0000679 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000680 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +0000681 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +0000682 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000683
684 // FIXME: add semantic analysis (C99 6.5.2.5).
Steve Naroffaff1edd2007-07-19 21:32:11 +0000685 return new CompoundLiteralExpr(literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000686}
687
688Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000689ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000690 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +0000691 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000692
Steve Naroff08d92e42007-09-15 18:49:24 +0000693 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +0000694 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000695
Steve Naroff38374b02007-09-02 20:30:18 +0000696 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
697 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
698 return e;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000699}
700
701Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000702ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +0000704 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +0000705
706 Expr *castExpr = static_cast<Expr*>(Op);
707 QualType castType = QualType::getFromOpaquePtr(Ty);
708
Steve Naroff711602b2007-08-31 00:32:44 +0000709 UsualUnaryConversions(castExpr);
710
Chris Lattner75af4802007-07-18 16:00:06 +0000711 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
712 // type needs to be scalar.
Chris Lattner3da2db42007-10-29 04:26:44 +0000713 if (!castType->isVoidType()) { // Cast to void allows any expr type.
714 if (!castType->isScalarType())
715 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
716 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
717 if (!castExpr->getType()->isScalarType()) {
718 return Diag(castExpr->getLocStart(),
719 diag::err_typecheck_expect_scalar_operand,
720 castExpr->getType().getAsString(),castExpr->getSourceRange());
721 }
Steve Naroff16beff82007-07-16 23:25:18 +0000722 }
723 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000724}
725
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000726// promoteExprToType - a helper function to ensure we create exactly one
727// ImplicitCastExpr.
728static void promoteExprToType(Expr *&expr, QualType type) {
729 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
730 impCast->setType(type);
731 else
732 expr = new ImplicitCastExpr(type, expr);
733 return;
734}
735
Reid Spencer5f016e22007-07-11 17:01:13 +0000736inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000737 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000738 UsualUnaryConversions(cond);
739 UsualUnaryConversions(lex);
740 UsualUnaryConversions(rex);
741 QualType condT = cond->getType();
742 QualType lexT = lex->getType();
743 QualType rexT = rex->getType();
744
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000746 if (!condT->isScalarType()) { // C99 6.5.15p2
747 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
748 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 return QualType();
750 }
751 // now check the two expressions.
Steve Naroffa4332e22007-07-17 00:58:39 +0000752 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
753 UsualArithmeticConversions(lex, rex);
754 return lex->getType();
755 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000756 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
757 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
758
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000759 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000760 return lexT;
761
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000763 lexT.getAsString(), rexT.getAsString(),
764 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 return QualType();
766 }
767 }
Chris Lattner590b6642007-07-15 23:26:56 +0000768 // C99 6.5.15p3
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000769 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
770 promoteExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000771 return lexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000772 }
773 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
774 promoteExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000775 return rexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000776 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000777 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
778 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
779 // get the "pointed to" types
780 QualType lhptee = LHSPT->getPointeeType();
781 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000782
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000783 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
784 if (lhptee->isVoidType() &&
785 (rhptee->isObjectType() || rhptee->isIncompleteType()))
786 return lexT;
787 if (rhptee->isVoidType() &&
788 (lhptee->isObjectType() || lhptee->isIncompleteType()))
789 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000790
Steve Naroffec0550f2007-10-15 20:41:53 +0000791 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
792 rhptee.getUnqualifiedType())) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000793 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
794 lexT.getAsString(), rexT.getAsString(),
795 lex->getSourceRange(), rex->getSourceRange());
796 return lexT; // FIXME: this is an _ext - is this return o.k?
797 }
798 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000799 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
800 // differently qualified versions of compatible types, the result type is
801 // a pointer to an appropriately qualified version of the *composite*
802 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000803 return lexT; // FIXME: Need to return the composite type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 }
805 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000806
Steve Naroff49b45262007-07-13 16:58:59 +0000807 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
808 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000809
810 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000811 lexT.getAsString(), rexT.getAsString(),
812 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 return QualType();
814}
815
Steve Narofff69936d2007-09-16 03:34:24 +0000816/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +0000817/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +0000818Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000819 SourceLocation ColonLoc,
820 ExprTy *Cond, ExprTy *LHS,
821 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000822 Expr *CondExpr = (Expr *) Cond;
823 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
824 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
825 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000826 if (result.isNull())
827 return true;
Chris Lattner26824902007-07-16 21:39:03 +0000828 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000829}
830
Steve Naroffb291ab62007-08-28 23:30:39 +0000831/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
832/// do not have a prototype. Integer promotions are performed on each
833/// argument, and arguments that have type float are promoted to double.
834void Sema::DefaultArgumentPromotion(Expr *&expr) {
835 QualType t = expr->getType();
836 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
837
838 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
839 promoteExprToType(expr, Context.IntTy);
840 if (t == Context.FloatTy)
841 promoteExprToType(expr, Context.DoubleTy);
842}
843
Steve Narofffa2eaab2007-07-15 02:02:06 +0000844/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000845void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000846 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000847 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000848
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000849 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000850 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
851 t = e->getType();
852 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000853 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000854 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnerc8629632007-07-31 19:29:30 +0000855 else if (const ArrayType *ary = t->getAsArrayType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000856 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000857}
858
859/// UsualUnaryConversion - Performs various conversions that are common to most
860/// operators (C99 6.3). The conversions of array and function types are
861/// sometimes surpressed. For example, the array->pointer conversion doesn't
862/// apply if the array is an argument to the sizeof or address (&) operators.
863/// In these instances, this routine should *not* be called.
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000864void Sema::UsualUnaryConversions(Expr *&expr) {
Steve Naroff49b45262007-07-13 16:58:59 +0000865 QualType t = expr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 assert(!t.isNull() && "UsualUnaryConversions - missing type");
867
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000868 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000869 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
870 t = expr->getType();
871 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000872 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000873 promoteExprToType(expr, Context.IntTy);
874 else
875 DefaultFunctionArrayConversion(expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000876}
877
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000878/// UsualArithmeticConversions - Performs various conversions that are common to
Reid Spencer5f016e22007-07-11 17:01:13 +0000879/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
880/// routine returns the first non-arithmetic type found. The client is
881/// responsible for emitting appropriate error diagnostics.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000882QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
883 bool isCompAssign) {
Steve Naroff8702a0f2007-08-25 19:54:59 +0000884 if (!isCompAssign) {
885 UsualUnaryConversions(lhsExpr);
886 UsualUnaryConversions(rhsExpr);
887 }
Steve Naroff3187e202007-10-18 18:55:53 +0000888 // For conversion purposes, we ignore any qualifiers.
889 // For example, "const float" and "float" are equivalent.
Steve Narofff68a63f2007-11-10 19:45:54 +0000890 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
891 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000892
893 // If both types are identical, no conversion is needed.
Steve Naroff3187e202007-10-18 18:55:53 +0000894 if (lhs == rhs)
895 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000896
897 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
898 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000899 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000900 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000901
902 // At this point, we have two different arithmetic types.
903
904 // Handle complex types first (C99 6.3.1.8p1).
905 if (lhs->isComplexType() || rhs->isComplexType()) {
906 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000907 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000908 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
909 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000910 }
911 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000912 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
913 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000914 }
Steve Narofff1448a02007-08-27 01:27:54 +0000915 // This handles complex/complex, complex/float, or float/complex.
916 // When both operands are complex, the shorter operand is converted to the
917 // type of the longer, and that is the type of the result. This corresponds
918 // to what is done when combining two real floating-point operands.
919 // The fun begins when size promotion occur across type domains.
920 // From H&S 6.3.4: When one operand is complex and the other is a real
921 // floating-point type, the less precise type is converted, within it's
922 // real or complex domain, to the precision of the other type. For example,
923 // when combining a "long double" with a "double _Complex", the
924 // "double _Complex" is promoted to "long double _Complex".
Steve Narofffb0d4962007-08-27 15:30:22 +0000925 int result = Context.compareFloatingType(lhs, rhs);
926
927 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff55fe4552007-08-27 21:32:55 +0000928 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
929 if (!isCompAssign)
930 promoteExprToType(rhsExpr, rhs);
931 } else if (result < 0) { // The right side is bigger, convert lhs.
932 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
933 if (!isCompAssign)
934 promoteExprToType(lhsExpr, lhs);
935 }
936 // At this point, lhs and rhs have the same rank/size. Now, make sure the
937 // domains match. This is a requirement for our implementation, C99
938 // does not require this promotion.
939 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
940 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff29960362007-08-27 21:43:43 +0000941 if (!isCompAssign)
942 promoteExprToType(lhsExpr, rhs);
943 return rhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000944 } else { // handle "_Complex double, double".
Steve Naroff29960362007-08-27 21:43:43 +0000945 if (!isCompAssign)
946 promoteExprToType(rhsExpr, lhs);
947 return lhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000948 }
Steve Naroffa4332e22007-07-17 00:58:39 +0000949 }
Steve Naroff29960362007-08-27 21:43:43 +0000950 return lhs; // The domain/size match exactly.
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000952 // Now handle "real" floating types (i.e. float, double, long double).
953 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
954 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000955 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000956 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
957 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000958 }
959 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000960 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
961 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000962 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000963 // We have two real floating types, float/complex combos were handled above.
964 // Convert the smaller operand to the bigger result.
Steve Narofffb0d4962007-08-27 15:30:22 +0000965 int result = Context.compareFloatingType(lhs, rhs);
966
967 if (result > 0) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000968 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
969 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000970 }
Steve Narofffb0d4962007-08-27 15:30:22 +0000971 if (result < 0) { // convert the lhs
972 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
973 return rhs;
974 }
975 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000977 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +0000978 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000979 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
980 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000981 }
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000982 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
983 return rhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000984}
985
986// CheckPointerTypesForAssignment - This is a very tricky routine (despite
987// being closely modeled after the C99 spec:-). The odd characteristic of this
988// routine is it effectively iqnores the qualifiers on the top level pointee.
989// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
990// FIXME: add a couple examples in this comment.
991Sema::AssignmentCheckResult
992Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
993 QualType lhptee, rhptee;
994
995 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000996 lhptee = lhsType->getAsPointerType()->getPointeeType();
997 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000998
999 // make sure we operate on the canonical type
1000 lhptee = lhptee.getCanonicalType();
1001 rhptee = rhptee.getCanonicalType();
1002
1003 AssignmentCheckResult r = Compatible;
1004
1005 // C99 6.5.16.1p1: This following citation is common to constraints
1006 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1007 // qualifiers of the type *pointed to* by the right;
1008 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1009 rhptee.getQualifiers())
1010 r = CompatiblePointerDiscardsQualifiers;
1011
1012 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1013 // incomplete type and the other is a pointer to a qualified or unqualified
1014 // version of void...
1015 if (lhptee.getUnqualifiedType()->isVoidType() &&
1016 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1017 ;
1018 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1019 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1020 ;
1021 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1022 // unqualified versions of compatible types, ...
Steve Naroffec0550f2007-10-15 20:41:53 +00001023 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1024 rhptee.getUnqualifiedType()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001025 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1026 return r;
1027}
1028
1029/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1030/// has code to accommodate several GCC extensions when type checking
1031/// pointers. Here are some objectionable examples that GCC considers warnings:
1032///
1033/// int a, *pint;
1034/// short *pshort;
1035/// struct foo *pfoo;
1036///
1037/// pint = pshort; // warning: assignment from incompatible pointer type
1038/// a = pint; // warning: assignment makes integer from pointer without a cast
1039/// pint = a; // warning: assignment makes pointer from integer without a cast
1040/// pint = pfoo; // warning: assignment from incompatible pointer type
1041///
1042/// As a result, the code for dealing with pointers is more complex than the
1043/// C99 spec dictates.
1044/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1045///
1046Sema::AssignmentCheckResult
1047Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroff8eabdff2007-11-13 00:31:42 +00001048 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1049 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattner84d35ce2007-10-29 05:15:40 +00001050 return Compatible; // common case, fast path...
Steve Naroff700204c2007-07-24 21:46:40 +00001051
Anders Carlsson793680e2007-10-12 23:56:29 +00001052 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001053 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001054 return Compatible;
1055 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1057 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1058 return Incompatible;
1059 }
1060 return Compatible;
1061 } else if (lhsType->isPointerType()) {
1062 if (rhsType->isIntegerType())
1063 return PointerFromInt;
1064
1065 if (rhsType->isPointerType())
1066 return CheckPointerTypesForAssignment(lhsType, rhsType);
1067 } else if (rhsType->isPointerType()) {
1068 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1069 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1070 return IntFromPointer;
1071
1072 if (lhsType->isPointerType())
1073 return CheckPointerTypesForAssignment(lhsType, rhsType);
1074 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001075 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001077 }
1078 return Incompatible;
1079}
1080
Steve Naroff90045e82007-07-13 23:32:42 +00001081Sema::AssignmentCheckResult
1082Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Chris Lattner943140e2007-10-16 02:55:40 +00001083 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001084 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001085 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001086 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001087 //
1088 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1089 // are better understood.
1090 if (!lhsType->isReferenceType())
1091 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001092
1093 Sema::AssignmentCheckResult result;
Steve Naroff90045e82007-07-13 23:32:42 +00001094
Steve Narofff1120de2007-08-24 22:33:52 +00001095 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1096
1097 // C99 6.5.16.1p2: The value of the right operand is converted to the
1098 // type of the assignment expression.
1099 if (rExpr->getType() != lhsType)
1100 promoteExprToType(rExpr, lhsType);
1101 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001102}
1103
1104Sema::AssignmentCheckResult
1105Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1106 return CheckAssignmentConstraints(lhsType, rhsType);
1107}
1108
Steve Naroff49b45262007-07-13 16:58:59 +00001109inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001110 Diag(loc, diag::err_typecheck_invalid_operands,
1111 lex->getType().getAsString(), rex->getType().getAsString(),
1112 lex->getSourceRange(), rex->getSourceRange());
1113}
1114
Steve Naroff49b45262007-07-13 16:58:59 +00001115inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1116 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 QualType lhsType = lex->getType(), rhsType = rex->getType();
1118
1119 // make sure the vector types are identical.
1120 if (lhsType == rhsType)
1121 return lhsType;
1122 // You cannot convert between vector values of different size.
1123 Diag(loc, diag::err_typecheck_vector_not_convertable,
1124 lex->getType().getAsString(), rex->getType().getAsString(),
1125 lex->getSourceRange(), rex->getSourceRange());
1126 return QualType();
1127}
1128
1129inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001130 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001131{
Steve Naroff90045e82007-07-13 23:32:42 +00001132 QualType lhsType = lex->getType(), rhsType = rex->getType();
1133
1134 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001136
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001137 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001138
Steve Naroffa4332e22007-07-17 00:58:39 +00001139 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001140 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 InvalidOperands(loc, lex, rex);
1142 return QualType();
1143}
1144
1145inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001146 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001147{
Steve Naroff90045e82007-07-13 23:32:42 +00001148 QualType lhsType = lex->getType(), rhsType = rex->getType();
1149
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001150 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001151
Steve Naroffa4332e22007-07-17 00:58:39 +00001152 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001153 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001154 InvalidOperands(loc, lex, rex);
1155 return QualType();
1156}
1157
1158inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001159 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001160{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001161 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001162 return CheckVectorOperands(loc, lex, rex);
1163
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001164 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Steve Naroff3e5e5562007-07-16 22:23:01 +00001165
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001167 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001168 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001169
Steve Naroffa4332e22007-07-17 00:58:39 +00001170 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1171 return lex->getType();
1172 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1173 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 InvalidOperands(loc, lex, rex);
1175 return QualType();
1176}
1177
1178inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001179 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001180{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001181 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001182 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001183
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001184 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001185
1186 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001187 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001188 return compType;
Steve Naroff3e5e5562007-07-16 22:23:01 +00001189
1190 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001191 return compType;
Steve Naroff3e5e5562007-07-16 22:23:01 +00001192 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
Chris Lattner8b9023b2007-07-13 03:05:23 +00001193 return Context.getPointerDiffType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 InvalidOperands(loc, lex, rex);
1195 return QualType();
1196}
1197
1198inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001199 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001200{
1201 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1202 // for int << longlong -> the result type should be int, not long long.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001203 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001204
Steve Naroffa4332e22007-07-17 00:58:39 +00001205 // handle the common case first (both operands are arithmetic).
1206 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001207 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 InvalidOperands(loc, lex, rex);
1209 return QualType();
1210}
1211
Ted Kremeneke780f0d2007-10-29 16:45:23 +00001212// Utility method to plow through parentheses to get the first nested
1213// non-ParenExpr expr.
1214static inline Expr* IgnoreParen(Expr* E) {
Ted Kremenek59092d02007-10-30 21:03:09 +00001215 while (ParenExpr* P = dyn_cast<ParenExpr>(E))
1216 E = P->getSubExpr();
Ted Kremeneke780f0d2007-10-29 16:45:23 +00001217
1218 return E;
1219}
1220
Chris Lattnera5937dd2007-08-26 01:18:55 +00001221inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1222 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Reid Spencer5f016e22007-07-11 17:01:13 +00001223{
Chris Lattnera5937dd2007-08-26 01:18:55 +00001224 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001225 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1226 UsualArithmeticConversions(lex, rex);
1227 else {
1228 UsualUnaryConversions(lex);
1229 UsualUnaryConversions(rex);
1230 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001231 QualType lType = lex->getType();
1232 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001233
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001234
1235 // For non-floating point types, check for self-comparisons of the form
1236 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1237 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001238 if (!lType->isFloatingType()) {
1239 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1240 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1241 if (DRL->getDecl() == DRR->getDecl())
1242 Diag(loc, diag::warn_selfcomparison);
1243 }
1244
Chris Lattnera5937dd2007-08-26 01:18:55 +00001245 if (isRelational) {
1246 if (lType->isRealType() && rType->isRealType())
1247 return Context.IntTy;
1248 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001249 // Check for comparisons of floating point operands using != and ==.
1250 // Issue a warning if these are no self-comparisons, as they are not likely
1251 // to do what the programmer intended.
1252 if (lType->isFloatingType()) {
1253 assert (rType->isFloatingType());
1254
Ted Kremenek6a261552007-10-29 16:40:01 +00001255 // Special case: check for x == x (which is OK).
1256 bool EmitWarning = true;
1257
Ted Kremeneke780f0d2007-10-29 16:45:23 +00001258 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1259 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
Ted Kremenek6a261552007-10-29 16:40:01 +00001260 if (DRL->getDecl() == DRR->getDecl())
1261 EmitWarning = false;
1262
1263 if (EmitWarning)
1264 Diag(loc, diag::warn_floatingpoint_eq);
1265 }
1266
Chris Lattnera5937dd2007-08-26 01:18:55 +00001267 if (lType->isArithmeticType() && rType->isArithmeticType())
1268 return Context.IntTy;
1269 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001270
Chris Lattnerd28f8152007-08-26 01:10:14 +00001271 bool LHSIsNull = lex->isNullPointerConstant(Context);
1272 bool RHSIsNull = rex->isNullPointerConstant(Context);
1273
Chris Lattnera5937dd2007-08-26 01:18:55 +00001274 // All of the following pointer related warnings are GCC extensions, except
1275 // when handling null pointer constants. One day, we can consider making them
1276 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001277 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerd28f8152007-08-26 01:10:14 +00001278 if (!LHSIsNull && !RHSIsNull &&
Steve Naroffec0550f2007-10-15 20:41:53 +00001279 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1280 rType.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001281 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1282 lType.getAsString(), rType.getAsString(),
1283 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 }
Chris Lattnerd28f8152007-08-26 01:10:14 +00001285 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001286 return Context.IntTy;
1287 }
1288 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001289 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001290 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1291 lType.getAsString(), rType.getAsString(),
1292 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001293 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001294 return Context.IntTy;
1295 }
1296 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001297 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001298 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1299 lType.getAsString(), rType.getAsString(),
1300 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001301 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001302 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001303 }
1304 InvalidOperands(loc, lex, rex);
1305 return QualType();
1306}
1307
Reid Spencer5f016e22007-07-11 17:01:13 +00001308inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001309 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001310{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001311 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001313
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001314 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001315
Steve Naroffa4332e22007-07-17 00:58:39 +00001316 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001317 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 InvalidOperands(loc, lex, rex);
1319 return QualType();
1320}
1321
1322inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001323 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001324{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001325 UsualUnaryConversions(lex);
1326 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001327
Steve Naroffa4332e22007-07-17 00:58:39 +00001328 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 return Context.IntTy;
1330 InvalidOperands(loc, lex, rex);
1331 return QualType();
1332}
1333
1334inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001335 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001336{
1337 QualType lhsType = lex->getType();
1338 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1339 bool hadError = false;
1340 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1341
1342 switch (mlval) { // C99 6.5.16p2
1343 case Expr::MLV_Valid:
1344 break;
1345 case Expr::MLV_ConstQualified:
1346 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1347 hadError = true;
1348 break;
1349 case Expr::MLV_ArrayType:
1350 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1351 lhsType.getAsString(), lex->getSourceRange());
1352 return QualType();
1353 case Expr::MLV_NotObjectType:
1354 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1355 lhsType.getAsString(), lex->getSourceRange());
1356 return QualType();
1357 case Expr::MLV_InvalidExpression:
1358 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1359 lex->getSourceRange());
1360 return QualType();
1361 case Expr::MLV_IncompleteType:
1362 case Expr::MLV_IncompleteVoidType:
1363 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1364 lhsType.getAsString(), lex->getSourceRange());
1365 return QualType();
Steve Narofffec0b492007-07-30 03:29:09 +00001366 case Expr::MLV_DuplicateVectorComponents:
1367 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1368 lex->getSourceRange());
1369 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 }
Steve Naroff90045e82007-07-13 23:32:42 +00001371 AssignmentCheckResult result;
1372
1373 if (compoundType.isNull())
1374 result = CheckSingleAssignmentConstraints(lhsType, rex);
1375 else
1376 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001377
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 // decode the result (notice that extensions still return a type).
1379 switch (result) {
1380 case Compatible:
1381 break;
1382 case Incompatible:
1383 Diag(loc, diag::err_typecheck_assign_incompatible,
1384 lhsType.getAsString(), rhsType.getAsString(),
1385 lex->getSourceRange(), rex->getSourceRange());
1386 hadError = true;
1387 break;
1388 case PointerFromInt:
1389 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +00001390 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1392 lhsType.getAsString(), rhsType.getAsString(),
1393 lex->getSourceRange(), rex->getSourceRange());
1394 }
1395 break;
1396 case IntFromPointer:
1397 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1398 lhsType.getAsString(), rhsType.getAsString(),
1399 lex->getSourceRange(), rex->getSourceRange());
1400 break;
1401 case IncompatiblePointer:
1402 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1403 lhsType.getAsString(), rhsType.getAsString(),
1404 lex->getSourceRange(), rex->getSourceRange());
1405 break;
1406 case CompatiblePointerDiscardsQualifiers:
1407 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1408 lhsType.getAsString(), rhsType.getAsString(),
1409 lex->getSourceRange(), rex->getSourceRange());
1410 break;
1411 }
1412 // C99 6.5.16p3: The type of an assignment expression is the type of the
1413 // left operand unless the left operand has qualified type, in which case
1414 // it is the unqualified version of the type of the left operand.
1415 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1416 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001417 // C++ 5.17p1: the type of the assignment expression is that of its left
1418 // oprdu.
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 return hadError ? QualType() : lhsType.getUnqualifiedType();
1420}
1421
1422inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001423 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001424 UsualUnaryConversions(rex);
1425 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001426}
1427
Steve Naroff49b45262007-07-13 16:58:59 +00001428/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1429/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001430QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001431 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 assert(!resType.isNull() && "no type for increment/decrement expression");
1433
Steve Naroff084f9ed2007-08-24 17:20:07 +00001434 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00001435 if (const PointerType *pt = resType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001436 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1437 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1438 resType.getAsString(), op->getSourceRange());
1439 return QualType();
1440 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001441 } else if (!resType->isRealType()) {
1442 if (resType->isComplexType())
1443 // C99 does not support ++/-- on complex types.
1444 Diag(OpLoc, diag::ext_integer_increment_complex,
1445 resType.getAsString(), op->getSourceRange());
1446 else {
1447 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1448 resType.getAsString(), op->getSourceRange());
1449 return QualType();
1450 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001452 // At this point, we know we have a real, complex or pointer type.
1453 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1455 if (mlval != Expr::MLV_Valid) {
1456 // FIXME: emit a more precise diagnostic...
1457 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1458 op->getSourceRange());
1459 return QualType();
1460 }
1461 return resType;
1462}
1463
1464/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1465/// This routine allows us to typecheck complex/recursive expressions
1466/// where the declaration is needed for type checking. Here are some
1467/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1468static Decl *getPrimaryDeclaration(Expr *e) {
1469 switch (e->getStmtClass()) {
1470 case Stmt::DeclRefExprClass:
1471 return cast<DeclRefExpr>(e)->getDecl();
1472 case Stmt::MemberExprClass:
1473 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1474 case Stmt::ArraySubscriptExprClass:
1475 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1476 case Stmt::CallExprClass:
1477 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1478 case Stmt::UnaryOperatorClass:
1479 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1480 case Stmt::ParenExprClass:
1481 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1482 default:
1483 return 0;
1484 }
1485}
1486
1487/// CheckAddressOfOperand - The operand of & must be either a function
1488/// designator or an lvalue designating an object. If it is an lvalue, the
1489/// object cannot be declared with storage class register or be a bit field.
1490/// Note: The usual conversions are *not* applied to the operand of the &
1491/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1492QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1493 Decl *dcl = getPrimaryDeclaration(op);
1494 Expr::isLvalueResult lval = op->isLvalue();
1495
1496 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1497 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1498 ;
1499 else { // FIXME: emit more specific diag...
1500 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1501 op->getSourceRange());
1502 return QualType();
1503 }
1504 } else if (dcl) {
1505 // We have an lvalue with a decl. Make sure the decl is not declared
1506 // with the register storage-class specifier.
1507 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1508 if (vd->getStorageClass() == VarDecl::Register) {
1509 Diag(OpLoc, diag::err_typecheck_address_of_register,
1510 op->getSourceRange());
1511 return QualType();
1512 }
1513 } else
1514 assert(0 && "Unknown/unexpected decl type");
1515
1516 // FIXME: add check for bitfields!
1517 }
1518 // If the operand has type "type", the result has type "pointer to type".
1519 return Context.getPointerType(op->getType());
1520}
1521
1522QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001523 UsualUnaryConversions(op);
1524 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001525
Chris Lattnerbefee482007-07-31 16:53:04 +00001526 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 QualType ptype = PT->getPointeeType();
1528 // C99 6.5.3.2p4. "if it points to an object,...".
1529 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1530 // GCC compat: special case 'void *' (treat as warning).
1531 if (ptype->isVoidType()) {
1532 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1533 qType.getAsString(), op->getSourceRange());
1534 } else {
1535 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1536 ptype.getAsString(), op->getSourceRange());
1537 return QualType();
1538 }
1539 }
1540 return ptype;
1541 }
1542 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1543 qType.getAsString(), op->getSourceRange());
1544 return QualType();
1545}
1546
1547static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1548 tok::TokenKind Kind) {
1549 BinaryOperator::Opcode Opc;
1550 switch (Kind) {
1551 default: assert(0 && "Unknown binop!");
1552 case tok::star: Opc = BinaryOperator::Mul; break;
1553 case tok::slash: Opc = BinaryOperator::Div; break;
1554 case tok::percent: Opc = BinaryOperator::Rem; break;
1555 case tok::plus: Opc = BinaryOperator::Add; break;
1556 case tok::minus: Opc = BinaryOperator::Sub; break;
1557 case tok::lessless: Opc = BinaryOperator::Shl; break;
1558 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1559 case tok::lessequal: Opc = BinaryOperator::LE; break;
1560 case tok::less: Opc = BinaryOperator::LT; break;
1561 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1562 case tok::greater: Opc = BinaryOperator::GT; break;
1563 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1564 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1565 case tok::amp: Opc = BinaryOperator::And; break;
1566 case tok::caret: Opc = BinaryOperator::Xor; break;
1567 case tok::pipe: Opc = BinaryOperator::Or; break;
1568 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1569 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1570 case tok::equal: Opc = BinaryOperator::Assign; break;
1571 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1572 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1573 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1574 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1575 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1576 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1577 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1578 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1579 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1580 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1581 case tok::comma: Opc = BinaryOperator::Comma; break;
1582 }
1583 return Opc;
1584}
1585
1586static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1587 tok::TokenKind Kind) {
1588 UnaryOperator::Opcode Opc;
1589 switch (Kind) {
1590 default: assert(0 && "Unknown unary op!");
1591 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1592 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1593 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1594 case tok::star: Opc = UnaryOperator::Deref; break;
1595 case tok::plus: Opc = UnaryOperator::Plus; break;
1596 case tok::minus: Opc = UnaryOperator::Minus; break;
1597 case tok::tilde: Opc = UnaryOperator::Not; break;
1598 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1599 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1600 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1601 case tok::kw___real: Opc = UnaryOperator::Real; break;
1602 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1603 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1604 }
1605 return Opc;
1606}
1607
1608// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001609Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 ExprTy *LHS, ExprTy *RHS) {
1611 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1612 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1613
Steve Narofff69936d2007-09-16 03:34:24 +00001614 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1615 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001616
1617 QualType ResultTy; // Result type of the binary operator.
1618 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1619
1620 switch (Opc) {
1621 default:
1622 assert(0 && "Unknown binary expr!");
1623 case BinaryOperator::Assign:
1624 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1625 break;
1626 case BinaryOperator::Mul:
1627 case BinaryOperator::Div:
1628 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1629 break;
1630 case BinaryOperator::Rem:
1631 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1632 break;
1633 case BinaryOperator::Add:
1634 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1635 break;
1636 case BinaryOperator::Sub:
1637 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1638 break;
1639 case BinaryOperator::Shl:
1640 case BinaryOperator::Shr:
1641 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1642 break;
1643 case BinaryOperator::LE:
1644 case BinaryOperator::LT:
1645 case BinaryOperator::GE:
1646 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001647 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 break;
1649 case BinaryOperator::EQ:
1650 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001651 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 break;
1653 case BinaryOperator::And:
1654 case BinaryOperator::Xor:
1655 case BinaryOperator::Or:
1656 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1657 break;
1658 case BinaryOperator::LAnd:
1659 case BinaryOperator::LOr:
1660 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1661 break;
1662 case BinaryOperator::MulAssign:
1663 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001664 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 if (!CompTy.isNull())
1666 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1667 break;
1668 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001669 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 if (!CompTy.isNull())
1671 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1672 break;
1673 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001674 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 if (!CompTy.isNull())
1676 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1677 break;
1678 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001679 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 if (!CompTy.isNull())
1681 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1682 break;
1683 case BinaryOperator::ShlAssign:
1684 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001685 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 if (!CompTy.isNull())
1687 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1688 break;
1689 case BinaryOperator::AndAssign:
1690 case BinaryOperator::XorAssign:
1691 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001692 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 if (!CompTy.isNull())
1694 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1695 break;
1696 case BinaryOperator::Comma:
1697 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1698 break;
1699 }
1700 if (ResultTy.isNull())
1701 return true;
1702 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001703 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001705 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001706}
1707
1708// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001709Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 ExprTy *input) {
1711 Expr *Input = (Expr*)input;
1712 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1713 QualType resultType;
1714 switch (Opc) {
1715 default:
1716 assert(0 && "Unimplemented unary expr!");
1717 case UnaryOperator::PreInc:
1718 case UnaryOperator::PreDec:
1719 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1720 break;
1721 case UnaryOperator::AddrOf:
1722 resultType = CheckAddressOfOperand(Input, OpLoc);
1723 break;
1724 case UnaryOperator::Deref:
1725 resultType = CheckIndirectionOperand(Input, OpLoc);
1726 break;
1727 case UnaryOperator::Plus:
1728 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001729 UsualUnaryConversions(Input);
1730 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1732 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1733 resultType.getAsString());
1734 break;
1735 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001736 UsualUnaryConversions(Input);
1737 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00001738 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1739 if (!resultType->isIntegerType()) {
1740 if (resultType->isComplexType())
1741 // C99 does not support '~' for complex conjugation.
1742 Diag(OpLoc, diag::ext_integer_complement_complex,
1743 resultType.getAsString());
1744 else
1745 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1746 resultType.getAsString());
1747 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001748 break;
1749 case UnaryOperator::LNot: // logical negation
1750 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001751 DefaultFunctionArrayConversion(Input);
1752 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001753 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1754 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1755 resultType.getAsString());
1756 // LNot always has type int. C99 6.5.3.3p5.
1757 resultType = Context.IntTy;
1758 break;
1759 case UnaryOperator::SizeOf:
1760 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1761 break;
1762 case UnaryOperator::AlignOf:
1763 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1764 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001765 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00001766 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00001767 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00001768 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 resultType = Input->getType();
1771 break;
1772 }
1773 if (resultType.isNull())
1774 return true;
1775 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1776}
1777
Steve Naroff1b273c42007-09-16 14:56:35 +00001778/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1779Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 SourceLocation LabLoc,
1781 IdentifierInfo *LabelII) {
1782 // Look up the record for this label identifier.
1783 LabelStmt *&LabelDecl = LabelMap[LabelII];
1784
1785 // If we haven't seen this label yet, create a forward reference.
1786 if (LabelDecl == 0)
1787 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1788
1789 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001790 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1791 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001792}
1793
Steve Naroff1b273c42007-09-16 14:56:35 +00001794Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001795 SourceLocation RPLoc) { // "({..})"
1796 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1797 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1798 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1799
1800 // FIXME: there are a variety of strange constraints to enforce here, for
1801 // example, it is not possible to goto into a stmt expression apparently.
1802 // More semantic analysis is needed.
1803
1804 // FIXME: the last statement in the compount stmt has its value used. We
1805 // should not warn about it being unused.
1806
1807 // If there are sub stmts in the compound stmt, take the type of the last one
1808 // as the type of the stmtexpr.
1809 QualType Ty = Context.VoidTy;
1810
1811 if (!Compound->body_empty())
1812 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1813 Ty = LastExpr->getType();
1814
1815 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1816}
Steve Naroffd34e9152007-08-01 22:05:33 +00001817
Steve Naroff1b273c42007-09-16 14:56:35 +00001818Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001819 SourceLocation TypeLoc,
1820 TypeTy *argty,
1821 OffsetOfComponent *CompPtr,
1822 unsigned NumComponents,
1823 SourceLocation RPLoc) {
1824 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1825 assert(!ArgTy.isNull() && "Missing type argument!");
1826
1827 // We must have at least one component that refers to the type, and the first
1828 // one is known to be a field designator. Verify that the ArgTy represents
1829 // a struct/union/class.
1830 if (!ArgTy->isRecordType())
1831 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1832
1833 // Otherwise, create a compound literal expression as the base, and
1834 // iteratively process the offsetof designators.
1835 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1836
Chris Lattner9e2b75c2007-08-31 21:49:13 +00001837 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1838 // GCC extension, diagnose them.
1839 if (NumComponents != 1)
1840 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1841 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1842
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001843 for (unsigned i = 0; i != NumComponents; ++i) {
1844 const OffsetOfComponent &OC = CompPtr[i];
1845 if (OC.isBrackets) {
1846 // Offset of an array sub-field. TODO: Should we allow vector elements?
1847 const ArrayType *AT = Res->getType()->getAsArrayType();
1848 if (!AT) {
1849 delete Res;
1850 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1851 Res->getType().getAsString());
1852 }
1853
Chris Lattner704fe352007-08-30 17:59:59 +00001854 // FIXME: C++: Verify that operator[] isn't overloaded.
1855
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001856 // C99 6.5.2.1p1
1857 Expr *Idx = static_cast<Expr*>(OC.U.E);
1858 if (!Idx->getType()->isIntegerType())
1859 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1860 Idx->getSourceRange());
1861
1862 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1863 continue;
1864 }
1865
1866 const RecordType *RC = Res->getType()->getAsRecordType();
1867 if (!RC) {
1868 delete Res;
1869 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1870 Res->getType().getAsString());
1871 }
1872
1873 // Get the decl corresponding to this.
1874 RecordDecl *RD = RC->getDecl();
1875 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1876 if (!MemberDecl)
1877 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1878 OC.U.IdentInfo->getName(),
1879 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00001880
1881 // FIXME: C++: Verify that MemberDecl isn't a static field.
1882 // FIXME: Verify that MemberDecl isn't a bitfield.
1883
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001884 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1885 }
1886
1887 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1888 BuiltinLoc);
1889}
1890
1891
Steve Naroff1b273c42007-09-16 14:56:35 +00001892Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00001893 TypeTy *arg1, TypeTy *arg2,
1894 SourceLocation RPLoc) {
1895 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1896 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1897
1898 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1899
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001900 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00001901}
1902
Steve Naroff1b273c42007-09-16 14:56:35 +00001903Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00001904 ExprTy *expr1, ExprTy *expr2,
1905 SourceLocation RPLoc) {
1906 Expr *CondExpr = static_cast<Expr*>(cond);
1907 Expr *LHSExpr = static_cast<Expr*>(expr1);
1908 Expr *RHSExpr = static_cast<Expr*>(expr2);
1909
1910 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1911
1912 // The conditional expression is required to be a constant expression.
1913 llvm::APSInt condEval(32);
1914 SourceLocation ExpLoc;
1915 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1916 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1917 CondExpr->getSourceRange());
1918
1919 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1920 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1921 RHSExpr->getType();
1922 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1923}
1924
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001925Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
1926 ExprTy *expr, TypeTy *type,
1927 SourceLocation RPLoc)
1928{
1929 Expr *E = static_cast<Expr*>(expr);
1930 QualType T = QualType::getFromOpaquePtr(type);
1931
1932 InitBuiltinVaListType();
1933
1934 Sema::AssignmentCheckResult result;
1935
1936 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
1937 E->getType());
1938 if (result != Compatible)
1939 return Diag(E->getLocStart(),
1940 diag::err_first_argument_to_va_arg_not_of_type_va_list,
1941 E->getType().getAsString(),
1942 E->getSourceRange());
1943
1944 // FIXME: Warn if a non-POD type is passed in.
1945
1946 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
1947}
1948
Anders Carlsson55085182007-08-21 17:43:55 +00001949// TODO: Move this to SemaObjC.cpp
Steve Naroffbeaf2992007-11-03 11:27:19 +00001950Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation AtLoc,
1951 ExprTy *string) {
Anders Carlsson55085182007-08-21 17:43:55 +00001952 StringLiteral* S = static_cast<StringLiteral *>(string);
1953
1954 if (CheckBuiltinCFStringArgument(S))
1955 return true;
1956
Steve Naroff21988912007-10-15 23:35:17 +00001957 if (Context.getObjcConstantStringInterface().isNull()) {
1958 // Initialize the constant string interface lazily. This assumes
1959 // the NSConstantString interface is seen in this translation unit.
1960 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
1961 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
1962 SourceLocation(), TUScope);
Steve Naroffa1fe1172007-10-16 00:00:18 +00001963 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff806a4eb2007-10-18 23:53:51 +00001964 if (!strIFace)
1965 return Diag(S->getLocStart(), diag::err_undef_interface,
1966 NSIdent->getName());
Steve Naroffa1fe1172007-10-16 00:00:18 +00001967 Context.setObjcConstantStringInterface(strIFace);
Steve Naroff21988912007-10-15 23:35:17 +00001968 }
1969 QualType t = Context.getObjcConstantStringInterface();
Anders Carlsson55085182007-08-21 17:43:55 +00001970 t = Context.getPointerType(t);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001971 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlsson55085182007-08-21 17:43:55 +00001972}
Anders Carlssonf9bcf012007-08-22 15:14:15 +00001973
1974Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattner674af952007-10-16 22:51:17 +00001975 SourceLocation EncodeLoc,
Anders Carlssonf9bcf012007-08-22 15:14:15 +00001976 SourceLocation LParenLoc,
1977 TypeTy *Ty,
1978 SourceLocation RParenLoc) {
1979 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1980
1981 QualType t = Context.getPointerType(Context.CharTy);
1982 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1983}
Steve Naroff708391a2007-09-17 21:01:15 +00001984
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00001985Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1986 SourceLocation AtLoc,
Fariborz Jahanian2a35fa92007-10-16 23:21:02 +00001987 SourceLocation SelLoc,
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00001988 SourceLocation LParenLoc,
1989 SourceLocation RParenLoc) {
Steve Naroff8ee529b2007-10-31 18:42:27 +00001990 QualType t = Context.getObjcSelType();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00001991 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
1992}
1993
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00001994Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1995 SourceLocation AtLoc,
1996 SourceLocation ProtoLoc,
1997 SourceLocation LParenLoc,
1998 SourceLocation RParenLoc) {
1999 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2000 if (!PDecl) {
2001 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2002 return true;
2003 }
2004
2005 QualType t = GetObjcProtoType(AtLoc);
Fariborz Jahanian3e27aa12007-10-18 22:59:23 +00002006 if (t.isNull())
2007 return true;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002008 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2009}
Steve Naroff81bfde92007-10-16 23:12:48 +00002010
2011bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2012 ObjcMethodDecl *Method) {
2013 bool anyIncompatibleArgs = false;
2014
2015 for (unsigned i = 0; i < NumArgs; i++) {
2016 Expr *argExpr = Args[i];
2017 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2018
2019 QualType lhsType = Method->getParamDecl(i)->getType();
2020 QualType rhsType = argExpr->getType();
2021
2022 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2023 if (const ArrayType *ary = lhsType->getAsArrayType())
2024 lhsType = Context.getPointerType(ary->getElementType());
2025 else if (lhsType->isFunctionType())
2026 lhsType = Context.getPointerType(lhsType);
2027
2028 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2029 argExpr);
2030 if (Args[i] != argExpr) // The expression was converted.
2031 Args[i] = argExpr; // Make sure we store the converted expression.
2032 SourceLocation l = argExpr->getLocStart();
2033
2034 // decode the result (notice that AST's are still created for extensions).
2035 switch (result) {
2036 case Compatible:
2037 break;
2038 case PointerFromInt:
2039 // check for null pointer constant (C99 6.3.2.3p3)
2040 if (!argExpr->isNullPointerConstant(Context)) {
2041 Diag(l, diag::ext_typecheck_sending_pointer_int,
2042 lhsType.getAsString(), rhsType.getAsString(),
2043 argExpr->getSourceRange());
2044 }
2045 break;
2046 case IntFromPointer:
2047 Diag(l, diag::ext_typecheck_sending_pointer_int,
2048 lhsType.getAsString(), rhsType.getAsString(),
2049 argExpr->getSourceRange());
2050 break;
2051 case IncompatiblePointer:
2052 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2053 rhsType.getAsString(), lhsType.getAsString(),
2054 argExpr->getSourceRange());
2055 break;
2056 case CompatiblePointerDiscardsQualifiers:
2057 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2058 rhsType.getAsString(), lhsType.getAsString(),
2059 argExpr->getSourceRange());
2060 break;
2061 case Incompatible:
2062 Diag(l, diag::err_typecheck_sending_incompatible,
2063 rhsType.getAsString(), lhsType.getAsString(),
2064 argExpr->getSourceRange());
2065 anyIncompatibleArgs = true;
2066 }
2067 }
2068 return anyIncompatibleArgs;
2069}
2070
Steve Naroff68d331a2007-09-27 14:38:14 +00002071// ActOnClassMessage - used for both unary and keyword messages.
2072// ArgExprs is optional - if it is present, the number of expressions
2073// is obtained from Sel.getNumArgs().
2074Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002075 Scope *S,
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002076 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00002077 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args)
Steve Naroff708391a2007-09-17 21:01:15 +00002078{
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002079 assert(receiverName && "missing receiver class name");
Steve Naroff563477d2007-09-18 23:55:05 +00002080
Steve Naroff81bfde92007-10-16 23:12:48 +00002081 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002082 ObjcInterfaceDecl* ClassDecl = 0;
2083 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2084 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahaniancffff842007-11-12 20:20:37 +00002085 if (ClassDecl && CurMethodDecl->isInstance()) {
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002086 IdentifierInfo &II = Context.Idents.get("self");
2087 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II,
2088 false);
2089 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2090 superTy = Context.getPointerType(superTy);
2091 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2092 SourceLocation(), ReceiverExpr.Val);
2093
2094 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
2095 Args);
2096 }
2097 // class method
2098 if (ClassDecl)
2099 receiverName = ClassDecl->getIdentifier();
2100 }
2101 else
2102 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002103 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002104 QualType returnType;
Steve Naroff945c0a82007-11-05 15:27:52 +00002105
2106 // Before we give up, check if the selector is an instance method.
2107 if (!Method)
2108 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002109 if (!Method) {
2110 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2111 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002112 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002113 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002114 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002115 if (Sel.getNumArgs()) {
2116 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2117 return true;
2118 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002119 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002120 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
2121 lbrac, rbrac, ArgExprs);
Steve Naroff708391a2007-09-17 21:01:15 +00002122}
2123
Steve Naroff68d331a2007-09-27 14:38:14 +00002124// ActOnInstanceMessage - used for both unary and keyword messages.
2125// ArgExprs is optional - if it is present, the number of expressions
2126// is obtained from Sel.getNumArgs().
2127Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroffbcfb06a2007-09-28 22:22:11 +00002128 ExprTy *receiver, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00002129 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args)
2130{
Steve Naroff563477d2007-09-18 23:55:05 +00002131 assert(receiver && "missing receiver expression");
2132
Steve Naroff81bfde92007-10-16 23:12:48 +00002133 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroff563477d2007-09-18 23:55:05 +00002134 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002135 QualType receiverType = RExpr->getType();
Steve Naroff3b950172007-10-10 21:53:07 +00002136 QualType returnType;
Steve Naroffdb611d52007-11-03 16:37:59 +00002137 ObjcMethodDecl *Method;
Steve Naroff3b950172007-10-10 21:53:07 +00002138
Steve Naroff7c249152007-11-11 17:52:25 +00002139 if (receiverType == Context.getObjcIdType() ||
2140 receiverType == Context.getObjcClassType()) {
Steve Naroffdb611d52007-11-03 16:37:59 +00002141 Method = InstanceMethodPool[Sel].Method;
Steve Naroff983df5b2007-10-16 20:39:36 +00002142 if (!Method) {
2143 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2144 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002145 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002146 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002147 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002148 if (Sel.getNumArgs())
2149 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2150 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002151 }
Steve Naroff3b950172007-10-10 21:53:07 +00002152 } else {
Chris Lattner22b73ba2007-10-10 23:42:28 +00002153 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2154 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroff3b950172007-10-10 21:53:07 +00002155 while (receiverType->isPointerType()) {
Chris Lattner22b73ba2007-10-10 23:42:28 +00002156 PointerType *pointerType =
2157 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroff3b950172007-10-10 21:53:07 +00002158 receiverType = pointerType->getPointeeType();
2159 }
Chris Lattner22b73ba2007-10-10 23:42:28 +00002160 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2161 "bad receiver type");
Steve Naroff3b950172007-10-10 21:53:07 +00002162 ObjcInterfaceDecl* ClassDecl = static_cast<ObjcInterfaceType*>(
2163 receiverType.getTypePtr())->getDecl();
Steve Naroff983df5b2007-10-16 20:39:36 +00002164 // FIXME: consider using InstanceMethodPool, since it will be faster
2165 // than the following method (which can do *many* linear searches). The
2166 // idea is to add class info to InstanceMethodPool...
Steve Naroffdb611d52007-11-03 16:37:59 +00002167 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002168 if (!Method) {
Steve Naroffc43d8682007-11-11 00:10:47 +00002169 // If we have an implementation in scope, check "private" methods.
2170 if (ObjcImplementationDecl *ImpDecl =
2171 ObjcImplementations[ClassDecl->getIdentifier()])
2172 Method = ImpDecl->lookupInstanceMethod(Sel);
2173 }
2174 if (!Method) {
Steve Naroff983df5b2007-10-16 20:39:36 +00002175 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2176 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002177 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002178 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002179 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002180 if (Sel.getNumArgs())
2181 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2182 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002183 }
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002184 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002185 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
2186 ArgExprs);
Steve Naroff708391a2007-09-17 21:01:15 +00002187}