blob: 6b871b4812ba70c4958f07d0377bb6b2a61c47fa [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"
17#include "clang/AST/Expr.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/LiteralSupport.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/SmallString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
28/// ParseStringLiteral - The specified tokens were lexed as pasted string
29/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
Chris Lattnerd2177732007-07-20 16:59:19 +000035Sema::ParseStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +000036 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
45
46 // FIXME: handle wchar_t
47 QualType t = Context.getPointerType(Context.CharTy);
48
49 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
50 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
51 Literal.AnyWide, t, StringToks[0].getLocation(),
52 StringToks[NumStringToks-1].getLocation());
53}
54
55
56/// ParseIdentifierExpr - The parser read an identifier in expression context,
57/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
58/// identifier is used in an function call context.
59Sema::ExprResult Sema::ParseIdentifierExpr(Scope *S, SourceLocation Loc,
60 IdentifierInfo &II,
61 bool HasTrailingLParen) {
62 // Could be enum-constant or decl.
63 Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
64 if (D == 0) {
65 // Otherwise, this could be an implicitly declared function reference (legal
66 // in C90, extension in C99).
67 if (HasTrailingLParen &&
68 // Not in C++.
69 !getLangOptions().CPlusPlus)
70 D = ImplicitlyDefineFunction(Loc, II, S);
71 else {
72 // If this name wasn't predeclared and if this is not a function call,
73 // diagnose the problem.
74 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
75 }
76 }
Reid Spencer5f016e22007-07-11 17:01:13 +000077 if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
78 return new DeclRefExpr(VD, VD->getType(), Loc);
79 if (isa<TypedefDecl>(D))
80 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
81
82 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +000083 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +000084}
85
Anders Carlsson22742662007-07-21 05:21:51 +000086Sema::ExprResult Sema::ParsePreDefinedExpr(SourceLocation Loc,
87 tok::TokenKind Kind) {
88 PreDefinedExpr::IdentType IT;
89
Reid Spencer5f016e22007-07-11 17:01:13 +000090 switch (Kind) {
91 default:
92 assert(0 && "Unknown simple primary expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +000093 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
Anders Carlsson22742662007-07-21 05:21:51 +000094 IT = PreDefinedExpr::Func;
95 break;
Reid Spencer5f016e22007-07-11 17:01:13 +000096 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +000097 IT = PreDefinedExpr::Function;
98 break;
Reid Spencer5f016e22007-07-11 17:01:13 +000099 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000100 IT = PreDefinedExpr::PrettyFunction;
101 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 }
Anders Carlsson22742662007-07-21 05:21:51 +0000103
104 // Pre-defined identifiers are always of type char *.
105 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000106}
107
Chris Lattnerd2177732007-07-20 16:59:19 +0000108Sema::ExprResult Sema::ParseCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 llvm::SmallString<16> CharBuffer;
110 CharBuffer.resize(Tok.getLength());
111 const char *ThisTokBegin = &CharBuffer[0];
112 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
113
114 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
115 Tok.getLocation(), PP);
116 if (Literal.hadError())
117 return ExprResult(true);
118 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
119 Tok.getLocation());
120}
121
Chris Lattnerd2177732007-07-20 16:59:19 +0000122Action::ExprResult Sema::ParseNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 // fast path for a single digit (which is quite common). A single digit
124 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
125 if (Tok.getLength() == 1) {
126 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
127
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000128 unsigned IntSize = Context.getTypeSize(Context.IntTy, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
130 Context.IntTy,
131 Tok.getLocation()));
132 }
133 llvm::SmallString<512> IntegerBuffer;
134 IntegerBuffer.resize(Tok.getLength());
135 const char *ThisTokBegin = &IntegerBuffer[0];
136
137 // Get the spelling of the token, which eliminates trigraphs, etc.
138 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
139 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
140 Tok.getLocation(), PP);
141 if (Literal.hadError)
142 return ExprResult(true);
143
144 if (Literal.isIntegerLiteral()) {
145 QualType t;
146
147 // Get the value in the widest-possible width.
148 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
149
150 if (Literal.GetIntegerValue(ResultVal)) {
151 // If this value didn't fit into uintmax_t, warn and force to ull.
152 Diag(Tok.getLocation(), diag::warn_integer_too_large);
153 t = Context.UnsignedLongLongTy;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000154 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 ResultVal.getBitWidth() && "long long is not intmax_t?");
156 } else {
157 // If this value fits into a ULL, try to figure out what else it fits into
158 // according to the rules of C99 6.4.4.1p5.
159
160 // Octal, Hexadecimal, and integers with a U suffix are allowed to
161 // be an unsigned int.
162 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
163
164 // Check from smallest to largest, picking the smallest type we can.
165 if (!Literal.isLong) { // Are int/unsigned possibilities?
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000166 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 // Does it fit in a unsigned int?
168 if (ResultVal.isIntN(IntSize)) {
169 // Does it fit in a signed int?
170 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
171 t = Context.IntTy;
172 else if (AllowUnsigned)
173 t = Context.UnsignedIntTy;
174 }
175
176 if (!t.isNull())
177 ResultVal.trunc(IntSize);
178 }
179
180 // Are long/unsigned long possibilities?
181 if (t.isNull() && !Literal.isLongLong) {
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000182 unsigned LongSize = Context.getTypeSize(Context.LongTy,
183 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000184
185 // Does it fit in a unsigned long?
186 if (ResultVal.isIntN(LongSize)) {
187 // Does it fit in a signed long?
188 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
189 t = Context.LongTy;
190 else if (AllowUnsigned)
191 t = Context.UnsignedLongTy;
192 }
193 if (!t.isNull())
194 ResultVal.trunc(LongSize);
195 }
196
197 // Finally, check long long if needed.
198 if (t.isNull()) {
199 unsigned LongLongSize =
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000200 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000201
202 // Does it fit in a unsigned long long?
203 if (ResultVal.isIntN(LongLongSize)) {
204 // Does it fit in a signed long long?
205 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
206 t = Context.LongLongTy;
207 else if (AllowUnsigned)
208 t = Context.UnsignedLongLongTy;
209 }
210 }
211
212 // If we still couldn't decide a type, we probably have something that
213 // does not fit in a signed long long, but has no U suffix.
214 if (t.isNull()) {
215 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
216 t = Context.UnsignedLongLongTy;
217 }
218 }
219
220 return new IntegerLiteral(ResultVal, t, Tok.getLocation());
221 } else if (Literal.isFloatingLiteral()) {
222 // FIXME: handle float values > 32 (including compute the real type...).
223 return new FloatingLiteral(Literal.GetFloatValue(), Context.FloatTy,
224 Tok.getLocation());
225 }
226 return ExprResult(true);
227}
228
229Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
230 ExprTy *Val) {
231 Expr *e = (Expr *)Val;
232 assert((e != 0) && "ParseParenExpr() missing expr");
233 return new ParenExpr(L, R, e);
234}
235
236/// The UsualUnaryConversions() function is *not* called by this routine.
237/// See C99 6.3.2.1p[2-4] for more details.
238QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
239 SourceLocation OpLoc, bool isSizeof) {
240 // C99 6.5.3.4p1:
241 if (isa<FunctionType>(exprType) && isSizeof)
242 // alignof(function) is allowed.
243 Diag(OpLoc, diag::ext_sizeof_function_type);
244 else if (exprType->isVoidType())
245 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
246 else if (exprType->isIncompleteType()) {
247 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
248 diag::err_alignof_incomplete_type,
249 exprType.getAsString());
250 return QualType(); // error
251 }
252 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
253 return Context.getSizeType();
254}
255
256Action::ExprResult Sema::
257ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
258 SourceLocation LPLoc, TypeTy *Ty,
259 SourceLocation RPLoc) {
260 // If error parsing type, ignore.
261 if (Ty == 0) return true;
262
263 // Verify that this is a valid expression.
264 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
265
266 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
267
268 if (resultType.isNull())
269 return true;
270 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
271}
272
273
274Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
275 tok::TokenKind Kind,
276 ExprTy *Input) {
277 UnaryOperator::Opcode Opc;
278 switch (Kind) {
279 default: assert(0 && "Unknown unary op!");
280 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
281 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
282 }
283 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
284 if (result.isNull())
285 return true;
286 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
287}
288
289Action::ExprResult Sema::
290ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
291 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000292 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000293
294 // Perform default conversions.
295 DefaultFunctionArrayConversion(LHSExp);
296 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000297
Chris Lattner12d9ff62007-07-16 00:14:47 +0000298 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000299
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
301 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
302 // in the subscript position. As a result, we need to derive the array base
303 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000304 Expr *BaseExpr, *IndexExpr;
305 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000306 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000307 BaseExpr = LHSExp;
308 IndexExpr = RHSExp;
309 // FIXME: need to deal with const...
310 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000311 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000312 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000313 BaseExpr = RHSExp;
314 IndexExpr = LHSExp;
315 // FIXME: need to deal with const...
316 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000317 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
318 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000319 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000320
321 // Component access limited to variables (reject vec4.rg[1]).
322 if (!isa<DeclRefExpr>(BaseExpr))
323 return Diag(LLoc, diag::err_ocuvector_component_access,
324 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000325 // FIXME: need to deal with const...
326 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000328 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
329 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 }
331 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000332 if (!IndexExpr->getType()->isIntegerType())
333 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
334 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000335
Chris Lattner12d9ff62007-07-16 00:14:47 +0000336 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
337 // the following check catches trying to index a pointer to a function (e.g.
338 // void (*)(int)). Functions are not objects in C99.
339 if (!ResultType->isObjectType())
340 return Diag(BaseExpr->getLocStart(),
341 diag::err_typecheck_subscript_not_object,
342 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
343
344 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000345}
346
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000347QualType Sema::
348CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
349 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnerc8629632007-07-31 19:29:30 +0000350 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000351
352 // The vector accessor can't exceed the number of elements.
353 const char *compStr = CompName.getName();
354 if (strlen(compStr) > vecType->getNumElements()) {
355 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
356 baseType.getAsString(), SourceRange(CompLoc));
357 return QualType();
358 }
359 // The component names must come from the same set.
Chris Lattner88dca042007-08-02 22:33:49 +0000360 if (vecType->getPointAccessorIdx(*compStr) != -1) {
361 do
362 compStr++;
363 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
364 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
365 do
366 compStr++;
367 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
368 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
369 do
370 compStr++;
371 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
372 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000373
374 if (*compStr) {
375 // We didn't get to the end of the string. This means the component names
376 // didn't come from the same set *or* we encountered an illegal name.
377 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
378 std::string(compStr,compStr+1), SourceRange(CompLoc));
379 return QualType();
380 }
381 // Each component accessor can't exceed the vector type.
382 compStr = CompName.getName();
383 while (*compStr) {
384 if (vecType->isAccessorWithinNumElements(*compStr))
385 compStr++;
386 else
387 break;
388 }
389 if (*compStr) {
390 // We didn't get to the end of the string. This means a component accessor
391 // exceeds the number of elements in the vector.
392 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
393 baseType.getAsString(), SourceRange(CompLoc));
394 return QualType();
395 }
396 // The component accessor looks fine - now we need to compute the actual type.
397 // The vector type is implied by the component accessor. For example,
398 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
399 unsigned CompSize = strlen(CompName.getName());
400 if (CompSize == 1)
401 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000402
403 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
404 // Now look up the TypeDefDecl from the vector type. Without this,
405 // diagostics look bad. We want OCU vector types to appear built-in.
406 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
407 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
408 return Context.getTypedefType(OCUVectorDecls[i]);
409 }
410 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000411}
412
Reid Spencer5f016e22007-07-11 17:01:13 +0000413Action::ExprResult Sema::
414ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
415 tok::TokenKind OpKind, SourceLocation MemberLoc,
416 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000417 Expr *BaseExpr = static_cast<Expr *>(Base);
418 assert(BaseExpr && "no record expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000419
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000420 QualType BaseType = BaseExpr->getType();
421 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000422
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000424 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000425 BaseType = PT->getPointeeType();
426 else
427 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
428 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000429 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000430 // The base type is either a record or an OCUVectorType.
Chris Lattnerc8629632007-07-31 19:29:30 +0000431 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000432 RecordDecl *RDecl = RTy->getDecl();
433 if (RTy->isIncompleteType())
434 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
435 BaseExpr->getSourceRange());
436 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000437 FieldDecl *MemberDecl = RDecl->getMember(&Member);
438 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000439 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
440 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000441 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
442 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff608e0ee2007-08-03 22:40:33 +0000443 // Component access limited to variables (reject vec4.rg.g).
444 if (!isa<DeclRefExpr>(BaseExpr))
445 return Diag(OpLoc, diag::err_ocuvector_component_access,
446 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000447 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
448 if (ret.isNull())
449 return true;
Chris Lattner6481a572007-08-03 17:31:20 +0000450 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000451 } else
452 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
453 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000454}
455
456/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
457/// This provides the location of the left/right parens and a list of comma
458/// locations.
459Action::ExprResult Sema::
Chris Lattner74c469f2007-07-21 03:03:59 +0000460ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
461 ExprTy **args, unsigned NumArgsInCall,
Reid Spencer5f016e22007-07-11 17:01:13 +0000462 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000463 Expr *Fn = static_cast<Expr *>(fn);
464 Expr **Args = reinterpret_cast<Expr**>(args);
465 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000466
Chris Lattner74c469f2007-07-21 03:03:59 +0000467 UsualUnaryConversions(Fn);
468 QualType funcType = Fn->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000469
470 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
471 // type pointer to function".
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000472 const PointerType *PT = funcType->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000474 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
475 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000476
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000477 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 if (funcT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000479 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
480 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000481
482 // If a prototype isn't declared, the parser implicitly defines a func decl
483 QualType resultType = funcT->getResultType();
484
485 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
486 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
487 // assignment, to the types of the corresponding parameter, ...
488
489 unsigned NumArgsInProto = proto->getNumArgs();
490 unsigned NumArgsToCheck = NumArgsInCall;
491
492 if (NumArgsInCall < NumArgsInProto)
493 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
Chris Lattner74c469f2007-07-21 03:03:59 +0000494 Fn->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 else if (NumArgsInCall > NumArgsInProto) {
496 if (!proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000497 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000498 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000499 SourceRange(Args[NumArgsInProto]->getLocStart(),
500 Args[NumArgsInCall-1]->getLocEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 }
502 NumArgsToCheck = NumArgsInProto;
503 }
504 // Continue to check argument types (even if we have too few/many args).
505 for (unsigned i = 0; i < NumArgsToCheck; i++) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000506 Expr *argExpr = Args[i];
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 assert(argExpr && "ParseCallExpr(): missing argument expression");
508
509 QualType lhsType = proto->getArgType(i);
510 QualType rhsType = argExpr->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000511
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000512 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnerc8629632007-07-31 19:29:30 +0000513 if (const ArrayType *ary = lhsType->getAsArrayType())
Steve Naroff700204c2007-07-24 21:46:40 +0000514 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000515 else if (lhsType->isFunctionType())
Steve Naroff700204c2007-07-24 21:46:40 +0000516 lhsType = Context.getPointerType(lhsType);
517
Steve Naroff90045e82007-07-13 23:32:42 +0000518 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
519 argExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 SourceLocation l = argExpr->getLocStart();
521
522 // decode the result (notice that AST's are still created for extensions).
523 switch (result) {
524 case Compatible:
525 break;
526 case PointerFromInt:
527 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +0000528 if (!argExpr->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 Diag(l, diag::ext_typecheck_passing_pointer_int,
530 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000531 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 }
533 break;
534 case IntFromPointer:
535 Diag(l, diag::ext_typecheck_passing_pointer_int,
536 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000537 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 break;
539 case IncompatiblePointer:
540 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
541 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000542 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 break;
544 case CompatiblePointerDiscardsQualifiers:
545 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
546 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000547 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 break;
549 case Incompatible:
550 return Diag(l, diag::err_typecheck_passing_incompatible,
551 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000552 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 }
554 }
555 // Even if the types checked, bail if we had the wrong number of arguments.
Chris Lattner74c469f2007-07-21 03:03:59 +0000556 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 return true;
558 }
Chris Lattner59907c42007-08-10 20:18:51 +0000559
560 // Do special checking on direct calls to functions.
561 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
562 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
563 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
564 CheckFunctionCall(Fn, FDecl, Args, NumArgsInCall);
565
Chris Lattner74c469f2007-07-21 03:03:59 +0000566 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000567}
568
569Action::ExprResult Sema::
Steve Naroff4aa88f82007-07-19 01:06:55 +0000570ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000571 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff4aa88f82007-07-19 01:06:55 +0000572 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
573 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000574 // FIXME: put back this assert when initializers are worked out.
575 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
576 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000577
578 // FIXME: add semantic analysis (C99 6.5.2.5).
Steve Naroffaff1edd2007-07-19 21:32:11 +0000579 return new CompoundLiteralExpr(literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000580}
581
582Action::ExprResult Sema::
583ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
584 SourceLocation RParenLoc) {
585 // FIXME: add semantic analysis (C99 6.7.8). This involves
586 // knowledge of the object being intialized. As a result, the code for
587 // doing the semantic analysis will likely be located elsewhere (i.e. in
588 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
589 return false; // FIXME instantiate an InitListExpr.
590}
591
592Action::ExprResult Sema::
Reid Spencer5f016e22007-07-11 17:01:13 +0000593ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
594 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff16beff82007-07-16 23:25:18 +0000595 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
596
597 Expr *castExpr = static_cast<Expr*>(Op);
598 QualType castType = QualType::getFromOpaquePtr(Ty);
599
Chris Lattner75af4802007-07-18 16:00:06 +0000600 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
601 // type needs to be scalar.
602 if (!castType->isScalarType() && !castType->isVoidType()) {
Steve Naroff16beff82007-07-16 23:25:18 +0000603 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
604 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
605 }
606 if (!castExpr->getType()->isScalarType()) {
607 return Diag(castExpr->getLocStart(),
608 diag::err_typecheck_expect_scalar_operand,
609 castExpr->getType().getAsString(), castExpr->getSourceRange());
610 }
611 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000612}
613
614inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000615 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000616 UsualUnaryConversions(cond);
617 UsualUnaryConversions(lex);
618 UsualUnaryConversions(rex);
619 QualType condT = cond->getType();
620 QualType lexT = lex->getType();
621 QualType rexT = rex->getType();
622
Reid Spencer5f016e22007-07-11 17:01:13 +0000623 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000624 if (!condT->isScalarType()) { // C99 6.5.15p2
625 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
626 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000627 return QualType();
628 }
629 // now check the two expressions.
Steve Naroffa4332e22007-07-17 00:58:39 +0000630 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
631 UsualArithmeticConversions(lex, rex);
632 return lex->getType();
633 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000634 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
635 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
636
637 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
638 return lexT;
639
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000641 lexT.getAsString(), rexT.getAsString(),
642 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 return QualType();
644 }
645 }
Chris Lattner590b6642007-07-15 23:26:56 +0000646 // C99 6.5.15p3
647 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
Steve Naroff49b45262007-07-13 16:58:59 +0000648 return lexT;
Chris Lattner590b6642007-07-15 23:26:56 +0000649 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
Steve Naroff49b45262007-07-13 16:58:59 +0000650 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000651
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000652 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
653 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
654 // get the "pointed to" types
655 QualType lhptee = LHSPT->getPointeeType();
656 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000657
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000658 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
659 if (lhptee->isVoidType() &&
660 (rhptee->isObjectType() || rhptee->isIncompleteType()))
661 return lexT;
662 if (rhptee->isVoidType() &&
663 (lhptee->isObjectType() || lhptee->isIncompleteType()))
664 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000665
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000666 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
667 rhptee.getUnqualifiedType())) {
668 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
669 lexT.getAsString(), rexT.getAsString(),
670 lex->getSourceRange(), rex->getSourceRange());
671 return lexT; // FIXME: this is an _ext - is this return o.k?
672 }
673 // The pointer types are compatible.
674 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
675 // differently qualified versions of compatible types, the result type is a
676 // pointer to an appropriately qualified version of the *composite* type.
677 return lexT; // FIXME: Need to return the composite type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 }
679 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000680
Steve Naroff49b45262007-07-13 16:58:59 +0000681 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
682 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000683
684 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000685 lexT.getAsString(), rexT.getAsString(),
686 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000687 return QualType();
688}
689
690/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
691/// in the case of a the GNU conditional expr extension.
692Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
693 SourceLocation ColonLoc,
694 ExprTy *Cond, ExprTy *LHS,
695 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000696 Expr *CondExpr = (Expr *) Cond;
697 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
698 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
699 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 if (result.isNull())
701 return true;
Chris Lattner26824902007-07-16 21:39:03 +0000702 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000703}
704
Steve Narofffa2eaab2007-07-15 02:02:06 +0000705// promoteExprToType - a helper function to ensure we create exactly one
706// ImplicitCastExpr. As a convenience (to the caller), we return the type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000707static void promoteExprToType(Expr *&expr, QualType type) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000708 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
709 impCast->setType(type);
710 else
711 expr = new ImplicitCastExpr(type, expr);
Steve Naroffa4332e22007-07-17 00:58:39 +0000712 return;
Steve Narofffa2eaab2007-07-15 02:02:06 +0000713}
714
715/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000716void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000717 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000718 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000719
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000720 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000721 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
722 t = e->getType();
723 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000724 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000725 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnerc8629632007-07-31 19:29:30 +0000726 else if (const ArrayType *ary = t->getAsArrayType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000727 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000728}
729
730/// UsualUnaryConversion - Performs various conversions that are common to most
731/// operators (C99 6.3). The conversions of array and function types are
732/// sometimes surpressed. For example, the array->pointer conversion doesn't
733/// apply if the array is an argument to the sizeof or address (&) operators.
734/// In these instances, this routine should *not* be called.
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000735void Sema::UsualUnaryConversions(Expr *&expr) {
Steve Naroff49b45262007-07-13 16:58:59 +0000736 QualType t = expr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 assert(!t.isNull() && "UsualUnaryConversions - missing type");
738
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000739 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000740 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
741 t = expr->getType();
742 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000743 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000744 promoteExprToType(expr, Context.IntTy);
745 else
746 DefaultFunctionArrayConversion(expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000747}
748
749/// UsualArithmeticConversions - Performs various conversions that are common to
750/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
751/// routine returns the first non-arithmetic type found. The client is
752/// responsible for emitting appropriate error diagnostics.
Steve Naroffa4332e22007-07-17 00:58:39 +0000753void Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000754 UsualUnaryConversions(lhsExpr);
755 UsualUnaryConversions(rhsExpr);
756
Steve Naroff3e5e5562007-07-16 22:23:01 +0000757 QualType lhs = lhsExpr->getType();
758 QualType rhs = rhsExpr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000759
760 // If both types are identical, no conversion is needed.
761 if (lhs == rhs)
Steve Naroffa4332e22007-07-17 00:58:39 +0000762 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000763
764 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
765 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000766 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
767 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000768
769 // At this point, we have two different arithmetic types.
770
771 // Handle complex types first (C99 6.3.1.8p1).
772 if (lhs->isComplexType() || rhs->isComplexType()) {
773 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000774 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
775 promoteExprToType(rhsExpr, lhs);
776 return;
777 }
778 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
779 promoteExprToType(lhsExpr, rhs);
780 return;
781 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000782 // Two complex types. Convert the smaller operand to the bigger result.
Steve Naroffa4332e22007-07-17 00:58:39 +0000783 if (Context.maxComplexType(lhs, rhs) == lhs) { // convert the rhs
784 promoteExprToType(rhsExpr, lhs);
785 return;
786 }
787 promoteExprToType(lhsExpr, rhs); // convert the lhs
788 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000790 // Now handle "real" floating types (i.e. float, double, long double).
791 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
792 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000793 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
794 promoteExprToType(rhsExpr, lhs);
795 return;
796 }
797 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
798 promoteExprToType(lhsExpr, rhs);
799 return;
800 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000801 // We have two real floating types, float/complex combos were handled above.
802 // Convert the smaller operand to the bigger result.
Steve Naroffa4332e22007-07-17 00:58:39 +0000803 if (Context.maxFloatingType(lhs, rhs) == lhs) { // convert the rhs
804 promoteExprToType(rhsExpr, lhs);
805 return;
806 }
807 promoteExprToType(lhsExpr, rhs); // convert the lhs
808 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000809 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000810 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +0000811 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
812 promoteExprToType(rhsExpr, lhs);
813 return;
814 }
815 promoteExprToType(lhsExpr, rhs); // convert the lhs
816 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000817}
818
819// CheckPointerTypesForAssignment - This is a very tricky routine (despite
820// being closely modeled after the C99 spec:-). The odd characteristic of this
821// routine is it effectively iqnores the qualifiers on the top level pointee.
822// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
823// FIXME: add a couple examples in this comment.
824Sema::AssignmentCheckResult
825Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
826 QualType lhptee, rhptee;
827
828 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000829 lhptee = lhsType->getAsPointerType()->getPointeeType();
830 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000831
832 // make sure we operate on the canonical type
833 lhptee = lhptee.getCanonicalType();
834 rhptee = rhptee.getCanonicalType();
835
836 AssignmentCheckResult r = Compatible;
837
838 // C99 6.5.16.1p1: This following citation is common to constraints
839 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
840 // qualifiers of the type *pointed to* by the right;
841 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
842 rhptee.getQualifiers())
843 r = CompatiblePointerDiscardsQualifiers;
844
845 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
846 // incomplete type and the other is a pointer to a qualified or unqualified
847 // version of void...
848 if (lhptee.getUnqualifiedType()->isVoidType() &&
849 (rhptee->isObjectType() || rhptee->isIncompleteType()))
850 ;
851 else if (rhptee.getUnqualifiedType()->isVoidType() &&
852 (lhptee->isObjectType() || lhptee->isIncompleteType()))
853 ;
854 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
855 // unqualified versions of compatible types, ...
856 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
857 rhptee.getUnqualifiedType()))
858 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
859 return r;
860}
861
862/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
863/// has code to accommodate several GCC extensions when type checking
864/// pointers. Here are some objectionable examples that GCC considers warnings:
865///
866/// int a, *pint;
867/// short *pshort;
868/// struct foo *pfoo;
869///
870/// pint = pshort; // warning: assignment from incompatible pointer type
871/// a = pint; // warning: assignment makes integer from pointer without a cast
872/// pint = a; // warning: assignment makes pointer from integer without a cast
873/// pint = pfoo; // warning: assignment from incompatible pointer type
874///
875/// As a result, the code for dealing with pointers is more complex than the
876/// C99 spec dictates.
877/// Note: the warning above turn into errors when -pedantic-errors is enabled.
878///
879Sema::AssignmentCheckResult
880Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroff700204c2007-07-24 21:46:40 +0000881 if (lhsType == rhsType) // common case, fast path...
882 return Compatible;
883
Reid Spencer5f016e22007-07-11 17:01:13 +0000884 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
885 if (lhsType->isVectorType() || rhsType->isVectorType()) {
886 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
887 return Incompatible;
888 }
889 return Compatible;
890 } else if (lhsType->isPointerType()) {
891 if (rhsType->isIntegerType())
892 return PointerFromInt;
893
894 if (rhsType->isPointerType())
895 return CheckPointerTypesForAssignment(lhsType, rhsType);
896 } else if (rhsType->isPointerType()) {
897 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
898 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
899 return IntFromPointer;
900
901 if (lhsType->isPointerType())
902 return CheckPointerTypesForAssignment(lhsType, rhsType);
903 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
904 if (Type::tagTypesAreCompatible(lhsType, rhsType))
905 return Compatible;
906 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
907 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
908 return Compatible;
909 }
910 return Incompatible;
911}
912
Steve Naroff90045e82007-07-13 23:32:42 +0000913Sema::AssignmentCheckResult
914Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
915 // This check seems unnatural, however it is necessary to insure the proper
916 // conversion of functions/arrays. If the conversion were done for all
917 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
918 // expressions that surpress this implicit conversion (&, sizeof).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000919 DefaultFunctionArrayConversion(rExpr);
Steve Naroff90045e82007-07-13 23:32:42 +0000920
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000921 return CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff90045e82007-07-13 23:32:42 +0000922}
923
924Sema::AssignmentCheckResult
925Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
926 return CheckAssignmentConstraints(lhsType, rhsType);
927}
928
Steve Naroff49b45262007-07-13 16:58:59 +0000929inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 Diag(loc, diag::err_typecheck_invalid_operands,
931 lex->getType().getAsString(), rex->getType().getAsString(),
932 lex->getSourceRange(), rex->getSourceRange());
933}
934
Steve Naroff49b45262007-07-13 16:58:59 +0000935inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
936 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000937 QualType lhsType = lex->getType(), rhsType = rex->getType();
938
939 // make sure the vector types are identical.
940 if (lhsType == rhsType)
941 return lhsType;
942 // You cannot convert between vector values of different size.
943 Diag(loc, diag::err_typecheck_vector_not_convertable,
944 lex->getType().getAsString(), rex->getType().getAsString(),
945 lex->getSourceRange(), rex->getSourceRange());
946 return QualType();
947}
948
949inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff49b45262007-07-13 16:58:59 +0000950 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +0000951{
Steve Naroff90045e82007-07-13 23:32:42 +0000952 QualType lhsType = lex->getType(), rhsType = rex->getType();
953
954 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +0000955 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +0000956
Steve Naroffa4332e22007-07-17 00:58:39 +0000957 UsualArithmeticConversions(lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +0000958
Steve Naroffa4332e22007-07-17 00:58:39 +0000959 // handle the common case first (both operands are arithmetic).
960 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
961 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000962 InvalidOperands(loc, lex, rex);
963 return QualType();
964}
965
966inline QualType Sema::CheckRemainderOperands(
Steve Naroff49b45262007-07-13 16:58:59 +0000967 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +0000968{
Steve Naroff90045e82007-07-13 23:32:42 +0000969 QualType lhsType = lex->getType(), rhsType = rex->getType();
970
Steve Naroffa4332e22007-07-17 00:58:39 +0000971 UsualArithmeticConversions(lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +0000972
Steve Naroffa4332e22007-07-17 00:58:39 +0000973 // handle the common case first (both operands are arithmetic).
974 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
975 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 InvalidOperands(loc, lex, rex);
977 return QualType();
978}
979
980inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff49b45262007-07-13 16:58:59 +0000981 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +0000982{
Steve Naroff3e5e5562007-07-16 22:23:01 +0000983 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +0000984 return CheckVectorOperands(loc, lex, rex);
985
Steve Naroffa4332e22007-07-17 00:58:39 +0000986 UsualArithmeticConversions(lex, rex);
Steve Naroff3e5e5562007-07-16 22:23:01 +0000987
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +0000989 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
990 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000991
Steve Naroffa4332e22007-07-17 00:58:39 +0000992 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
993 return lex->getType();
994 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
995 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000996 InvalidOperands(loc, lex, rex);
997 return QualType();
998}
999
1000inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff49b45262007-07-13 16:58:59 +00001001 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001002{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001003 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001004 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001005
Steve Naroffa4332e22007-07-17 00:58:39 +00001006 UsualArithmeticConversions(lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001007
1008 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001009 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1010 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001011
1012 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroffa4332e22007-07-17 00:58:39 +00001013 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001014 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
Chris Lattner8b9023b2007-07-13 03:05:23 +00001015 return Context.getPointerDiffType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001016 InvalidOperands(loc, lex, rex);
1017 return QualType();
1018}
1019
1020inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff49b45262007-07-13 16:58:59 +00001021 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001022{
1023 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1024 // for int << longlong -> the result type should be int, not long long.
Steve Naroffa4332e22007-07-17 00:58:39 +00001025 UsualArithmeticConversions(lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001026
Steve Naroffa4332e22007-07-17 00:58:39 +00001027 // handle the common case first (both operands are arithmetic).
1028 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1029 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 InvalidOperands(loc, lex, rex);
1031 return QualType();
1032}
1033
1034inline QualType Sema::CheckRelationalOperands( // C99 6.5.8
Steve Naroff49b45262007-07-13 16:58:59 +00001035 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001036{
Steve Naroff30bf7712007-08-10 18:26:40 +00001037 // C99 6.5.8p3
1038 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1039 UsualArithmeticConversions(lex, rex);
1040 else {
1041 UsualUnaryConversions(lex);
1042 UsualUnaryConversions(rex);
1043 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001044 QualType lType = lex->getType();
1045 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001046
1047 if (lType->isRealType() && rType->isRealType())
1048 return Context.IntTy;
1049
1050 if (lType->isPointerType()) {
1051 if (rType->isPointerType())
1052 return Context.IntTy;
1053 if (rType->isIntegerType()) {
Chris Lattner590b6642007-07-15 23:26:56 +00001054 if (!rex->isNullPointerConstant(Context))
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1056 lex->getSourceRange(), rex->getSourceRange());
1057 return Context.IntTy; // the previous diagnostic is a GCC extension.
1058 }
1059 } else if (rType->isPointerType()) {
1060 if (lType->isIntegerType()) {
Chris Lattner590b6642007-07-15 23:26:56 +00001061 if (!lex->isNullPointerConstant(Context))
Reid Spencer5f016e22007-07-11 17:01:13 +00001062 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1063 lex->getSourceRange(), rex->getSourceRange());
1064 return Context.IntTy; // the previous diagnostic is a GCC extension.
1065 }
1066 }
1067 InvalidOperands(loc, lex, rex);
1068 return QualType();
1069}
1070
1071inline QualType Sema::CheckEqualityOperands( // C99 6.5.9
Steve Naroff49b45262007-07-13 16:58:59 +00001072 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001073{
Steve Naroff30bf7712007-08-10 18:26:40 +00001074 // C99 6.5.9p4
1075 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1076 UsualArithmeticConversions(lex, rex);
1077 else {
1078 UsualUnaryConversions(lex);
1079 UsualUnaryConversions(rex);
1080 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001081 QualType lType = lex->getType();
1082 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001083
1084 if (lType->isArithmeticType() && rType->isArithmeticType())
1085 return Context.IntTy;
1086
1087 if (lType->isPointerType()) {
1088 if (rType->isPointerType())
1089 return Context.IntTy;
1090 if (rType->isIntegerType()) {
Chris Lattner590b6642007-07-15 23:26:56 +00001091 if (!rex->isNullPointerConstant(Context))
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1093 lex->getSourceRange(), rex->getSourceRange());
1094 return Context.IntTy; // the previous diagnostic is a GCC extension.
1095 }
1096 } else if (rType->isPointerType()) {
1097 if (lType->isIntegerType()) {
Chris Lattner590b6642007-07-15 23:26:56 +00001098 if (!lex->isNullPointerConstant(Context))
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1100 lex->getSourceRange(), rex->getSourceRange());
1101 return Context.IntTy; // the previous diagnostic is a GCC extension.
1102 }
1103 }
1104 InvalidOperands(loc, lex, rex);
1105 return QualType();
1106}
1107
1108inline QualType Sema::CheckBitwiseOperands(
Steve Naroff49b45262007-07-13 16:58:59 +00001109 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001110{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001111 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001113
Steve Naroffa4332e22007-07-17 00:58:39 +00001114 UsualArithmeticConversions(lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001115
Steve Naroffa4332e22007-07-17 00:58:39 +00001116 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1117 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 InvalidOperands(loc, lex, rex);
1119 return QualType();
1120}
1121
1122inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001123 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001124{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001125 UsualUnaryConversions(lex);
1126 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001127
Steve Naroffa4332e22007-07-17 00:58:39 +00001128 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 return Context.IntTy;
1130 InvalidOperands(loc, lex, rex);
1131 return QualType();
1132}
1133
1134inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
1135 Expr *lex, Expr *rex, SourceLocation loc, QualType compoundType)
1136{
1137 QualType lhsType = lex->getType();
1138 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1139 bool hadError = false;
1140 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1141
1142 switch (mlval) { // C99 6.5.16p2
1143 case Expr::MLV_Valid:
1144 break;
1145 case Expr::MLV_ConstQualified:
1146 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1147 hadError = true;
1148 break;
1149 case Expr::MLV_ArrayType:
1150 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1151 lhsType.getAsString(), lex->getSourceRange());
1152 return QualType();
1153 case Expr::MLV_NotObjectType:
1154 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1155 lhsType.getAsString(), lex->getSourceRange());
1156 return QualType();
1157 case Expr::MLV_InvalidExpression:
1158 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1159 lex->getSourceRange());
1160 return QualType();
1161 case Expr::MLV_IncompleteType:
1162 case Expr::MLV_IncompleteVoidType:
1163 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1164 lhsType.getAsString(), lex->getSourceRange());
1165 return QualType();
Steve Narofffec0b492007-07-30 03:29:09 +00001166 case Expr::MLV_DuplicateVectorComponents:
1167 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1168 lex->getSourceRange());
1169 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001170 }
Steve Naroff90045e82007-07-13 23:32:42 +00001171 AssignmentCheckResult result;
1172
1173 if (compoundType.isNull())
1174 result = CheckSingleAssignmentConstraints(lhsType, rex);
1175 else
1176 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001177
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 // decode the result (notice that extensions still return a type).
1179 switch (result) {
1180 case Compatible:
1181 break;
1182 case Incompatible:
1183 Diag(loc, diag::err_typecheck_assign_incompatible,
1184 lhsType.getAsString(), rhsType.getAsString(),
1185 lex->getSourceRange(), rex->getSourceRange());
1186 hadError = true;
1187 break;
1188 case PointerFromInt:
1189 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +00001190 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1192 lhsType.getAsString(), rhsType.getAsString(),
1193 lex->getSourceRange(), rex->getSourceRange());
1194 }
1195 break;
1196 case IntFromPointer:
1197 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1198 lhsType.getAsString(), rhsType.getAsString(),
1199 lex->getSourceRange(), rex->getSourceRange());
1200 break;
1201 case IncompatiblePointer:
1202 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1203 lhsType.getAsString(), rhsType.getAsString(),
1204 lex->getSourceRange(), rex->getSourceRange());
1205 break;
1206 case CompatiblePointerDiscardsQualifiers:
1207 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1208 lhsType.getAsString(), rhsType.getAsString(),
1209 lex->getSourceRange(), rex->getSourceRange());
1210 break;
1211 }
1212 // C99 6.5.16p3: The type of an assignment expression is the type of the
1213 // left operand unless the left operand has qualified type, in which case
1214 // it is the unqualified version of the type of the left operand.
1215 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1216 // is converted to the type of the assignment expression (above).
1217 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1218 return hadError ? QualType() : lhsType.getUnqualifiedType();
1219}
1220
1221inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001222 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001223 UsualUnaryConversions(rex);
1224 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001225}
1226
Steve Naroff49b45262007-07-13 16:58:59 +00001227/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1228/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001229QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001230 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 assert(!resType.isNull() && "no type for increment/decrement expression");
1232
1233 // C99 6.5.2.4p1
1234 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1235 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1236 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1237 resType.getAsString(), op->getSourceRange());
1238 return QualType();
1239 }
1240 } else if (!resType->isRealType()) {
1241 // FIXME: Allow Complex as a GCC extension.
1242 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1243 resType.getAsString(), op->getSourceRange());
1244 return QualType();
1245 }
1246 // At this point, we know we have a real or pointer type. Now make sure
1247 // the operand is a modifiable lvalue.
1248 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1249 if (mlval != Expr::MLV_Valid) {
1250 // FIXME: emit a more precise diagnostic...
1251 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1252 op->getSourceRange());
1253 return QualType();
1254 }
1255 return resType;
1256}
1257
1258/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1259/// This routine allows us to typecheck complex/recursive expressions
1260/// where the declaration is needed for type checking. Here are some
1261/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1262static Decl *getPrimaryDeclaration(Expr *e) {
1263 switch (e->getStmtClass()) {
1264 case Stmt::DeclRefExprClass:
1265 return cast<DeclRefExpr>(e)->getDecl();
1266 case Stmt::MemberExprClass:
1267 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1268 case Stmt::ArraySubscriptExprClass:
1269 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1270 case Stmt::CallExprClass:
1271 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1272 case Stmt::UnaryOperatorClass:
1273 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1274 case Stmt::ParenExprClass:
1275 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1276 default:
1277 return 0;
1278 }
1279}
1280
1281/// CheckAddressOfOperand - The operand of & must be either a function
1282/// designator or an lvalue designating an object. If it is an lvalue, the
1283/// object cannot be declared with storage class register or be a bit field.
1284/// Note: The usual conversions are *not* applied to the operand of the &
1285/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1286QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1287 Decl *dcl = getPrimaryDeclaration(op);
1288 Expr::isLvalueResult lval = op->isLvalue();
1289
1290 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1291 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1292 ;
1293 else { // FIXME: emit more specific diag...
1294 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1295 op->getSourceRange());
1296 return QualType();
1297 }
1298 } else if (dcl) {
1299 // We have an lvalue with a decl. Make sure the decl is not declared
1300 // with the register storage-class specifier.
1301 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1302 if (vd->getStorageClass() == VarDecl::Register) {
1303 Diag(OpLoc, diag::err_typecheck_address_of_register,
1304 op->getSourceRange());
1305 return QualType();
1306 }
1307 } else
1308 assert(0 && "Unknown/unexpected decl type");
1309
1310 // FIXME: add check for bitfields!
1311 }
1312 // If the operand has type "type", the result has type "pointer to type".
1313 return Context.getPointerType(op->getType());
1314}
1315
1316QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001317 UsualUnaryConversions(op);
1318 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001319
Chris Lattnerbefee482007-07-31 16:53:04 +00001320 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 QualType ptype = PT->getPointeeType();
1322 // C99 6.5.3.2p4. "if it points to an object,...".
1323 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1324 // GCC compat: special case 'void *' (treat as warning).
1325 if (ptype->isVoidType()) {
1326 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1327 qType.getAsString(), op->getSourceRange());
1328 } else {
1329 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1330 ptype.getAsString(), op->getSourceRange());
1331 return QualType();
1332 }
1333 }
1334 return ptype;
1335 }
1336 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1337 qType.getAsString(), op->getSourceRange());
1338 return QualType();
1339}
1340
1341static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1342 tok::TokenKind Kind) {
1343 BinaryOperator::Opcode Opc;
1344 switch (Kind) {
1345 default: assert(0 && "Unknown binop!");
1346 case tok::star: Opc = BinaryOperator::Mul; break;
1347 case tok::slash: Opc = BinaryOperator::Div; break;
1348 case tok::percent: Opc = BinaryOperator::Rem; break;
1349 case tok::plus: Opc = BinaryOperator::Add; break;
1350 case tok::minus: Opc = BinaryOperator::Sub; break;
1351 case tok::lessless: Opc = BinaryOperator::Shl; break;
1352 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1353 case tok::lessequal: Opc = BinaryOperator::LE; break;
1354 case tok::less: Opc = BinaryOperator::LT; break;
1355 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1356 case tok::greater: Opc = BinaryOperator::GT; break;
1357 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1358 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1359 case tok::amp: Opc = BinaryOperator::And; break;
1360 case tok::caret: Opc = BinaryOperator::Xor; break;
1361 case tok::pipe: Opc = BinaryOperator::Or; break;
1362 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1363 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1364 case tok::equal: Opc = BinaryOperator::Assign; break;
1365 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1366 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1367 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1368 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1369 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1370 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1371 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1372 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1373 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1374 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1375 case tok::comma: Opc = BinaryOperator::Comma; break;
1376 }
1377 return Opc;
1378}
1379
1380static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1381 tok::TokenKind Kind) {
1382 UnaryOperator::Opcode Opc;
1383 switch (Kind) {
1384 default: assert(0 && "Unknown unary op!");
1385 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1386 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1387 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1388 case tok::star: Opc = UnaryOperator::Deref; break;
1389 case tok::plus: Opc = UnaryOperator::Plus; break;
1390 case tok::minus: Opc = UnaryOperator::Minus; break;
1391 case tok::tilde: Opc = UnaryOperator::Not; break;
1392 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1393 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1394 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1395 case tok::kw___real: Opc = UnaryOperator::Real; break;
1396 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1397 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1398 }
1399 return Opc;
1400}
1401
1402// Binary Operators. 'Tok' is the token for the operator.
1403Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1404 ExprTy *LHS, ExprTy *RHS) {
1405 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1406 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1407
1408 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1409 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1410
1411 QualType ResultTy; // Result type of the binary operator.
1412 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1413
1414 switch (Opc) {
1415 default:
1416 assert(0 && "Unknown binary expr!");
1417 case BinaryOperator::Assign:
1418 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1419 break;
1420 case BinaryOperator::Mul:
1421 case BinaryOperator::Div:
1422 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1423 break;
1424 case BinaryOperator::Rem:
1425 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1426 break;
1427 case BinaryOperator::Add:
1428 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1429 break;
1430 case BinaryOperator::Sub:
1431 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1432 break;
1433 case BinaryOperator::Shl:
1434 case BinaryOperator::Shr:
1435 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1436 break;
1437 case BinaryOperator::LE:
1438 case BinaryOperator::LT:
1439 case BinaryOperator::GE:
1440 case BinaryOperator::GT:
1441 ResultTy = CheckRelationalOperands(lhs, rhs, TokLoc);
1442 break;
1443 case BinaryOperator::EQ:
1444 case BinaryOperator::NE:
1445 ResultTy = CheckEqualityOperands(lhs, rhs, TokLoc);
1446 break;
1447 case BinaryOperator::And:
1448 case BinaryOperator::Xor:
1449 case BinaryOperator::Or:
1450 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1451 break;
1452 case BinaryOperator::LAnd:
1453 case BinaryOperator::LOr:
1454 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1455 break;
1456 case BinaryOperator::MulAssign:
1457 case BinaryOperator::DivAssign:
1458 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1459 if (!CompTy.isNull())
1460 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1461 break;
1462 case BinaryOperator::RemAssign:
1463 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1464 if (!CompTy.isNull())
1465 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1466 break;
1467 case BinaryOperator::AddAssign:
1468 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1469 if (!CompTy.isNull())
1470 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1471 break;
1472 case BinaryOperator::SubAssign:
1473 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1474 if (!CompTy.isNull())
1475 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1476 break;
1477 case BinaryOperator::ShlAssign:
1478 case BinaryOperator::ShrAssign:
1479 CompTy = CheckShiftOperands(lhs, rhs, TokLoc);
1480 if (!CompTy.isNull())
1481 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1482 break;
1483 case BinaryOperator::AndAssign:
1484 case BinaryOperator::XorAssign:
1485 case BinaryOperator::OrAssign:
1486 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1487 if (!CompTy.isNull())
1488 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1489 break;
1490 case BinaryOperator::Comma:
1491 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1492 break;
1493 }
1494 if (ResultTy.isNull())
1495 return true;
1496 if (CompTy.isNull())
1497 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1498 else
1499 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1500}
1501
1502// Unary Operators. 'Tok' is the token for the operator.
1503Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1504 ExprTy *input) {
1505 Expr *Input = (Expr*)input;
1506 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1507 QualType resultType;
1508 switch (Opc) {
1509 default:
1510 assert(0 && "Unimplemented unary expr!");
1511 case UnaryOperator::PreInc:
1512 case UnaryOperator::PreDec:
1513 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1514 break;
1515 case UnaryOperator::AddrOf:
1516 resultType = CheckAddressOfOperand(Input, OpLoc);
1517 break;
1518 case UnaryOperator::Deref:
1519 resultType = CheckIndirectionOperand(Input, OpLoc);
1520 break;
1521 case UnaryOperator::Plus:
1522 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001523 UsualUnaryConversions(Input);
1524 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1526 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1527 resultType.getAsString());
1528 break;
1529 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001530 UsualUnaryConversions(Input);
1531 resultType = Input->getType();
Steve Naroffc63b96a2007-07-12 21:46:55 +00001532 if (!resultType->isIntegerType()) // C99 6.5.3.3p1
1533 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1534 resultType.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 break;
1536 case UnaryOperator::LNot: // logical negation
1537 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001538 DefaultFunctionArrayConversion(Input);
1539 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1541 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1542 resultType.getAsString());
1543 // LNot always has type int. C99 6.5.3.3p5.
1544 resultType = Context.IntTy;
1545 break;
1546 case UnaryOperator::SizeOf:
1547 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1548 break;
1549 case UnaryOperator::AlignOf:
1550 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1551 break;
1552 case UnaryOperator::Extension:
1553 // FIXME: does __extension__ cause any promotions? I would think not.
1554 resultType = Input->getType();
1555 break;
1556 }
1557 if (resultType.isNull())
1558 return true;
1559 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1560}
1561
1562/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1563Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1564 SourceLocation LabLoc,
1565 IdentifierInfo *LabelII) {
1566 // Look up the record for this label identifier.
1567 LabelStmt *&LabelDecl = LabelMap[LabelII];
1568
1569 // If we haven't seen this label yet, create a forward reference.
1570 if (LabelDecl == 0)
1571 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1572
1573 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001574 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1575 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001576}
1577
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001578Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1579 SourceLocation RPLoc) { // "({..})"
1580 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1581 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1582 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1583
1584 // FIXME: there are a variety of strange constraints to enforce here, for
1585 // example, it is not possible to goto into a stmt expression apparently.
1586 // More semantic analysis is needed.
1587
1588 // FIXME: the last statement in the compount stmt has its value used. We
1589 // should not warn about it being unused.
1590
1591 // If there are sub stmts in the compound stmt, take the type of the last one
1592 // as the type of the stmtexpr.
1593 QualType Ty = Context.VoidTy;
1594
1595 if (!Compound->body_empty())
1596 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1597 Ty = LastExpr->getType();
1598
1599 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1600}
Steve Naroffd34e9152007-08-01 22:05:33 +00001601
Steve Naroff363bcff2007-08-01 23:45:51 +00001602Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00001603 TypeTy *arg1, TypeTy *arg2,
1604 SourceLocation RPLoc) {
1605 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1606 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1607
1608 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1609
Steve Naroff363bcff2007-08-01 23:45:51 +00001610 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2, RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00001611}
1612
Steve Naroffd04fdd52007-08-03 21:21:27 +00001613Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1614 ExprTy *expr1, ExprTy *expr2,
1615 SourceLocation RPLoc) {
1616 Expr *CondExpr = static_cast<Expr*>(cond);
1617 Expr *LHSExpr = static_cast<Expr*>(expr1);
1618 Expr *RHSExpr = static_cast<Expr*>(expr2);
1619
1620 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1621
1622 // The conditional expression is required to be a constant expression.
1623 llvm::APSInt condEval(32);
1624 SourceLocation ExpLoc;
1625 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1626 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1627 CondExpr->getSourceRange());
1628
1629 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1630 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1631 RHSExpr->getType();
1632 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1633}
1634