blob: 00838f79c1b9cc73c1694c9cb67380c78dfd882e [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
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"
25using namespace clang;
26
27/// ParseStringLiteral - The specified tokens were lexed as pasted string
28/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
29/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
30/// multiple tokens. However, the common case is that StringToks points to one
31/// string.
32///
33Action::ExprResult
34Sema::ParseStringLiteral(const Token *StringToks, unsigned NumStringToks) {
35 assert(NumStringToks && "Must have at least one string!");
36
37 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
38 if (Literal.hadError)
39 return ExprResult(true);
40
41 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
42 for (unsigned i = 0; i != NumStringToks; ++i)
43 StringTokLocs.push_back(StringToks[i].getLocation());
44
45 // FIXME: handle wchar_t
46 QualType t = Context.getPointerType(Context.CharTy);
47
48 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
49 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
50 Literal.AnyWide, t, StringToks[0].getLocation(),
51 StringToks[NumStringToks-1].getLocation());
52}
53
54
55/// ParseIdentifierExpr - The parser read an identifier in expression context,
56/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
57/// identifier is used in an function call context.
58Sema::ExprResult Sema::ParseIdentifierExpr(Scope *S, SourceLocation Loc,
59 IdentifierInfo &II,
60 bool HasTrailingLParen) {
61 // Could be enum-constant or decl.
62 Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
63 if (D == 0) {
64 // Otherwise, this could be an implicitly declared function reference (legal
65 // in C90, extension in C99).
66 if (HasTrailingLParen &&
67 // Not in C++.
68 !getLangOptions().CPlusPlus)
69 D = ImplicitlyDefineFunction(Loc, II, S);
70 else {
71 // If this name wasn't predeclared and if this is not a function call,
72 // diagnose the problem.
73 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
74 }
75 }
76
77 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");
83 abort();
84}
85
86Sema::ExprResult Sema::ParsePreDefinedExpr(SourceLocation Loc,
87 tok::TokenKind Kind) {
88 PreDefinedExpr::IdentType IT;
89
90 switch (Kind) {
91 default:
92 assert(0 && "Unknown simple primary expr!");
93 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
94 IT = PreDefinedExpr::Func;
95 break;
96 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
97 IT = PreDefinedExpr::Function;
98 break;
99 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
100 IT = PreDefinedExpr::PrettyFunction;
101 break;
102 }
103
104 // Pre-defined identifiers are always of type char *.
105 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
106}
107
108Sema::ExprResult Sema::ParseCharacterConstant(const Token &Tok) {
109 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
122Action::ExprResult Sema::ParseNumericConstant(const Token &Tok) {
123 // 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
128 unsigned IntSize = Context.getTypeSize(Context.IntTy, Tok.getLocation());
129 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;
154 assert(Context.getTypeSize(t, Tok.getLocation()) ==
155 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?
166 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
167 // 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) {
182 unsigned LongSize = Context.getTypeSize(Context.LongTy,
183 Tok.getLocation());
184
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 =
200 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
201
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) {
292 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
293
294 // Perform default conversions.
295 DefaultFunctionArrayConversion(LHSExp);
296 DefaultFunctionArrayConversion(RHSExp);
297
298 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
299
300 // 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.
304 Expr *BaseExpr, *IndexExpr;
305 QualType ResultType;
306 if (const PointerType *PTy = LHSTy->isPointerType()) {
307 BaseExpr = LHSExp;
308 IndexExpr = RHSExp;
309 // FIXME: need to deal with const...
310 ResultType = PTy->getPointeeType();
311 } else if (const PointerType *PTy = RHSTy->isPointerType()) {
312 // Handle the uncommon case of "123[Ptr]".
313 BaseExpr = RHSExp;
314 IndexExpr = LHSExp;
315 // FIXME: need to deal with const...
316 ResultType = PTy->getPointeeType();
317 } else if (const VectorType *VTy = LHSTy->isVectorType()) { // vectors: V[123]
318 BaseExpr = LHSExp;
319 IndexExpr = RHSExp;
320 // FIXME: need to deal with const...
321 ResultType = VTy->getElementType();
322 } else {
323 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
324 RHSExp->getSourceRange());
325 }
326 // C99 6.5.2.1p1
327 if (!IndexExpr->getType()->isIntegerType())
328 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
329 IndexExpr->getSourceRange());
330
331 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
332 // the following check catches trying to index a pointer to a function (e.g.
333 // void (*)(int)). Functions are not objects in C99.
334 if (!ResultType->isObjectType())
335 return Diag(BaseExpr->getLocStart(),
336 diag::err_typecheck_subscript_not_object,
337 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
338
339 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
340}
341
342Action::ExprResult Sema::
343ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
344 tok::TokenKind OpKind, SourceLocation MemberLoc,
345 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000346 Expr *BaseExpr = static_cast<Expr *>(Base);
347 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000348
Steve Naroff2cb66382007-07-26 03:11:44 +0000349 QualType BaseType = BaseExpr->getType();
350 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000351
Chris Lattner4b009652007-07-25 00:24:17 +0000352 if (OpKind == tok::arrow) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000353 if (const PointerType *PT = BaseType->isPointerType())
354 BaseType = PT->getPointeeType();
355 else
356 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
357 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000358 }
Steve Naroff2cb66382007-07-26 03:11:44 +0000359 // Get the member decl from the struct/union definition.
360 FieldDecl *MemberDecl;
361 if (const RecordType *RTy = BaseType->isRecordType()) {
362 RecordDecl *RDecl = RTy->getDecl();
363 if (RTy->isIncompleteType())
364 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
365 BaseExpr->getSourceRange());
366 // The record definition is complete, now make sure the member is valid.
367 if (!(MemberDecl = RDecl->getMember(&Member)))
368 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
369 SourceRange(MemberLoc));
370 } else
371 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
372 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000373
Steve Naroff2cb66382007-07-26 03:11:44 +0000374 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl, MemberLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000375}
376
377/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
378/// This provides the location of the left/right parens and a list of comma
379/// locations.
380Action::ExprResult Sema::
381ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
382 ExprTy **args, unsigned NumArgsInCall,
383 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
384 Expr *Fn = static_cast<Expr *>(fn);
385 Expr **Args = reinterpret_cast<Expr**>(args);
386 assert(Fn && "no function call expression");
387
388 UsualUnaryConversions(Fn);
389 QualType funcType = Fn->getType();
390
391 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
392 // type pointer to function".
393 const PointerType *PT = dyn_cast<PointerType>(funcType);
394 if (PT == 0) PT = dyn_cast<PointerType>(funcType.getCanonicalType());
395
396 if (PT == 0)
397 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
398 SourceRange(Fn->getLocStart(), RParenLoc));
399
400 const FunctionType *funcT = dyn_cast<FunctionType>(PT->getPointeeType());
401 if (funcT == 0)
402 funcT = dyn_cast<FunctionType>(PT->getPointeeType().getCanonicalType());
403
404 if (funcT == 0)
405 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
406 SourceRange(Fn->getLocStart(), RParenLoc));
407
408 // If a prototype isn't declared, the parser implicitly defines a func decl
409 QualType resultType = funcT->getResultType();
410
411 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
412 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
413 // assignment, to the types of the corresponding parameter, ...
414
415 unsigned NumArgsInProto = proto->getNumArgs();
416 unsigned NumArgsToCheck = NumArgsInCall;
417
418 if (NumArgsInCall < NumArgsInProto)
419 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
420 Fn->getSourceRange());
421 else if (NumArgsInCall > NumArgsInProto) {
422 if (!proto->isVariadic()) {
423 Diag(Args[NumArgsInProto]->getLocStart(),
424 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
425 SourceRange(Args[NumArgsInProto]->getLocStart(),
426 Args[NumArgsInCall-1]->getLocEnd()));
427 }
428 NumArgsToCheck = NumArgsInProto;
429 }
430 // Continue to check argument types (even if we have too few/many args).
431 for (unsigned i = 0; i < NumArgsToCheck; i++) {
432 Expr *argExpr = Args[i];
433 assert(argExpr && "ParseCallExpr(): missing argument expression");
434
435 QualType lhsType = proto->getArgType(i);
436 QualType rhsType = argExpr->getType();
437
Steve Naroff75644062007-07-25 20:45:33 +0000438 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattner4b009652007-07-25 00:24:17 +0000439 if (const ArrayType *ary = lhsType->isArrayType())
440 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000441 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000442 lhsType = Context.getPointerType(lhsType);
443
444 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
445 argExpr);
446 SourceLocation l = argExpr->getLocStart();
447
448 // decode the result (notice that AST's are still created for extensions).
449 switch (result) {
450 case Compatible:
451 break;
452 case PointerFromInt:
453 // check for null pointer constant (C99 6.3.2.3p3)
454 if (!argExpr->isNullPointerConstant(Context)) {
455 Diag(l, diag::ext_typecheck_passing_pointer_int,
456 lhsType.getAsString(), rhsType.getAsString(),
457 Fn->getSourceRange(), argExpr->getSourceRange());
458 }
459 break;
460 case IntFromPointer:
461 Diag(l, diag::ext_typecheck_passing_pointer_int,
462 lhsType.getAsString(), rhsType.getAsString(),
463 Fn->getSourceRange(), argExpr->getSourceRange());
464 break;
465 case IncompatiblePointer:
466 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
467 rhsType.getAsString(), lhsType.getAsString(),
468 Fn->getSourceRange(), argExpr->getSourceRange());
469 break;
470 case CompatiblePointerDiscardsQualifiers:
471 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
472 rhsType.getAsString(), lhsType.getAsString(),
473 Fn->getSourceRange(), argExpr->getSourceRange());
474 break;
475 case Incompatible:
476 return Diag(l, diag::err_typecheck_passing_incompatible,
477 rhsType.getAsString(), lhsType.getAsString(),
478 Fn->getSourceRange(), argExpr->getSourceRange());
479 }
480 }
481 // Even if the types checked, bail if we had the wrong number of arguments.
482 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
483 return true;
484 }
485 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
486}
487
488Action::ExprResult Sema::
489ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
490 SourceLocation RParenLoc, ExprTy *InitExpr) {
491 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
492 QualType literalType = QualType::getFromOpaquePtr(Ty);
493 // FIXME: put back this assert when initializers are worked out.
494 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
495 Expr *literalExpr = static_cast<Expr*>(InitExpr);
496
497 // FIXME: add semantic analysis (C99 6.5.2.5).
498 return new CompoundLiteralExpr(literalType, literalExpr);
499}
500
501Action::ExprResult Sema::
502ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
503 SourceLocation RParenLoc) {
504 // FIXME: add semantic analysis (C99 6.7.8). This involves
505 // knowledge of the object being intialized. As a result, the code for
506 // doing the semantic analysis will likely be located elsewhere (i.e. in
507 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
508 return false; // FIXME instantiate an InitListExpr.
509}
510
511Action::ExprResult Sema::
512ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
513 SourceLocation RParenLoc, ExprTy *Op) {
514 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
515
516 Expr *castExpr = static_cast<Expr*>(Op);
517 QualType castType = QualType::getFromOpaquePtr(Ty);
518
519 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
520 // type needs to be scalar.
521 if (!castType->isScalarType() && !castType->isVoidType()) {
522 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
523 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
524 }
525 if (!castExpr->getType()->isScalarType()) {
526 return Diag(castExpr->getLocStart(),
527 diag::err_typecheck_expect_scalar_operand,
528 castExpr->getType().getAsString(), castExpr->getSourceRange());
529 }
530 return new CastExpr(castType, castExpr, LParenLoc);
531}
532
533inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
534 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
535 UsualUnaryConversions(cond);
536 UsualUnaryConversions(lex);
537 UsualUnaryConversions(rex);
538 QualType condT = cond->getType();
539 QualType lexT = lex->getType();
540 QualType rexT = rex->getType();
541
542 // first, check the condition.
543 if (!condT->isScalarType()) { // C99 6.5.15p2
544 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
545 condT.getAsString());
546 return QualType();
547 }
548 // now check the two expressions.
549 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
550 UsualArithmeticConversions(lex, rex);
551 return lex->getType();
552 }
553 if ((lexT->isStructureType() && rexT->isStructureType()) || // C99 6.5.15p3
554 (lexT->isUnionType() && rexT->isUnionType())) {
555 TagType *lTag = cast<TagType>(lexT.getCanonicalType());
556 TagType *rTag = cast<TagType>(rexT.getCanonicalType());
557
558 if (lTag->getDecl()->getIdentifier() == rTag->getDecl()->getIdentifier())
559 return lexT;
560 else {
561 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
562 lexT.getAsString(), rexT.getAsString(),
563 lex->getSourceRange(), rex->getSourceRange());
564 return QualType();
565 }
566 }
567 // C99 6.5.15p3
568 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
569 return lexT;
570 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
571 return rexT;
572
573 if (lexT->isPointerType() && rexT->isPointerType()) { // C99 6.5.15p3,6
574 QualType lhptee, rhptee;
575
576 // get the "pointed to" type
577 lhptee = cast<PointerType>(lexT.getCanonicalType())->getPointeeType();
578 rhptee = cast<PointerType>(rexT.getCanonicalType())->getPointeeType();
579
580 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
581 if (lhptee.getUnqualifiedType()->isVoidType() &&
582 (rhptee->isObjectType() || rhptee->isIncompleteType()))
583 return lexT;
584 if (rhptee.getUnqualifiedType()->isVoidType() &&
585 (lhptee->isObjectType() || lhptee->isIncompleteType()))
586 return rexT;
587
Chris Lattner4b009652007-07-25 00:24:17 +0000588 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
589 rhptee.getUnqualifiedType())) {
590 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
591 lexT.getAsString(), rexT.getAsString(),
592 lex->getSourceRange(), rex->getSourceRange());
593 return lexT; // FIXME: this is an _ext - is this return o.k?
594 }
Steve Naroffdd598cf2007-07-26 14:35:56 +0000595 // The pointer types are compatible.
596 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
597 // differently qualified versions of compatible types, the result type is a
598 // pointer to an appropriately qualified version of the *composite* type.
599 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000600 }
601 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
602 return lexT;
603
604 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
605 lexT.getAsString(), rexT.getAsString(),
606 lex->getSourceRange(), rex->getSourceRange());
607 return QualType();
608}
609
610/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
611/// in the case of a the GNU conditional expr extension.
612Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
613 SourceLocation ColonLoc,
614 ExprTy *Cond, ExprTy *LHS,
615 ExprTy *RHS) {
616 Expr *CondExpr = (Expr *) Cond;
617 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
618 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
619 RHSExpr, QuestionLoc);
620 if (result.isNull())
621 return true;
622 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
623}
624
625// promoteExprToType - a helper function to ensure we create exactly one
626// ImplicitCastExpr. As a convenience (to the caller), we return the type.
627static void promoteExprToType(Expr *&expr, QualType type) {
628 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
629 impCast->setType(type);
630 else
631 expr = new ImplicitCastExpr(type, expr);
632 return;
633}
634
635/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
636void Sema::DefaultFunctionArrayConversion(Expr *&e) {
637 QualType t = e->getType();
638 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
639
640 if (const ReferenceType *ref = t->isReferenceType()) {
641 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
642 t = e->getType();
643 }
644 if (t->isFunctionType())
645 promoteExprToType(e, Context.getPointerType(t));
646 else if (const ArrayType *ary = t->isArrayType())
647 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
648}
649
650/// UsualUnaryConversion - Performs various conversions that are common to most
651/// operators (C99 6.3). The conversions of array and function types are
652/// sometimes surpressed. For example, the array->pointer conversion doesn't
653/// apply if the array is an argument to the sizeof or address (&) operators.
654/// In these instances, this routine should *not* be called.
655void Sema::UsualUnaryConversions(Expr *&expr) {
656 QualType t = expr->getType();
657 assert(!t.isNull() && "UsualUnaryConversions - missing type");
658
659 if (const ReferenceType *ref = t->isReferenceType()) {
660 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
661 t = expr->getType();
662 }
663 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
664 promoteExprToType(expr, Context.IntTy);
665 else
666 DefaultFunctionArrayConversion(expr);
667}
668
669/// UsualArithmeticConversions - Performs various conversions that are common to
670/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
671/// routine returns the first non-arithmetic type found. The client is
672/// responsible for emitting appropriate error diagnostics.
673void Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr) {
674 UsualUnaryConversions(lhsExpr);
675 UsualUnaryConversions(rhsExpr);
676
677 QualType lhs = lhsExpr->getType();
678 QualType rhs = rhsExpr->getType();
679
680 // If both types are identical, no conversion is needed.
681 if (lhs == rhs)
682 return;
683
684 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
685 // The caller can deal with this (e.g. pointer + int).
686 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
687 return;
688
689 // At this point, we have two different arithmetic types.
690
691 // Handle complex types first (C99 6.3.1.8p1).
692 if (lhs->isComplexType() || rhs->isComplexType()) {
693 // if we have an integer operand, the result is the complex type.
694 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
695 promoteExprToType(rhsExpr, lhs);
696 return;
697 }
698 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
699 promoteExprToType(lhsExpr, rhs);
700 return;
701 }
702 // Two complex types. Convert the smaller operand to the bigger result.
703 if (Context.maxComplexType(lhs, rhs) == lhs) { // convert the rhs
704 promoteExprToType(rhsExpr, lhs);
705 return;
706 }
707 promoteExprToType(lhsExpr, rhs); // convert the lhs
708 return;
709 }
710 // Now handle "real" floating types (i.e. float, double, long double).
711 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
712 // if we have an integer operand, the result is the real floating type.
713 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
714 promoteExprToType(rhsExpr, lhs);
715 return;
716 }
717 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
718 promoteExprToType(lhsExpr, rhs);
719 return;
720 }
721 // We have two real floating types, float/complex combos were handled above.
722 // Convert the smaller operand to the bigger result.
723 if (Context.maxFloatingType(lhs, rhs) == lhs) { // convert the rhs
724 promoteExprToType(rhsExpr, lhs);
725 return;
726 }
727 promoteExprToType(lhsExpr, rhs); // convert the lhs
728 return;
729 }
730 // Finally, we have two differing integer types.
731 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
732 promoteExprToType(rhsExpr, lhs);
733 return;
734 }
735 promoteExprToType(lhsExpr, rhs); // convert the lhs
736 return;
737}
738
739// CheckPointerTypesForAssignment - This is a very tricky routine (despite
740// being closely modeled after the C99 spec:-). The odd characteristic of this
741// routine is it effectively iqnores the qualifiers on the top level pointee.
742// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
743// FIXME: add a couple examples in this comment.
744Sema::AssignmentCheckResult
745Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
746 QualType lhptee, rhptee;
747
748 // get the "pointed to" type (ignoring qualifiers at the top level)
749 lhptee = cast<PointerType>(lhsType.getCanonicalType())->getPointeeType();
750 rhptee = cast<PointerType>(rhsType.getCanonicalType())->getPointeeType();
751
752 // make sure we operate on the canonical type
753 lhptee = lhptee.getCanonicalType();
754 rhptee = rhptee.getCanonicalType();
755
756 AssignmentCheckResult r = Compatible;
757
758 // C99 6.5.16.1p1: This following citation is common to constraints
759 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
760 // qualifiers of the type *pointed to* by the right;
761 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
762 rhptee.getQualifiers())
763 r = CompatiblePointerDiscardsQualifiers;
764
765 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
766 // incomplete type and the other is a pointer to a qualified or unqualified
767 // version of void...
768 if (lhptee.getUnqualifiedType()->isVoidType() &&
769 (rhptee->isObjectType() || rhptee->isIncompleteType()))
770 ;
771 else if (rhptee.getUnqualifiedType()->isVoidType() &&
772 (lhptee->isObjectType() || lhptee->isIncompleteType()))
773 ;
774 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
775 // unqualified versions of compatible types, ...
776 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
777 rhptee.getUnqualifiedType()))
778 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
779 return r;
780}
781
782/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
783/// has code to accommodate several GCC extensions when type checking
784/// pointers. Here are some objectionable examples that GCC considers warnings:
785///
786/// int a, *pint;
787/// short *pshort;
788/// struct foo *pfoo;
789///
790/// pint = pshort; // warning: assignment from incompatible pointer type
791/// a = pint; // warning: assignment makes integer from pointer without a cast
792/// pint = a; // warning: assignment makes pointer from integer without a cast
793/// pint = pfoo; // warning: assignment from incompatible pointer type
794///
795/// As a result, the code for dealing with pointers is more complex than the
796/// C99 spec dictates.
797/// Note: the warning above turn into errors when -pedantic-errors is enabled.
798///
799Sema::AssignmentCheckResult
800Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
801 if (lhsType == rhsType) // common case, fast path...
802 return Compatible;
803
804 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
805 if (lhsType->isVectorType() || rhsType->isVectorType()) {
806 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
807 return Incompatible;
808 }
809 return Compatible;
810 } else if (lhsType->isPointerType()) {
811 if (rhsType->isIntegerType())
812 return PointerFromInt;
813
814 if (rhsType->isPointerType())
815 return CheckPointerTypesForAssignment(lhsType, rhsType);
816 } else if (rhsType->isPointerType()) {
817 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
818 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
819 return IntFromPointer;
820
821 if (lhsType->isPointerType())
822 return CheckPointerTypesForAssignment(lhsType, rhsType);
823 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
824 if (Type::tagTypesAreCompatible(lhsType, rhsType))
825 return Compatible;
826 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
827 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
828 return Compatible;
829 }
830 return Incompatible;
831}
832
833Sema::AssignmentCheckResult
834Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
835 // This check seems unnatural, however it is necessary to insure the proper
836 // conversion of functions/arrays. If the conversion were done for all
837 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
838 // expressions that surpress this implicit conversion (&, sizeof).
839 DefaultFunctionArrayConversion(rExpr);
840
841 return CheckAssignmentConstraints(lhsType, rExpr->getType());
842}
843
844Sema::AssignmentCheckResult
845Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
846 return CheckAssignmentConstraints(lhsType, rhsType);
847}
848
849inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
850 Diag(loc, diag::err_typecheck_invalid_operands,
851 lex->getType().getAsString(), rex->getType().getAsString(),
852 lex->getSourceRange(), rex->getSourceRange());
853}
854
855inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
856 Expr *&rex) {
857 QualType lhsType = lex->getType(), rhsType = rex->getType();
858
859 // make sure the vector types are identical.
860 if (lhsType == rhsType)
861 return lhsType;
862 // You cannot convert between vector values of different size.
863 Diag(loc, diag::err_typecheck_vector_not_convertable,
864 lex->getType().getAsString(), rex->getType().getAsString(),
865 lex->getSourceRange(), rex->getSourceRange());
866 return QualType();
867}
868
869inline QualType Sema::CheckMultiplyDivideOperands(
870 Expr *&lex, Expr *&rex, SourceLocation loc)
871{
872 QualType lhsType = lex->getType(), rhsType = rex->getType();
873
874 if (lhsType->isVectorType() || rhsType->isVectorType())
875 return CheckVectorOperands(loc, lex, rex);
876
877 UsualArithmeticConversions(lex, rex);
878
879 // handle the common case first (both operands are arithmetic).
880 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
881 return lex->getType();
882 InvalidOperands(loc, lex, rex);
883 return QualType();
884}
885
886inline QualType Sema::CheckRemainderOperands(
887 Expr *&lex, Expr *&rex, SourceLocation loc)
888{
889 QualType lhsType = lex->getType(), rhsType = rex->getType();
890
891 UsualArithmeticConversions(lex, rex);
892
893 // handle the common case first (both operands are arithmetic).
894 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
895 return lex->getType();
896 InvalidOperands(loc, lex, rex);
897 return QualType();
898}
899
900inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
901 Expr *&lex, Expr *&rex, SourceLocation loc)
902{
903 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
904 return CheckVectorOperands(loc, lex, rex);
905
906 UsualArithmeticConversions(lex, rex);
907
908 // handle the common case first (both operands are arithmetic).
909 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
910 return lex->getType();
911
912 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
913 return lex->getType();
914 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
915 return rex->getType();
916 InvalidOperands(loc, lex, rex);
917 return QualType();
918}
919
920inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
921 Expr *&lex, Expr *&rex, SourceLocation loc)
922{
923 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
924 return CheckVectorOperands(loc, lex, rex);
925
926 UsualArithmeticConversions(lex, rex);
927
928 // handle the common case first (both operands are arithmetic).
929 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
930 return lex->getType();
931
932 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
933 return lex->getType();
934 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
935 return Context.getPointerDiffType();
936 InvalidOperands(loc, lex, rex);
937 return QualType();
938}
939
940inline QualType Sema::CheckShiftOperands( // C99 6.5.7
941 Expr *&lex, Expr *&rex, SourceLocation loc)
942{
943 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
944 // for int << longlong -> the result type should be int, not long long.
945 UsualArithmeticConversions(lex, rex);
946
947 // handle the common case first (both operands are arithmetic).
948 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
949 return lex->getType();
950 InvalidOperands(loc, lex, rex);
951 return QualType();
952}
953
954inline QualType Sema::CheckRelationalOperands( // C99 6.5.8
955 Expr *&lex, Expr *&rex, SourceLocation loc)
956{
957 UsualUnaryConversions(lex);
958 UsualUnaryConversions(rex);
959 QualType lType = lex->getType();
960 QualType rType = rex->getType();
961
962 if (lType->isRealType() && rType->isRealType())
963 return Context.IntTy;
964
965 if (lType->isPointerType()) {
966 if (rType->isPointerType())
967 return Context.IntTy;
968 if (rType->isIntegerType()) {
969 if (!rex->isNullPointerConstant(Context))
970 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
971 lex->getSourceRange(), rex->getSourceRange());
972 return Context.IntTy; // the previous diagnostic is a GCC extension.
973 }
974 } else if (rType->isPointerType()) {
975 if (lType->isIntegerType()) {
976 if (!lex->isNullPointerConstant(Context))
977 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
978 lex->getSourceRange(), rex->getSourceRange());
979 return Context.IntTy; // the previous diagnostic is a GCC extension.
980 }
981 }
982 InvalidOperands(loc, lex, rex);
983 return QualType();
984}
985
986inline QualType Sema::CheckEqualityOperands( // C99 6.5.9
987 Expr *&lex, Expr *&rex, SourceLocation loc)
988{
989 UsualUnaryConversions(lex);
990 UsualUnaryConversions(rex);
991 QualType lType = lex->getType();
992 QualType rType = rex->getType();
993
994 if (lType->isArithmeticType() && rType->isArithmeticType())
995 return Context.IntTy;
996
997 if (lType->isPointerType()) {
998 if (rType->isPointerType())
999 return Context.IntTy;
1000 if (rType->isIntegerType()) {
1001 if (!rex->isNullPointerConstant(Context))
1002 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1003 lex->getSourceRange(), rex->getSourceRange());
1004 return Context.IntTy; // the previous diagnostic is a GCC extension.
1005 }
1006 } else if (rType->isPointerType()) {
1007 if (lType->isIntegerType()) {
1008 if (!lex->isNullPointerConstant(Context))
1009 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1010 lex->getSourceRange(), rex->getSourceRange());
1011 return Context.IntTy; // the previous diagnostic is a GCC extension.
1012 }
1013 }
1014 InvalidOperands(loc, lex, rex);
1015 return QualType();
1016}
1017
1018inline QualType Sema::CheckBitwiseOperands(
1019 Expr *&lex, Expr *&rex, SourceLocation loc)
1020{
1021 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1022 return CheckVectorOperands(loc, lex, rex);
1023
1024 UsualArithmeticConversions(lex, rex);
1025
1026 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1027 return lex->getType();
1028 InvalidOperands(loc, lex, rex);
1029 return QualType();
1030}
1031
1032inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1033 Expr *&lex, Expr *&rex, SourceLocation loc)
1034{
1035 UsualUnaryConversions(lex);
1036 UsualUnaryConversions(rex);
1037
1038 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1039 return Context.IntTy;
1040 InvalidOperands(loc, lex, rex);
1041 return QualType();
1042}
1043
1044inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
1045 Expr *lex, Expr *rex, SourceLocation loc, QualType compoundType)
1046{
1047 QualType lhsType = lex->getType();
1048 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1049 bool hadError = false;
1050 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1051
1052 switch (mlval) { // C99 6.5.16p2
1053 case Expr::MLV_Valid:
1054 break;
1055 case Expr::MLV_ConstQualified:
1056 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1057 hadError = true;
1058 break;
1059 case Expr::MLV_ArrayType:
1060 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1061 lhsType.getAsString(), lex->getSourceRange());
1062 return QualType();
1063 case Expr::MLV_NotObjectType:
1064 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1065 lhsType.getAsString(), lex->getSourceRange());
1066 return QualType();
1067 case Expr::MLV_InvalidExpression:
1068 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1069 lex->getSourceRange());
1070 return QualType();
1071 case Expr::MLV_IncompleteType:
1072 case Expr::MLV_IncompleteVoidType:
1073 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1074 lhsType.getAsString(), lex->getSourceRange());
1075 return QualType();
1076 }
1077 AssignmentCheckResult result;
1078
1079 if (compoundType.isNull())
1080 result = CheckSingleAssignmentConstraints(lhsType, rex);
1081 else
1082 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1083
1084 // decode the result (notice that extensions still return a type).
1085 switch (result) {
1086 case Compatible:
1087 break;
1088 case Incompatible:
1089 Diag(loc, diag::err_typecheck_assign_incompatible,
1090 lhsType.getAsString(), rhsType.getAsString(),
1091 lex->getSourceRange(), rex->getSourceRange());
1092 hadError = true;
1093 break;
1094 case PointerFromInt:
1095 // check for null pointer constant (C99 6.3.2.3p3)
1096 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1097 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1098 lhsType.getAsString(), rhsType.getAsString(),
1099 lex->getSourceRange(), rex->getSourceRange());
1100 }
1101 break;
1102 case IntFromPointer:
1103 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1104 lhsType.getAsString(), rhsType.getAsString(),
1105 lex->getSourceRange(), rex->getSourceRange());
1106 break;
1107 case IncompatiblePointer:
1108 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1109 lhsType.getAsString(), rhsType.getAsString(),
1110 lex->getSourceRange(), rex->getSourceRange());
1111 break;
1112 case CompatiblePointerDiscardsQualifiers:
1113 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1114 lhsType.getAsString(), rhsType.getAsString(),
1115 lex->getSourceRange(), rex->getSourceRange());
1116 break;
1117 }
1118 // C99 6.5.16p3: The type of an assignment expression is the type of the
1119 // left operand unless the left operand has qualified type, in which case
1120 // it is the unqualified version of the type of the left operand.
1121 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1122 // is converted to the type of the assignment expression (above).
1123 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1124 return hadError ? QualType() : lhsType.getUnqualifiedType();
1125}
1126
1127inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1128 Expr *&lex, Expr *&rex, SourceLocation loc) {
1129 UsualUnaryConversions(rex);
1130 return rex->getType();
1131}
1132
1133/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1134/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1135QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1136 QualType resType = op->getType();
1137 assert(!resType.isNull() && "no type for increment/decrement expression");
1138
1139 // C99 6.5.2.4p1
1140 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1141 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1142 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1143 resType.getAsString(), op->getSourceRange());
1144 return QualType();
1145 }
1146 } else if (!resType->isRealType()) {
1147 // FIXME: Allow Complex as a GCC extension.
1148 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1149 resType.getAsString(), op->getSourceRange());
1150 return QualType();
1151 }
1152 // At this point, we know we have a real or pointer type. Now make sure
1153 // the operand is a modifiable lvalue.
1154 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1155 if (mlval != Expr::MLV_Valid) {
1156 // FIXME: emit a more precise diagnostic...
1157 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1158 op->getSourceRange());
1159 return QualType();
1160 }
1161 return resType;
1162}
1163
1164/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1165/// This routine allows us to typecheck complex/recursive expressions
1166/// where the declaration is needed for type checking. Here are some
1167/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1168static Decl *getPrimaryDeclaration(Expr *e) {
1169 switch (e->getStmtClass()) {
1170 case Stmt::DeclRefExprClass:
1171 return cast<DeclRefExpr>(e)->getDecl();
1172 case Stmt::MemberExprClass:
1173 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1174 case Stmt::ArraySubscriptExprClass:
1175 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1176 case Stmt::CallExprClass:
1177 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1178 case Stmt::UnaryOperatorClass:
1179 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1180 case Stmt::ParenExprClass:
1181 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1182 default:
1183 return 0;
1184 }
1185}
1186
1187/// CheckAddressOfOperand - The operand of & must be either a function
1188/// designator or an lvalue designating an object. If it is an lvalue, the
1189/// object cannot be declared with storage class register or be a bit field.
1190/// Note: The usual conversions are *not* applied to the operand of the &
1191/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1192QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1193 Decl *dcl = getPrimaryDeclaration(op);
1194 Expr::isLvalueResult lval = op->isLvalue();
1195
1196 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1197 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1198 ;
1199 else { // FIXME: emit more specific diag...
1200 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1201 op->getSourceRange());
1202 return QualType();
1203 }
1204 } else if (dcl) {
1205 // We have an lvalue with a decl. Make sure the decl is not declared
1206 // with the register storage-class specifier.
1207 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1208 if (vd->getStorageClass() == VarDecl::Register) {
1209 Diag(OpLoc, diag::err_typecheck_address_of_register,
1210 op->getSourceRange());
1211 return QualType();
1212 }
1213 } else
1214 assert(0 && "Unknown/unexpected decl type");
1215
1216 // FIXME: add check for bitfields!
1217 }
1218 // If the operand has type "type", the result has type "pointer to type".
1219 return Context.getPointerType(op->getType());
1220}
1221
1222QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1223 UsualUnaryConversions(op);
1224 QualType qType = op->getType();
1225
1226 if (PointerType *PT = dyn_cast<PointerType>(qType.getCanonicalType())) {
1227 QualType ptype = PT->getPointeeType();
1228 // C99 6.5.3.2p4. "if it points to an object,...".
1229 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1230 // GCC compat: special case 'void *' (treat as warning).
1231 if (ptype->isVoidType()) {
1232 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1233 qType.getAsString(), op->getSourceRange());
1234 } else {
1235 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1236 ptype.getAsString(), op->getSourceRange());
1237 return QualType();
1238 }
1239 }
1240 return ptype;
1241 }
1242 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1243 qType.getAsString(), op->getSourceRange());
1244 return QualType();
1245}
1246
1247static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1248 tok::TokenKind Kind) {
1249 BinaryOperator::Opcode Opc;
1250 switch (Kind) {
1251 default: assert(0 && "Unknown binop!");
1252 case tok::star: Opc = BinaryOperator::Mul; break;
1253 case tok::slash: Opc = BinaryOperator::Div; break;
1254 case tok::percent: Opc = BinaryOperator::Rem; break;
1255 case tok::plus: Opc = BinaryOperator::Add; break;
1256 case tok::minus: Opc = BinaryOperator::Sub; break;
1257 case tok::lessless: Opc = BinaryOperator::Shl; break;
1258 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1259 case tok::lessequal: Opc = BinaryOperator::LE; break;
1260 case tok::less: Opc = BinaryOperator::LT; break;
1261 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1262 case tok::greater: Opc = BinaryOperator::GT; break;
1263 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1264 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1265 case tok::amp: Opc = BinaryOperator::And; break;
1266 case tok::caret: Opc = BinaryOperator::Xor; break;
1267 case tok::pipe: Opc = BinaryOperator::Or; break;
1268 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1269 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1270 case tok::equal: Opc = BinaryOperator::Assign; break;
1271 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1272 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1273 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1274 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1275 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1276 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1277 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1278 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1279 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1280 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1281 case tok::comma: Opc = BinaryOperator::Comma; break;
1282 }
1283 return Opc;
1284}
1285
1286static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1287 tok::TokenKind Kind) {
1288 UnaryOperator::Opcode Opc;
1289 switch (Kind) {
1290 default: assert(0 && "Unknown unary op!");
1291 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1292 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1293 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1294 case tok::star: Opc = UnaryOperator::Deref; break;
1295 case tok::plus: Opc = UnaryOperator::Plus; break;
1296 case tok::minus: Opc = UnaryOperator::Minus; break;
1297 case tok::tilde: Opc = UnaryOperator::Not; break;
1298 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1299 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1300 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1301 case tok::kw___real: Opc = UnaryOperator::Real; break;
1302 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1303 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1304 }
1305 return Opc;
1306}
1307
1308// Binary Operators. 'Tok' is the token for the operator.
1309Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1310 ExprTy *LHS, ExprTy *RHS) {
1311 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1312 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1313
1314 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1315 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1316
1317 QualType ResultTy; // Result type of the binary operator.
1318 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1319
1320 switch (Opc) {
1321 default:
1322 assert(0 && "Unknown binary expr!");
1323 case BinaryOperator::Assign:
1324 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1325 break;
1326 case BinaryOperator::Mul:
1327 case BinaryOperator::Div:
1328 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1329 break;
1330 case BinaryOperator::Rem:
1331 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1332 break;
1333 case BinaryOperator::Add:
1334 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1335 break;
1336 case BinaryOperator::Sub:
1337 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1338 break;
1339 case BinaryOperator::Shl:
1340 case BinaryOperator::Shr:
1341 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1342 break;
1343 case BinaryOperator::LE:
1344 case BinaryOperator::LT:
1345 case BinaryOperator::GE:
1346 case BinaryOperator::GT:
1347 ResultTy = CheckRelationalOperands(lhs, rhs, TokLoc);
1348 break;
1349 case BinaryOperator::EQ:
1350 case BinaryOperator::NE:
1351 ResultTy = CheckEqualityOperands(lhs, rhs, TokLoc);
1352 break;
1353 case BinaryOperator::And:
1354 case BinaryOperator::Xor:
1355 case BinaryOperator::Or:
1356 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1357 break;
1358 case BinaryOperator::LAnd:
1359 case BinaryOperator::LOr:
1360 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1361 break;
1362 case BinaryOperator::MulAssign:
1363 case BinaryOperator::DivAssign:
1364 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1365 if (!CompTy.isNull())
1366 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1367 break;
1368 case BinaryOperator::RemAssign:
1369 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1370 if (!CompTy.isNull())
1371 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1372 break;
1373 case BinaryOperator::AddAssign:
1374 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1375 if (!CompTy.isNull())
1376 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1377 break;
1378 case BinaryOperator::SubAssign:
1379 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1380 if (!CompTy.isNull())
1381 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1382 break;
1383 case BinaryOperator::ShlAssign:
1384 case BinaryOperator::ShrAssign:
1385 CompTy = CheckShiftOperands(lhs, rhs, TokLoc);
1386 if (!CompTy.isNull())
1387 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1388 break;
1389 case BinaryOperator::AndAssign:
1390 case BinaryOperator::XorAssign:
1391 case BinaryOperator::OrAssign:
1392 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1393 if (!CompTy.isNull())
1394 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1395 break;
1396 case BinaryOperator::Comma:
1397 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1398 break;
1399 }
1400 if (ResultTy.isNull())
1401 return true;
1402 if (CompTy.isNull())
1403 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1404 else
1405 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1406}
1407
1408// Unary Operators. 'Tok' is the token for the operator.
1409Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1410 ExprTy *input) {
1411 Expr *Input = (Expr*)input;
1412 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1413 QualType resultType;
1414 switch (Opc) {
1415 default:
1416 assert(0 && "Unimplemented unary expr!");
1417 case UnaryOperator::PreInc:
1418 case UnaryOperator::PreDec:
1419 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1420 break;
1421 case UnaryOperator::AddrOf:
1422 resultType = CheckAddressOfOperand(Input, OpLoc);
1423 break;
1424 case UnaryOperator::Deref:
1425 resultType = CheckIndirectionOperand(Input, OpLoc);
1426 break;
1427 case UnaryOperator::Plus:
1428 case UnaryOperator::Minus:
1429 UsualUnaryConversions(Input);
1430 resultType = Input->getType();
1431 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1432 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1433 resultType.getAsString());
1434 break;
1435 case UnaryOperator::Not: // bitwise complement
1436 UsualUnaryConversions(Input);
1437 resultType = Input->getType();
1438 if (!resultType->isIntegerType()) // C99 6.5.3.3p1
1439 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1440 resultType.getAsString());
1441 break;
1442 case UnaryOperator::LNot: // logical negation
1443 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1444 DefaultFunctionArrayConversion(Input);
1445 resultType = Input->getType();
1446 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1447 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1448 resultType.getAsString());
1449 // LNot always has type int. C99 6.5.3.3p5.
1450 resultType = Context.IntTy;
1451 break;
1452 case UnaryOperator::SizeOf:
1453 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1454 break;
1455 case UnaryOperator::AlignOf:
1456 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1457 break;
1458 case UnaryOperator::Extension:
1459 // FIXME: does __extension__ cause any promotions? I would think not.
1460 resultType = Input->getType();
1461 break;
1462 }
1463 if (resultType.isNull())
1464 return true;
1465 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1466}
1467
1468/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1469Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1470 SourceLocation LabLoc,
1471 IdentifierInfo *LabelII) {
1472 // Look up the record for this label identifier.
1473 LabelStmt *&LabelDecl = LabelMap[LabelII];
1474
1475 // If we haven't seen this label yet, create a forward reference.
1476 if (LabelDecl == 0)
1477 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1478
1479 // Create the AST node. The address of a label always has type 'void*'.
1480 return new AddrLabel(OpLoc, LabLoc, LabelDecl,
1481 Context.getPointerType(Context.VoidTy));
1482}
1483
1484Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1485 SourceLocation RPLoc) { // "({..})"
1486 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1487 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1488 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1489
1490 // FIXME: there are a variety of strange constraints to enforce here, for
1491 // example, it is not possible to goto into a stmt expression apparently.
1492 // More semantic analysis is needed.
1493
1494 // FIXME: the last statement in the compount stmt has its value used. We
1495 // should not warn about it being unused.
1496
1497 // If there are sub stmts in the compound stmt, take the type of the last one
1498 // as the type of the stmtexpr.
1499 QualType Ty = Context.VoidTy;
1500
1501 if (!Compound->body_empty())
1502 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1503 Ty = LastExpr->getType();
1504
1505 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1506}