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