blob: cd19872a1a6ed7fc0972af6bdc164d4e2bfebabd [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
588 // FIXME: C99 6.5.15p6: If both operands are pointers to compatible types
589 // *or* to differently qualified versions of compatible types, the result
590 // type is a pointer to an appropriately qualified version of the
591 // *composite* type.
592 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
593 rhptee.getUnqualifiedType())) {
594 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
595 lexT.getAsString(), rexT.getAsString(),
596 lex->getSourceRange(), rex->getSourceRange());
597 return lexT; // FIXME: this is an _ext - is this return o.k?
598 }
599 }
600 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
601 return lexT;
602
603 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
604 lexT.getAsString(), rexT.getAsString(),
605 lex->getSourceRange(), rex->getSourceRange());
606 return QualType();
607}
608
609/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
610/// in the case of a the GNU conditional expr extension.
611Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
612 SourceLocation ColonLoc,
613 ExprTy *Cond, ExprTy *LHS,
614 ExprTy *RHS) {
615 Expr *CondExpr = (Expr *) Cond;
616 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
617 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
618 RHSExpr, QuestionLoc);
619 if (result.isNull())
620 return true;
621 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
622}
623
624// promoteExprToType - a helper function to ensure we create exactly one
625// ImplicitCastExpr. As a convenience (to the caller), we return the type.
626static void promoteExprToType(Expr *&expr, QualType type) {
627 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
628 impCast->setType(type);
629 else
630 expr = new ImplicitCastExpr(type, expr);
631 return;
632}
633
634/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
635void Sema::DefaultFunctionArrayConversion(Expr *&e) {
636 QualType t = e->getType();
637 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
638
639 if (const ReferenceType *ref = t->isReferenceType()) {
640 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
641 t = e->getType();
642 }
643 if (t->isFunctionType())
644 promoteExprToType(e, Context.getPointerType(t));
645 else if (const ArrayType *ary = t->isArrayType())
646 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
647}
648
649/// UsualUnaryConversion - Performs various conversions that are common to most
650/// operators (C99 6.3). The conversions of array and function types are
651/// sometimes surpressed. For example, the array->pointer conversion doesn't
652/// apply if the array is an argument to the sizeof or address (&) operators.
653/// In these instances, this routine should *not* be called.
654void Sema::UsualUnaryConversions(Expr *&expr) {
655 QualType t = expr->getType();
656 assert(!t.isNull() && "UsualUnaryConversions - missing type");
657
658 if (const ReferenceType *ref = t->isReferenceType()) {
659 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
660 t = expr->getType();
661 }
662 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
663 promoteExprToType(expr, Context.IntTy);
664 else
665 DefaultFunctionArrayConversion(expr);
666}
667
668/// UsualArithmeticConversions - Performs various conversions that are common to
669/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
670/// routine returns the first non-arithmetic type found. The client is
671/// responsible for emitting appropriate error diagnostics.
672void Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr) {
673 UsualUnaryConversions(lhsExpr);
674 UsualUnaryConversions(rhsExpr);
675
676 QualType lhs = lhsExpr->getType();
677 QualType rhs = rhsExpr->getType();
678
679 // If both types are identical, no conversion is needed.
680 if (lhs == rhs)
681 return;
682
683 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
684 // The caller can deal with this (e.g. pointer + int).
685 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
686 return;
687
688 // At this point, we have two different arithmetic types.
689
690 // Handle complex types first (C99 6.3.1.8p1).
691 if (lhs->isComplexType() || rhs->isComplexType()) {
692 // if we have an integer operand, the result is the complex type.
693 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
694 promoteExprToType(rhsExpr, lhs);
695 return;
696 }
697 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
698 promoteExprToType(lhsExpr, rhs);
699 return;
700 }
701 // Two complex types. Convert the smaller operand to the bigger result.
702 if (Context.maxComplexType(lhs, rhs) == lhs) { // convert the rhs
703 promoteExprToType(rhsExpr, lhs);
704 return;
705 }
706 promoteExprToType(lhsExpr, rhs); // convert the lhs
707 return;
708 }
709 // Now handle "real" floating types (i.e. float, double, long double).
710 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
711 // if we have an integer operand, the result is the real floating type.
712 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
713 promoteExprToType(rhsExpr, lhs);
714 return;
715 }
716 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
717 promoteExprToType(lhsExpr, rhs);
718 return;
719 }
720 // We have two real floating types, float/complex combos were handled above.
721 // Convert the smaller operand to the bigger result.
722 if (Context.maxFloatingType(lhs, rhs) == lhs) { // convert the rhs
723 promoteExprToType(rhsExpr, lhs);
724 return;
725 }
726 promoteExprToType(lhsExpr, rhs); // convert the lhs
727 return;
728 }
729 // Finally, we have two differing integer types.
730 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
731 promoteExprToType(rhsExpr, lhs);
732 return;
733 }
734 promoteExprToType(lhsExpr, rhs); // convert the lhs
735 return;
736}
737
738// CheckPointerTypesForAssignment - This is a very tricky routine (despite
739// being closely modeled after the C99 spec:-). The odd characteristic of this
740// routine is it effectively iqnores the qualifiers on the top level pointee.
741// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
742// FIXME: add a couple examples in this comment.
743Sema::AssignmentCheckResult
744Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
745 QualType lhptee, rhptee;
746
747 // get the "pointed to" type (ignoring qualifiers at the top level)
748 lhptee = cast<PointerType>(lhsType.getCanonicalType())->getPointeeType();
749 rhptee = cast<PointerType>(rhsType.getCanonicalType())->getPointeeType();
750
751 // make sure we operate on the canonical type
752 lhptee = lhptee.getCanonicalType();
753 rhptee = rhptee.getCanonicalType();
754
755 AssignmentCheckResult r = Compatible;
756
757 // C99 6.5.16.1p1: This following citation is common to constraints
758 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
759 // qualifiers of the type *pointed to* by the right;
760 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
761 rhptee.getQualifiers())
762 r = CompatiblePointerDiscardsQualifiers;
763
764 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
765 // incomplete type and the other is a pointer to a qualified or unqualified
766 // version of void...
767 if (lhptee.getUnqualifiedType()->isVoidType() &&
768 (rhptee->isObjectType() || rhptee->isIncompleteType()))
769 ;
770 else if (rhptee.getUnqualifiedType()->isVoidType() &&
771 (lhptee->isObjectType() || lhptee->isIncompleteType()))
772 ;
773 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
774 // unqualified versions of compatible types, ...
775 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
776 rhptee.getUnqualifiedType()))
777 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
778 return r;
779}
780
781/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
782/// has code to accommodate several GCC extensions when type checking
783/// pointers. Here are some objectionable examples that GCC considers warnings:
784///
785/// int a, *pint;
786/// short *pshort;
787/// struct foo *pfoo;
788///
789/// pint = pshort; // warning: assignment from incompatible pointer type
790/// a = pint; // warning: assignment makes integer from pointer without a cast
791/// pint = a; // warning: assignment makes pointer from integer without a cast
792/// pint = pfoo; // warning: assignment from incompatible pointer type
793///
794/// As a result, the code for dealing with pointers is more complex than the
795/// C99 spec dictates.
796/// Note: the warning above turn into errors when -pedantic-errors is enabled.
797///
798Sema::AssignmentCheckResult
799Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
800 if (lhsType == rhsType) // common case, fast path...
801 return Compatible;
802
803 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
804 if (lhsType->isVectorType() || rhsType->isVectorType()) {
805 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
806 return Incompatible;
807 }
808 return Compatible;
809 } else if (lhsType->isPointerType()) {
810 if (rhsType->isIntegerType())
811 return PointerFromInt;
812
813 if (rhsType->isPointerType())
814 return CheckPointerTypesForAssignment(lhsType, rhsType);
815 } else if (rhsType->isPointerType()) {
816 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
817 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
818 return IntFromPointer;
819
820 if (lhsType->isPointerType())
821 return CheckPointerTypesForAssignment(lhsType, rhsType);
822 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
823 if (Type::tagTypesAreCompatible(lhsType, rhsType))
824 return Compatible;
825 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
826 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
827 return Compatible;
828 }
829 return Incompatible;
830}
831
832Sema::AssignmentCheckResult
833Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
834 // This check seems unnatural, however it is necessary to insure the proper
835 // conversion of functions/arrays. If the conversion were done for all
836 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
837 // expressions that surpress this implicit conversion (&, sizeof).
838 DefaultFunctionArrayConversion(rExpr);
839
840 return CheckAssignmentConstraints(lhsType, rExpr->getType());
841}
842
843Sema::AssignmentCheckResult
844Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
845 return CheckAssignmentConstraints(lhsType, rhsType);
846}
847
848inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
849 Diag(loc, diag::err_typecheck_invalid_operands,
850 lex->getType().getAsString(), rex->getType().getAsString(),
851 lex->getSourceRange(), rex->getSourceRange());
852}
853
854inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
855 Expr *&rex) {
856 QualType lhsType = lex->getType(), rhsType = rex->getType();
857
858 // make sure the vector types are identical.
859 if (lhsType == rhsType)
860 return lhsType;
861 // You cannot convert between vector values of different size.
862 Diag(loc, diag::err_typecheck_vector_not_convertable,
863 lex->getType().getAsString(), rex->getType().getAsString(),
864 lex->getSourceRange(), rex->getSourceRange());
865 return QualType();
866}
867
868inline QualType Sema::CheckMultiplyDivideOperands(
869 Expr *&lex, Expr *&rex, SourceLocation loc)
870{
871 QualType lhsType = lex->getType(), rhsType = rex->getType();
872
873 if (lhsType->isVectorType() || rhsType->isVectorType())
874 return CheckVectorOperands(loc, lex, rex);
875
876 UsualArithmeticConversions(lex, rex);
877
878 // handle the common case first (both operands are arithmetic).
879 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
880 return lex->getType();
881 InvalidOperands(loc, lex, rex);
882 return QualType();
883}
884
885inline QualType Sema::CheckRemainderOperands(
886 Expr *&lex, Expr *&rex, SourceLocation loc)
887{
888 QualType lhsType = lex->getType(), rhsType = rex->getType();
889
890 UsualArithmeticConversions(lex, rex);
891
892 // handle the common case first (both operands are arithmetic).
893 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
894 return lex->getType();
895 InvalidOperands(loc, lex, rex);
896 return QualType();
897}
898
899inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
900 Expr *&lex, Expr *&rex, SourceLocation loc)
901{
902 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
903 return CheckVectorOperands(loc, lex, rex);
904
905 UsualArithmeticConversions(lex, rex);
906
907 // handle the common case first (both operands are arithmetic).
908 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
909 return lex->getType();
910
911 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
912 return lex->getType();
913 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
914 return rex->getType();
915 InvalidOperands(loc, lex, rex);
916 return QualType();
917}
918
919inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
920 Expr *&lex, Expr *&rex, SourceLocation loc)
921{
922 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
923 return CheckVectorOperands(loc, lex, rex);
924
925 UsualArithmeticConversions(lex, rex);
926
927 // handle the common case first (both operands are arithmetic).
928 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
929 return lex->getType();
930
931 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
932 return lex->getType();
933 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
934 return Context.getPointerDiffType();
935 InvalidOperands(loc, lex, rex);
936 return QualType();
937}
938
939inline QualType Sema::CheckShiftOperands( // C99 6.5.7
940 Expr *&lex, Expr *&rex, SourceLocation loc)
941{
942 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
943 // for int << longlong -> the result type should be int, not long long.
944 UsualArithmeticConversions(lex, rex);
945
946 // handle the common case first (both operands are arithmetic).
947 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
948 return lex->getType();
949 InvalidOperands(loc, lex, rex);
950 return QualType();
951}
952
953inline QualType Sema::CheckRelationalOperands( // C99 6.5.8
954 Expr *&lex, Expr *&rex, SourceLocation loc)
955{
956 UsualUnaryConversions(lex);
957 UsualUnaryConversions(rex);
958 QualType lType = lex->getType();
959 QualType rType = rex->getType();
960
961 if (lType->isRealType() && rType->isRealType())
962 return Context.IntTy;
963
964 if (lType->isPointerType()) {
965 if (rType->isPointerType())
966 return Context.IntTy;
967 if (rType->isIntegerType()) {
968 if (!rex->isNullPointerConstant(Context))
969 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
970 lex->getSourceRange(), rex->getSourceRange());
971 return Context.IntTy; // the previous diagnostic is a GCC extension.
972 }
973 } else if (rType->isPointerType()) {
974 if (lType->isIntegerType()) {
975 if (!lex->isNullPointerConstant(Context))
976 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
977 lex->getSourceRange(), rex->getSourceRange());
978 return Context.IntTy; // the previous diagnostic is a GCC extension.
979 }
980 }
981 InvalidOperands(loc, lex, rex);
982 return QualType();
983}
984
985inline QualType Sema::CheckEqualityOperands( // C99 6.5.9
986 Expr *&lex, Expr *&rex, SourceLocation loc)
987{
988 UsualUnaryConversions(lex);
989 UsualUnaryConversions(rex);
990 QualType lType = lex->getType();
991 QualType rType = rex->getType();
992
993 if (lType->isArithmeticType() && rType->isArithmeticType())
994 return Context.IntTy;
995
996 if (lType->isPointerType()) {
997 if (rType->isPointerType())
998 return Context.IntTy;
999 if (rType->isIntegerType()) {
1000 if (!rex->isNullPointerConstant(Context))
1001 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1002 lex->getSourceRange(), rex->getSourceRange());
1003 return Context.IntTy; // the previous diagnostic is a GCC extension.
1004 }
1005 } else if (rType->isPointerType()) {
1006 if (lType->isIntegerType()) {
1007 if (!lex->isNullPointerConstant(Context))
1008 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1009 lex->getSourceRange(), rex->getSourceRange());
1010 return Context.IntTy; // the previous diagnostic is a GCC extension.
1011 }
1012 }
1013 InvalidOperands(loc, lex, rex);
1014 return QualType();
1015}
1016
1017inline QualType Sema::CheckBitwiseOperands(
1018 Expr *&lex, Expr *&rex, SourceLocation loc)
1019{
1020 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1021 return CheckVectorOperands(loc, lex, rex);
1022
1023 UsualArithmeticConversions(lex, rex);
1024
1025 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1026 return lex->getType();
1027 InvalidOperands(loc, lex, rex);
1028 return QualType();
1029}
1030
1031inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1032 Expr *&lex, Expr *&rex, SourceLocation loc)
1033{
1034 UsualUnaryConversions(lex);
1035 UsualUnaryConversions(rex);
1036
1037 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1038 return Context.IntTy;
1039 InvalidOperands(loc, lex, rex);
1040 return QualType();
1041}
1042
1043inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
1044 Expr *lex, Expr *rex, SourceLocation loc, QualType compoundType)
1045{
1046 QualType lhsType = lex->getType();
1047 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1048 bool hadError = false;
1049 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1050
1051 switch (mlval) { // C99 6.5.16p2
1052 case Expr::MLV_Valid:
1053 break;
1054 case Expr::MLV_ConstQualified:
1055 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1056 hadError = true;
1057 break;
1058 case Expr::MLV_ArrayType:
1059 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1060 lhsType.getAsString(), lex->getSourceRange());
1061 return QualType();
1062 case Expr::MLV_NotObjectType:
1063 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1064 lhsType.getAsString(), lex->getSourceRange());
1065 return QualType();
1066 case Expr::MLV_InvalidExpression:
1067 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1068 lex->getSourceRange());
1069 return QualType();
1070 case Expr::MLV_IncompleteType:
1071 case Expr::MLV_IncompleteVoidType:
1072 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1073 lhsType.getAsString(), lex->getSourceRange());
1074 return QualType();
1075 }
1076 AssignmentCheckResult result;
1077
1078 if (compoundType.isNull())
1079 result = CheckSingleAssignmentConstraints(lhsType, rex);
1080 else
1081 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1082
1083 // decode the result (notice that extensions still return a type).
1084 switch (result) {
1085 case Compatible:
1086 break;
1087 case Incompatible:
1088 Diag(loc, diag::err_typecheck_assign_incompatible,
1089 lhsType.getAsString(), rhsType.getAsString(),
1090 lex->getSourceRange(), rex->getSourceRange());
1091 hadError = true;
1092 break;
1093 case PointerFromInt:
1094 // check for null pointer constant (C99 6.3.2.3p3)
1095 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1096 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1097 lhsType.getAsString(), rhsType.getAsString(),
1098 lex->getSourceRange(), rex->getSourceRange());
1099 }
1100 break;
1101 case IntFromPointer:
1102 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1103 lhsType.getAsString(), rhsType.getAsString(),
1104 lex->getSourceRange(), rex->getSourceRange());
1105 break;
1106 case IncompatiblePointer:
1107 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1108 lhsType.getAsString(), rhsType.getAsString(),
1109 lex->getSourceRange(), rex->getSourceRange());
1110 break;
1111 case CompatiblePointerDiscardsQualifiers:
1112 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1113 lhsType.getAsString(), rhsType.getAsString(),
1114 lex->getSourceRange(), rex->getSourceRange());
1115 break;
1116 }
1117 // C99 6.5.16p3: The type of an assignment expression is the type of the
1118 // left operand unless the left operand has qualified type, in which case
1119 // it is the unqualified version of the type of the left operand.
1120 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1121 // is converted to the type of the assignment expression (above).
1122 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1123 return hadError ? QualType() : lhsType.getUnqualifiedType();
1124}
1125
1126inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1127 Expr *&lex, Expr *&rex, SourceLocation loc) {
1128 UsualUnaryConversions(rex);
1129 return rex->getType();
1130}
1131
1132/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1133/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1134QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1135 QualType resType = op->getType();
1136 assert(!resType.isNull() && "no type for increment/decrement expression");
1137
1138 // C99 6.5.2.4p1
1139 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1140 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1141 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1142 resType.getAsString(), op->getSourceRange());
1143 return QualType();
1144 }
1145 } else if (!resType->isRealType()) {
1146 // FIXME: Allow Complex as a GCC extension.
1147 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1148 resType.getAsString(), op->getSourceRange());
1149 return QualType();
1150 }
1151 // At this point, we know we have a real or pointer type. Now make sure
1152 // the operand is a modifiable lvalue.
1153 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1154 if (mlval != Expr::MLV_Valid) {
1155 // FIXME: emit a more precise diagnostic...
1156 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1157 op->getSourceRange());
1158 return QualType();
1159 }
1160 return resType;
1161}
1162
1163/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1164/// This routine allows us to typecheck complex/recursive expressions
1165/// where the declaration is needed for type checking. Here are some
1166/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1167static Decl *getPrimaryDeclaration(Expr *e) {
1168 switch (e->getStmtClass()) {
1169 case Stmt::DeclRefExprClass:
1170 return cast<DeclRefExpr>(e)->getDecl();
1171 case Stmt::MemberExprClass:
1172 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1173 case Stmt::ArraySubscriptExprClass:
1174 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1175 case Stmt::CallExprClass:
1176 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1177 case Stmt::UnaryOperatorClass:
1178 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1179 case Stmt::ParenExprClass:
1180 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1181 default:
1182 return 0;
1183 }
1184}
1185
1186/// CheckAddressOfOperand - The operand of & must be either a function
1187/// designator or an lvalue designating an object. If it is an lvalue, the
1188/// object cannot be declared with storage class register or be a bit field.
1189/// Note: The usual conversions are *not* applied to the operand of the &
1190/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1191QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1192 Decl *dcl = getPrimaryDeclaration(op);
1193 Expr::isLvalueResult lval = op->isLvalue();
1194
1195 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1196 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1197 ;
1198 else { // FIXME: emit more specific diag...
1199 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1200 op->getSourceRange());
1201 return QualType();
1202 }
1203 } else if (dcl) {
1204 // We have an lvalue with a decl. Make sure the decl is not declared
1205 // with the register storage-class specifier.
1206 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1207 if (vd->getStorageClass() == VarDecl::Register) {
1208 Diag(OpLoc, diag::err_typecheck_address_of_register,
1209 op->getSourceRange());
1210 return QualType();
1211 }
1212 } else
1213 assert(0 && "Unknown/unexpected decl type");
1214
1215 // FIXME: add check for bitfields!
1216 }
1217 // If the operand has type "type", the result has type "pointer to type".
1218 return Context.getPointerType(op->getType());
1219}
1220
1221QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1222 UsualUnaryConversions(op);
1223 QualType qType = op->getType();
1224
1225 if (PointerType *PT = dyn_cast<PointerType>(qType.getCanonicalType())) {
1226 QualType ptype = PT->getPointeeType();
1227 // C99 6.5.3.2p4. "if it points to an object,...".
1228 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1229 // GCC compat: special case 'void *' (treat as warning).
1230 if (ptype->isVoidType()) {
1231 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1232 qType.getAsString(), op->getSourceRange());
1233 } else {
1234 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1235 ptype.getAsString(), op->getSourceRange());
1236 return QualType();
1237 }
1238 }
1239 return ptype;
1240 }
1241 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1242 qType.getAsString(), op->getSourceRange());
1243 return QualType();
1244}
1245
1246static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1247 tok::TokenKind Kind) {
1248 BinaryOperator::Opcode Opc;
1249 switch (Kind) {
1250 default: assert(0 && "Unknown binop!");
1251 case tok::star: Opc = BinaryOperator::Mul; break;
1252 case tok::slash: Opc = BinaryOperator::Div; break;
1253 case tok::percent: Opc = BinaryOperator::Rem; break;
1254 case tok::plus: Opc = BinaryOperator::Add; break;
1255 case tok::minus: Opc = BinaryOperator::Sub; break;
1256 case tok::lessless: Opc = BinaryOperator::Shl; break;
1257 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1258 case tok::lessequal: Opc = BinaryOperator::LE; break;
1259 case tok::less: Opc = BinaryOperator::LT; break;
1260 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1261 case tok::greater: Opc = BinaryOperator::GT; break;
1262 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1263 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1264 case tok::amp: Opc = BinaryOperator::And; break;
1265 case tok::caret: Opc = BinaryOperator::Xor; break;
1266 case tok::pipe: Opc = BinaryOperator::Or; break;
1267 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1268 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1269 case tok::equal: Opc = BinaryOperator::Assign; break;
1270 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1271 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1272 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1273 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1274 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1275 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1276 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1277 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1278 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1279 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1280 case tok::comma: Opc = BinaryOperator::Comma; break;
1281 }
1282 return Opc;
1283}
1284
1285static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1286 tok::TokenKind Kind) {
1287 UnaryOperator::Opcode Opc;
1288 switch (Kind) {
1289 default: assert(0 && "Unknown unary op!");
1290 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1291 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1292 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1293 case tok::star: Opc = UnaryOperator::Deref; break;
1294 case tok::plus: Opc = UnaryOperator::Plus; break;
1295 case tok::minus: Opc = UnaryOperator::Minus; break;
1296 case tok::tilde: Opc = UnaryOperator::Not; break;
1297 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1298 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1299 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1300 case tok::kw___real: Opc = UnaryOperator::Real; break;
1301 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1302 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1303 }
1304 return Opc;
1305}
1306
1307// Binary Operators. 'Tok' is the token for the operator.
1308Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1309 ExprTy *LHS, ExprTy *RHS) {
1310 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1311 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1312
1313 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1314 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1315
1316 QualType ResultTy; // Result type of the binary operator.
1317 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1318
1319 switch (Opc) {
1320 default:
1321 assert(0 && "Unknown binary expr!");
1322 case BinaryOperator::Assign:
1323 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1324 break;
1325 case BinaryOperator::Mul:
1326 case BinaryOperator::Div:
1327 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1328 break;
1329 case BinaryOperator::Rem:
1330 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1331 break;
1332 case BinaryOperator::Add:
1333 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1334 break;
1335 case BinaryOperator::Sub:
1336 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1337 break;
1338 case BinaryOperator::Shl:
1339 case BinaryOperator::Shr:
1340 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1341 break;
1342 case BinaryOperator::LE:
1343 case BinaryOperator::LT:
1344 case BinaryOperator::GE:
1345 case BinaryOperator::GT:
1346 ResultTy = CheckRelationalOperands(lhs, rhs, TokLoc);
1347 break;
1348 case BinaryOperator::EQ:
1349 case BinaryOperator::NE:
1350 ResultTy = CheckEqualityOperands(lhs, rhs, TokLoc);
1351 break;
1352 case BinaryOperator::And:
1353 case BinaryOperator::Xor:
1354 case BinaryOperator::Or:
1355 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1356 break;
1357 case BinaryOperator::LAnd:
1358 case BinaryOperator::LOr:
1359 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1360 break;
1361 case BinaryOperator::MulAssign:
1362 case BinaryOperator::DivAssign:
1363 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1364 if (!CompTy.isNull())
1365 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1366 break;
1367 case BinaryOperator::RemAssign:
1368 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1369 if (!CompTy.isNull())
1370 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1371 break;
1372 case BinaryOperator::AddAssign:
1373 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1374 if (!CompTy.isNull())
1375 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1376 break;
1377 case BinaryOperator::SubAssign:
1378 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1379 if (!CompTy.isNull())
1380 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1381 break;
1382 case BinaryOperator::ShlAssign:
1383 case BinaryOperator::ShrAssign:
1384 CompTy = CheckShiftOperands(lhs, rhs, TokLoc);
1385 if (!CompTy.isNull())
1386 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1387 break;
1388 case BinaryOperator::AndAssign:
1389 case BinaryOperator::XorAssign:
1390 case BinaryOperator::OrAssign:
1391 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1392 if (!CompTy.isNull())
1393 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1394 break;
1395 case BinaryOperator::Comma:
1396 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1397 break;
1398 }
1399 if (ResultTy.isNull())
1400 return true;
1401 if (CompTy.isNull())
1402 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1403 else
1404 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1405}
1406
1407// Unary Operators. 'Tok' is the token for the operator.
1408Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1409 ExprTy *input) {
1410 Expr *Input = (Expr*)input;
1411 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1412 QualType resultType;
1413 switch (Opc) {
1414 default:
1415 assert(0 && "Unimplemented unary expr!");
1416 case UnaryOperator::PreInc:
1417 case UnaryOperator::PreDec:
1418 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1419 break;
1420 case UnaryOperator::AddrOf:
1421 resultType = CheckAddressOfOperand(Input, OpLoc);
1422 break;
1423 case UnaryOperator::Deref:
1424 resultType = CheckIndirectionOperand(Input, OpLoc);
1425 break;
1426 case UnaryOperator::Plus:
1427 case UnaryOperator::Minus:
1428 UsualUnaryConversions(Input);
1429 resultType = Input->getType();
1430 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1431 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1432 resultType.getAsString());
1433 break;
1434 case UnaryOperator::Not: // bitwise complement
1435 UsualUnaryConversions(Input);
1436 resultType = Input->getType();
1437 if (!resultType->isIntegerType()) // C99 6.5.3.3p1
1438 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1439 resultType.getAsString());
1440 break;
1441 case UnaryOperator::LNot: // logical negation
1442 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1443 DefaultFunctionArrayConversion(Input);
1444 resultType = Input->getType();
1445 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1446 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1447 resultType.getAsString());
1448 // LNot always has type int. C99 6.5.3.3p5.
1449 resultType = Context.IntTy;
1450 break;
1451 case UnaryOperator::SizeOf:
1452 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1453 break;
1454 case UnaryOperator::AlignOf:
1455 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1456 break;
1457 case UnaryOperator::Extension:
1458 // FIXME: does __extension__ cause any promotions? I would think not.
1459 resultType = Input->getType();
1460 break;
1461 }
1462 if (resultType.isNull())
1463 return true;
1464 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1465}
1466
1467/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1468Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1469 SourceLocation LabLoc,
1470 IdentifierInfo *LabelII) {
1471 // Look up the record for this label identifier.
1472 LabelStmt *&LabelDecl = LabelMap[LabelII];
1473
1474 // If we haven't seen this label yet, create a forward reference.
1475 if (LabelDecl == 0)
1476 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1477
1478 // Create the AST node. The address of a label always has type 'void*'.
1479 return new AddrLabel(OpLoc, LabLoc, LabelDecl,
1480 Context.getPointerType(Context.VoidTy));
1481}
1482
1483Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1484 SourceLocation RPLoc) { // "({..})"
1485 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1486 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1487 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1488
1489 // FIXME: there are a variety of strange constraints to enforce here, for
1490 // example, it is not possible to goto into a stmt expression apparently.
1491 // More semantic analysis is needed.
1492
1493 // FIXME: the last statement in the compount stmt has its value used. We
1494 // should not warn about it being unused.
1495
1496 // If there are sub stmts in the compound stmt, take the type of the last one
1497 // as the type of the stmtexpr.
1498 QualType Ty = Context.VoidTy;
1499
1500 if (!Compound->body_empty())
1501 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1502 Ty = LastExpr->getType();
1503
1504 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1505}