blob: 79823cc564ecdceedb0bcddc7ea0ffde57500c43 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +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"
Chris Lattnercb6a3822006-11-10 06:20:45 +000015#include "clang/AST/ASTContext.h"
Chris Lattner17ed4872006-11-20 04:58:19 +000016#include "clang/AST/Decl.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000017#include "clang/AST/Expr.h"
18#include "clang/Lex/Preprocessor.h"
Steve Naroff09ef4742007-03-09 23:16:33 +000019#include "clang/Lex/LiteralSupport.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerac18be92006-11-20 06:49:47 +000022#include "clang/Basic/LangOptions.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000023#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/SmallString.h"
Steve Naroff17f76e02007-05-03 21:03:48 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000026using namespace llvm;
27using namespace clang;
28
Steve Naroffe4718892007-04-27 18:30:00 +000029// Sema.h avoids including Expr.h. As a result, all the Check* functions take
30// an unsigned which is really an enum. These typedefs provide a short hand
31// notiation for casting (to keep the lines within 80 columns:-)
32typedef BinaryOperator::Opcode BOP;
33typedef UnaryOperator::Opcode UOP;
34
Steve Naroffdf7855b2007-02-21 23:46:25 +000035/// ParseStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +000036/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
37/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
38/// multiple tokens. However, the common case is that StringToks points to one
39/// string.
40///
41Action::ExprResult
Steve Naroffdf7855b2007-02-21 23:46:25 +000042Sema::ParseStringLiteral(const LexerToken *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +000043 assert(NumStringToks && "Must have at least one string!");
44
Steve Naroff4f88b312007-03-13 22:37:02 +000045 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
46 if (Literal.hadError)
47 return ExprResult(true);
Chris Lattner5b183d82006-11-10 05:03:26 +000048
Chris Lattner5b183d82006-11-10 05:03:26 +000049 SmallVector<SourceLocation, 4> StringTokLocs;
50 for (unsigned i = 0; i != NumStringToks; ++i)
51 StringTokLocs.push_back(StringToks[i].getLocation());
Steve Narofff1e53692007-03-23 22:27:02 +000052
53 // FIXME: handle wchar_t
Steve Naroffe5aa9be2007-04-05 22:36:20 +000054 QualType t = Context.getPointerType(Context.CharTy);
Steve Narofff1e53692007-03-23 22:27:02 +000055
Chris Lattner5b183d82006-11-10 05:03:26 +000056 // FIXME: use factory.
Chris Lattner5b183d82006-11-10 05:03:26 +000057 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Steve Naroff4f88b312007-03-13 22:37:02 +000058 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Steve Narofff1e53692007-03-23 22:27:02 +000059 Literal.AnyWide, t);
Chris Lattner5b183d82006-11-10 05:03:26 +000060}
61
Chris Lattnere168f762006-11-10 05:29:30 +000062
Chris Lattnerac18be92006-11-20 06:49:47 +000063/// ParseIdentifierExpr - The parser read an identifier in expression context,
64/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
65/// identifier is used in an function call context.
66Sema::ExprResult Sema::ParseIdentifierExpr(Scope *S, SourceLocation Loc,
67 IdentifierInfo &II,
68 bool HasTrailingLParen) {
Chris Lattner17ed4872006-11-20 04:58:19 +000069 // Could be enum-constant or decl.
Chris Lattner9561a0b2007-01-28 08:20:04 +000070 Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner17ed4872006-11-20 04:58:19 +000071 if (D == 0) {
Bill Wendling4073ed52007-02-13 01:51:42 +000072 // Otherwise, this could be an implicitly declared function reference (legal
Chris Lattner9561a0b2007-01-28 08:20:04 +000073 // in C90, extension in C99).
Chris Lattnerac18be92006-11-20 06:49:47 +000074 if (HasTrailingLParen &&
75 // Not in C++.
Steve Narofff1e53692007-03-23 22:27:02 +000076 !getLangOptions().CPlusPlus)
Chris Lattnerac18be92006-11-20 06:49:47 +000077 D = ImplicitlyDefineFunction(Loc, II, S);
Steve Naroff92e30f82007-04-02 22:35:25 +000078 else {
Chris Lattnerac18be92006-11-20 06:49:47 +000079 // If this name wasn't predeclared and if this is not a function call,
80 // diagnose the problem.
Steve Narofff1e53692007-03-23 22:27:02 +000081 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
Steve Naroff92e30f82007-04-02 22:35:25 +000082 }
Chris Lattner17ed4872006-11-20 04:58:19 +000083 }
84
Steve Naroff46ba1eb2007-04-03 23:13:13 +000085 if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
86 return new DeclRefExpr(VD, VD->getType());
87 if (isa<TypedefDecl>(D))
Steve Narofff1e53692007-03-23 22:27:02 +000088 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
89
90 assert(0 && "Invalid decl");
Chris Lattner17ed4872006-11-20 04:58:19 +000091}
Chris Lattnere168f762006-11-10 05:29:30 +000092
Chris Lattner17ed4872006-11-20 04:58:19 +000093Sema::ExprResult Sema::ParseSimplePrimaryExpr(SourceLocation Loc,
94 tok::TokenKind Kind) {
Chris Lattnere168f762006-11-10 05:29:30 +000095 switch (Kind) {
96 default:
97 assert(0 && "Unknown simple primary expr!");
Steve Naroffe4718892007-04-27 18:30:00 +000098 // TODO: MOVE this to be some other callback.
Chris Lattnere168f762006-11-10 05:29:30 +000099 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
100 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
101 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Chris Lattner17ed4872006-11-20 04:58:19 +0000102 return 0;
Chris Lattnere168f762006-11-10 05:29:30 +0000103 }
104}
105
Steve Naroffae4143e2007-04-26 20:39:23 +0000106Sema::ExprResult Sema::ParseCharacterConstant(const LexerToken &Tok) {
107 SmallString<16> CharBuffer;
108 CharBuffer.resize(Tok.getLength());
109 const char *ThisTokBegin = &CharBuffer[0];
110 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
111
112 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
113 Tok.getLocation(), PP);
114 if (Literal.hadError())
115 return ExprResult(true);
116 return new CharacterLiteral(Literal.getValue(), Context.IntTy);
117}
118
Steve Naroff8160ea22007-03-06 01:09:46 +0000119Action::ExprResult Sema::ParseNumericConstant(const LexerToken &Tok) {
Steve Narofff2fb89e2007-03-13 20:29:44 +0000120 // fast path for a single digit (which is quite common). A single digit
121 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
122 if (Tok.getLength() == 1) {
123 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
124 return ExprResult(new IntegerLiteral(*t-'0', Context.IntTy));
125 }
Steve Naroff8160ea22007-03-06 01:09:46 +0000126 SmallString<512> IntegerBuffer;
127 IntegerBuffer.resize(Tok.getLength());
128 const char *ThisTokBegin = &IntegerBuffer[0];
129
130 // Get the spelling of the token, which eliminates trigraphs, etc. Notes:
131 // - We know that ThisTokBuf points to a buffer that is big enough for the
132 // whole token and 'spelled' tokens can only shrink.
133 // - In practice, the local buffer is only used when the spelling doesn't
134 // match the original token (which is rare). The common case simply returns
135 // a pointer to a *constant* buffer (avoiding a copy).
136
137 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Steve Naroff09ef4742007-03-09 23:16:33 +0000138 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +0000139 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +0000140 if (Literal.hadError)
141 return ExprResult(true);
142
Steve Naroff09ef4742007-03-09 23:16:33 +0000143 if (Literal.isIntegerLiteral()) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000144 QualType t;
Steve Naroff09ef4742007-03-09 23:16:33 +0000145 if (Literal.hasSuffix()) {
146 if (Literal.isLong)
147 t = Literal.isUnsigned ? Context.UnsignedLongTy : Context.LongTy;
148 else if (Literal.isLongLong)
149 t = Literal.isUnsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
150 else
151 t = Context.UnsignedIntTy;
152 } else {
153 t = Context.IntTy; // implicit type is "int"
154 }
Steve Naroff451d8f162007-03-12 23:22:38 +0000155 uintmax_t val;
156 if (Literal.GetIntegerValue(val)) {
Steve Narofff2fb89e2007-03-13 20:29:44 +0000157 return new IntegerLiteral(val, t);
Steve Naroff09ef4742007-03-09 23:16:33 +0000158 }
159 } else if (Literal.isFloatingLiteral()) {
Steve Narofff1e53692007-03-23 22:27:02 +0000160 // FIXME: fill in the value and compute the real type...
161 return new FloatingLiteral(7.7, Context.FloatTy);
Steve Naroff09ef4742007-03-09 23:16:33 +0000162 }
Steve Narofff2fb89e2007-03-13 20:29:44 +0000163 return ExprResult(true);
Chris Lattnere168f762006-11-10 05:29:30 +0000164}
165
166Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
167 ExprTy *Val) {
Steve Naroffae4143e2007-04-26 20:39:23 +0000168 Expr *e = (Expr *)Val;
169 assert((e != 0) && "ParseParenExpr() missing expr");
170 return e;
Chris Lattnere168f762006-11-10 05:29:30 +0000171}
172
Steve Naroffa78fe7e2007-05-16 19:47:19 +0000173/// The UsualUnaryConversion() function is *not* called by this routine.
174/// See C99 6.3.2.1p[2-4] for more details.
Steve Naroff043d45d2007-05-15 02:32:35 +0000175QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
176 SourceLocation OpLoc, bool isSizeof) {
177 // C99 6.5.3.4p1:
178 if (isa<FunctionType>(exprType) && isSizeof)
179 // alignof(function) is allowed.
180 Diag(OpLoc, diag::ext_sizeof_function_type);
181 else if (exprType->isVoidType())
182 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
183 else if (exprType->isIncompleteType()) {
Steve Naroff043d45d2007-05-15 02:32:35 +0000184 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
Chris Lattner3dc3d772007-05-16 18:07:12 +0000185 diag::err_alignof_incomplete_type,
186 exprType.getAsString());
Steve Naroff043d45d2007-05-15 02:32:35 +0000187 return QualType(); // error
188 }
189 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
190 return Context.getSizeType();
191}
192
Chris Lattnere168f762006-11-10 05:29:30 +0000193Action::ExprResult Sema::
194ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
195 SourceLocation LParenLoc, TypeTy *Ty,
196 SourceLocation RParenLoc) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +0000197 // If error parsing type, ignore.
198 if (Ty == 0) return true;
Chris Lattner6531c102007-01-23 22:29:49 +0000199
200 // Verify that this is a valid expression.
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000201 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
Chris Lattner6531c102007-01-23 22:29:49 +0000202
Steve Naroff043d45d2007-05-15 02:32:35 +0000203 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
204
205 if (resultType.isNull())
206 return true;
207 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType);
Chris Lattnere168f762006-11-10 05:29:30 +0000208}
209
210
211Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
212 tok::TokenKind Kind,
213 ExprTy *Input) {
214 UnaryOperator::Opcode Opc;
215 switch (Kind) {
216 default: assert(0 && "Unknown unary op!");
217 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
218 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
219 }
Steve Naroff35d85152007-05-07 00:24:15 +0000220 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
221 if (result.isNull())
222 return true;
223 return new UnaryOperator((Expr *)Input, Opc, result);
Chris Lattnere168f762006-11-10 05:29:30 +0000224}
225
226Action::ExprResult Sema::
227ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
228 ExprTy *Idx, SourceLocation RLoc) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000229 QualType t1 = ((Expr *)Base)->getType();
230 QualType t2 = ((Expr *)Idx)->getType();
Steve Narofff1e53692007-03-23 22:27:02 +0000231
232 assert(!t1.isNull() && "no type for array base expression");
Steve Naroffc1aadb12007-03-28 21:49:40 +0000233 assert(!t2.isNull() && "no type for array index expression");
Steve Narofff1e53692007-03-23 22:27:02 +0000234
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000235 QualType canonT1 = t1.getCanonicalType();
236 QualType canonT2 = t2.getCanonicalType();
Steve Naroffd50c88e2007-04-05 21:15:20 +0000237
Steve Naroffc1aadb12007-03-28 21:49:40 +0000238 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
239 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Steve Narofff1e53692007-03-23 22:27:02 +0000240 // in the subscript position. As a result, we need to derive the array base
241 // and index from the expression types.
242
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000243 QualType baseType, indexType;
Steve Naroffd50c88e2007-04-05 21:15:20 +0000244 if (isa<ArrayType>(canonT1) || isa<PointerType>(canonT1)) {
245 baseType = canonT1;
246 indexType = canonT2;
247 } else if (isa<ArrayType>(canonT2) || isa<PointerType>(canonT2)) { // uncommon
248 baseType = canonT2;
249 indexType = canonT1;
Steve Narofff1e53692007-03-23 22:27:02 +0000250 } else
251 return Diag(LLoc, diag::err_typecheck_subscript_value);
252
Steve Naroffc1aadb12007-03-28 21:49:40 +0000253 // C99 6.5.2.1p1
Steve Naroff1926c832007-04-24 00:23:05 +0000254 if (!indexType->isIntegerType())
Steve Narofff1e53692007-03-23 22:27:02 +0000255 return Diag(LLoc, diag::err_typecheck_subscript);
Steve Naroffc1aadb12007-03-28 21:49:40 +0000256
Steve Naroff95af0132007-03-30 23:47:58 +0000257 // FIXME: need to deal with const...
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000258 QualType resultType;
Steve Naroffc1aadb12007-03-28 21:49:40 +0000259 if (ArrayType *ary = dyn_cast<ArrayType>(baseType)) {
260 resultType = ary->getElementType();
261 } else if (PointerType *ary = dyn_cast<PointerType>(baseType)) {
262 resultType = ary->getPointeeType();
263 // in practice, the following check catches trying to index a pointer
264 // to a function (e.g. void (*)(int)). Functions are not objects in c99.
Steve Naroffbc2f0992007-03-30 20:09:34 +0000265 if (!resultType->isObjectType())
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000266 return Diag(LLoc, diag::err_typecheck_subscript_not_object,
267 baseType.getAsString());
Steve Naroffc1aadb12007-03-28 21:49:40 +0000268 }
269 return new ArraySubscriptExpr((Expr*)Base, (Expr*)Idx, resultType);
Chris Lattnere168f762006-11-10 05:29:30 +0000270}
271
272Action::ExprResult Sema::
273ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
274 tok::TokenKind OpKind, SourceLocation MemberLoc,
275 IdentifierInfo &Member) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000276 QualType qualifiedType = ((Expr *)Base)->getType();
Steve Naroffca8f7122007-04-01 01:41:35 +0000277
278 assert(!qualifiedType.isNull() && "no type for member expression");
279
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000280 QualType canonType = qualifiedType.getCanonicalType();
Steve Narofff1e53692007-03-23 22:27:02 +0000281
282 if (OpKind == tok::arrow) {
Steve Naroffca8f7122007-04-01 01:41:35 +0000283 if (PointerType *PT = dyn_cast<PointerType>(canonType)) {
284 qualifiedType = PT->getPointeeType();
Steve Naroffd50c88e2007-04-05 21:15:20 +0000285 canonType = qualifiedType.getCanonicalType();
Steve Naroffca8f7122007-04-01 01:41:35 +0000286 } else
Steve Narofff1e53692007-03-23 22:27:02 +0000287 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow);
288 }
Steve Naroff92e30f82007-04-02 22:35:25 +0000289 if (!isa<RecordType>(canonType))
290 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion);
291
292 // get the struct/union definition from the type.
293 RecordDecl *RD = cast<RecordType>(canonType)->getDecl();
Steve Naroffcc321422007-03-26 23:09:51 +0000294
Steve Naroff92e30f82007-04-02 22:35:25 +0000295 if (canonType->isIncompleteType())
296 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RD->getName());
Steve Naroffcc321422007-03-26 23:09:51 +0000297
Steve Naroff92e30f82007-04-02 22:35:25 +0000298 FieldDecl *MemberDecl = RD->getMember(&Member);
299 if (!MemberDecl)
300 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName());
301
302 return new MemberExpr((Expr*)Base, OpKind == tok::arrow, MemberDecl);
Chris Lattnere168f762006-11-10 05:29:30 +0000303}
304
305/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
306/// This provides the location of the left/right parens and a list of comma
307/// locations.
308Action::ExprResult Sema::
309ParseCallExpr(ExprTy *Fn, SourceLocation LParenLoc,
Steve Naroffb8c289d2007-05-08 22:18:00 +0000310 ExprTy **Args, unsigned NumArgsInCall,
Chris Lattnere168f762006-11-10 05:29:30 +0000311 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Steve Naroffae4143e2007-04-26 20:39:23 +0000312 QualType qType = ((Expr *)Fn)->getType();
313
314 assert(!qType.isNull() && "no type for function call expression");
315
Steve Naroff17f76e02007-05-03 21:03:48 +0000316 const FunctionType *funcT = dyn_cast<FunctionType>(qType.getCanonicalType());
Steve Naroffae4143e2007-04-26 20:39:23 +0000317
Steve Naroff17f76e02007-05-03 21:03:48 +0000318 assert(funcT && "ParseCallExpr(): not a function type");
Steve Naroffb8c289d2007-05-08 22:18:00 +0000319
Steve Naroff17f76e02007-05-03 21:03:48 +0000320 // If a prototype isn't declared, the parser implicitly defines a func decl
321 QualType resultType = funcT->getResultType();
322
323 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
324 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
325 // assignment, to the types of the corresponding parameter, ...
326
327 unsigned NumArgsInProto = proto->getNumArgs();
Steve Naroffb8c289d2007-05-08 22:18:00 +0000328 unsigned NumArgsToCheck = NumArgsInCall;
Steve Naroff17f76e02007-05-03 21:03:48 +0000329
Steve Naroffb8c289d2007-05-08 22:18:00 +0000330 if (NumArgsInCall < NumArgsInProto)
Steve Naroff1f4d7272007-05-11 04:00:31 +0000331 Diag(LParenLoc, diag::err_typecheck_call_too_few_args);
Steve Naroffb8c289d2007-05-08 22:18:00 +0000332 else if (NumArgsInCall > NumArgsInProto) {
333 if (!proto->isVariadic())
Steve Naroff1f4d7272007-05-11 04:00:31 +0000334 Diag(LParenLoc, diag::err_typecheck_call_too_many_args);
Steve Naroffb8c289d2007-05-08 22:18:00 +0000335 NumArgsToCheck = NumArgsInProto;
Steve Naroff17f76e02007-05-03 21:03:48 +0000336 }
337 // Continue to check argument types (even if we have too few/many args).
Steve Naroffb8c289d2007-05-08 22:18:00 +0000338 for (unsigned i = 0; i < NumArgsToCheck; i++) {
Steve Naroff17f76e02007-05-03 21:03:48 +0000339 QualType lhsType = proto->getArgType(i);
340 QualType rhsType = ((Expr **)Args)[i]->getType();
341
342 if (lhsType == rhsType) // common case, fast path...
343 continue;
344 AssignmentConversionResult result;
Steve Naroff218bc2b2007-05-04 21:54:46 +0000345 UsualAssignmentConversions(lhsType, rhsType, result);
Steve Naroff17f76e02007-05-03 21:03:48 +0000346
347 SourceLocation l = (i == 0) ? LParenLoc : CommaLocs[i-1];
348
349 // decode the result (notice that AST's are still created for extensions).
350 // FIXME: consider fancier error diagnostics (since this is quite common).
351 // #1: emit the actual prototype arg...requires adding source loc info.
352 // #2: pass Diag the offending argument type...requires hacking Diag.
353 switch (result) {
354 case Compatible:
355 break;
356 case PointerFromInt:
Steve Naroff218bc2b2007-05-04 21:54:46 +0000357 // check for null pointer constant (C99 6.3.2.3p3)
358 if (!((Expr **)Args)[i]->isNullPointerConstant())
359 Diag(l, diag::ext_typecheck_passing_pointer_from_int, utostr(i+1));
Steve Naroff17f76e02007-05-03 21:03:48 +0000360 break;
361 case IntFromPointer:
362 Diag(l, diag::ext_typecheck_passing_int_from_pointer, utostr(i+1));
363 break;
364 case IncompatiblePointer:
365 Diag(l, diag::ext_typecheck_passing_incompatible_pointer, utostr(i+1));
366 break;
Steve Naroff1f4d7272007-05-11 04:00:31 +0000367 case CompatiblePointerDiscardsQualifiers:
368 Diag(l, diag::ext_typecheck_passing_discards_qualifiers, utostr(i+1));
369 break;
Steve Naroff17f76e02007-05-03 21:03:48 +0000370 case Incompatible:
371 return Diag(l, diag::err_typecheck_passing_incompatible, utostr(i+1));
372 }
373 }
Steve Naroffb8c289d2007-05-08 22:18:00 +0000374 // Even if the types checked, bail if we had the wrong number of arguments.
375 if ((NumArgsInCall != NumArgsInProto) && !proto->isVariadic())
376 return true;
Steve Naroffae4143e2007-04-26 20:39:23 +0000377 }
Steve Naroffb8c289d2007-05-08 22:18:00 +0000378 return new CallExpr((Expr*)Fn, (Expr**)Args, NumArgsInCall, resultType);
Chris Lattnere168f762006-11-10 05:29:30 +0000379}
380
381Action::ExprResult Sema::
382ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
383 SourceLocation RParenLoc, ExprTy *Op) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +0000384 // If error parsing type, ignore.
Steve Naroffae4143e2007-04-26 20:39:23 +0000385 assert((Ty != 0) && "ParseCastExpr(): missing type");
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000386 return new CastExpr(QualType::getFromOpaquePtr(Ty), (Expr*)Op);
Chris Lattnere168f762006-11-10 05:29:30 +0000387}
388
Steve Narofff8a28c52007-05-15 20:29:32 +0000389inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
390 Expr *Cond, Expr *LHS, Expr *RHS, SourceLocation questionLoc) {
Steve Naroffa78fe7e2007-05-16 19:47:19 +0000391 QualType cond = Cond->getType();
392 QualType lhs = LHS->getType();
393 QualType rhs = RHS->getType();
394
Steve Narofff8a28c52007-05-15 20:29:32 +0000395 assert(!cond.isNull() && "ParseConditionalOp(): no conditional type");
396 assert(!lhs.isNull() && "ParseConditionalOp(): no lhs type");
397 assert(!rhs.isNull() && "ParseConditionalOp(): no rhs type");
398
Steve Naroffa78fe7e2007-05-16 19:47:19 +0000399 cond = UsualUnaryConversion(cond);
400 lhs = UsualUnaryConversion(lhs);
401 rhs = UsualUnaryConversion(rhs);
402
403 // first, check the condition.
404 if (!cond->isScalarType()) { // C99 6.5.15p2
405 // FIXME: need to compute the location from the Cond expr node...
406 Diag(questionLoc, diag::err_typecheck_cond_expect_scalar,
407 cond.getAsString());
408 return QualType();
409 }
410 // now check the two expressions.
411 if (lhs->isArithmeticType() && rhs->isArithmeticType()) // C99 6.5.15p3,5
412 return UsualArithmeticConversions(lhs, rhs);
413
414 if ((lhs->isStructureType() && rhs->isStructureType()) || // C99 6.5.15p3
415 (lhs->isUnionType() && rhs->isUnionType())) {
416 TagType *lTag = cast<TagType>(lhs.getCanonicalType());
417 TagType *rTag = cast<TagType>(rhs.getCanonicalType());
418
419 if (lTag->getDecl()->getIdentifier() == rTag->getDecl()->getIdentifier())
420 return lhs;
421 else {
422 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
423 lhs.getAsString(), rhs.getAsString());
424 return QualType();
425 }
426 }
427 if (lhs->isPointerType() && rhs->isPointerType()) { // C99 6.5.15p3,6
428 QualType lhptee, rhptee;
429
430 // get the "pointed to" type
431 lhptee = cast<PointerType>(lhs.getCanonicalType())->getPointeeType();
432 rhptee = cast<PointerType>(rhs.getCanonicalType())->getPointeeType();
433
434 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
435 if (lhptee.getUnqualifiedType()->isVoidType() &&
436 (rhptee->isObjectType() || rhptee->isIncompleteType()))
437 return lhs;
438 if (rhptee.getUnqualifiedType()->isVoidType() &&
439 (lhptee->isObjectType() || lhptee->isIncompleteType()))
440 return rhs;
441
442 // FIXME: C99 6.5.15p6: If both operands are pointers to compatible types
443 // *or* to differently qualified versions of compatible types, the result
444 // type is a pointer to an appropriately qualified version of the
445 // *composite* type.
446 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
447 rhptee.getUnqualifiedType())) {
448 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
449 lhs.getAsString(), rhs.getAsString());
450 return lhs; // FIXME: this is an _ext - is this return o.k?
451 }
452 }
453 if (lhs->isVoidType() && rhs->isVoidType()) // C99 6.5.15p3
454 return lhs;
455 if (lhs->isPointerType() && RHS->isNullPointerConstant()) // C99 6.5.15p3
456 return lhs;
457 if (rhs->isPointerType() && LHS->isNullPointerConstant()) // C99 6.5.15p3
458 return rhs;
459
460 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
461 lhs.getAsString(), rhs.getAsString());
462 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +0000463}
464
Chris Lattnere168f762006-11-10 05:29:30 +0000465/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
466/// in the case of a the GNU conditional expr extension.
467Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
468 SourceLocation ColonLoc,
469 ExprTy *Cond, ExprTy *LHS,
470 ExprTy *RHS) {
Steve Narofff8a28c52007-05-15 20:29:32 +0000471 QualType result = CheckConditionalOperands((Expr *)Cond, (Expr *)LHS,
472 (Expr *)RHS, QuestionLoc);
473 if (result.isNull())
474 return true;
475 return new ConditionalOperator((Expr*)Cond, (Expr*)LHS, (Expr*)RHS, result);
Chris Lattnere168f762006-11-10 05:29:30 +0000476}
477
Steve Naroff1926c832007-04-24 00:23:05 +0000478/// UsualUnaryConversion - Performs various conversions that are common to most
479/// operators (C99 6.3). The conversions of array and function types are
480/// sometimes surpressed. For example, the array->pointer conversion doesn't
481/// apply if the array is an argument to the sizeof or address (&) operators.
482/// In these instances, this routine should *not* be called.
483QualType Sema::UsualUnaryConversion(QualType t) {
484 assert(!t.isNull() && "UsualUnaryConversion - missing type");
Steve Naroff4b7ce032007-04-20 22:26:17 +0000485
Steve Naroff1926c832007-04-24 00:23:05 +0000486 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
487 return Context.IntTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +0000488 if (t->isFunctionType()) // C99 6.3.2.1p4
489 return Context.getPointerType(t.getCanonicalType());
490 if (const ArrayType *ary = dyn_cast<ArrayType>(t.getCanonicalType()))
491 return Context.getPointerType(ary->getElementType()); // C99 6.3.2.1p3
Steve Naroff1926c832007-04-24 00:23:05 +0000492 return t;
493}
494
495/// UsualArithmeticConversions - Performs various conversions that are common to
496/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
497/// routine returns the first non-arithmetic type found. The client is
498/// responsible for emitting appropriate error diagnostics.
499QualType Sema::UsualArithmeticConversions(QualType t1, QualType t2) {
Steve Naroffb01bbe32007-04-25 01:22:31 +0000500 QualType lhs = UsualUnaryConversion(t1);
501 QualType rhs = UsualUnaryConversion(t2);
Steve Naroff1926c832007-04-24 00:23:05 +0000502
503 // if either operand is not of arithmetic type, no conversion is possible.
Steve Naroffb01bbe32007-04-25 01:22:31 +0000504 if (!lhs->isArithmeticType())
505 return lhs;
Steve Narofff633d092007-04-25 19:01:39 +0000506 if (!rhs->isArithmeticType())
Steve Naroffb01bbe32007-04-25 01:22:31 +0000507 return rhs;
Steve Naroff1926c832007-04-24 00:23:05 +0000508
Steve Narofff633d092007-04-25 19:01:39 +0000509 // if both arithmetic types are identical, no conversion is needed.
Steve Naroffb01bbe32007-04-25 01:22:31 +0000510 if (lhs == rhs)
511 return lhs;
Steve Naroff1926c832007-04-24 00:23:05 +0000512
Steve Naroffb01bbe32007-04-25 01:22:31 +0000513 // at this point, we have two different arithmetic types.
514
515 // Handle complex types first (C99 6.3.1.8p1).
516 if (lhs->isComplexType() || rhs->isComplexType()) {
517 // if we have an integer operand, the result is the complex type.
518 if (rhs->isIntegerType())
519 return lhs;
520 if (lhs->isIntegerType())
521 return rhs;
522
Steve Naroffe4718892007-04-27 18:30:00 +0000523 return Context.maxComplexType(lhs, rhs);
Steve Naroffbf223ba2007-04-24 20:56:26 +0000524 }
Steve Naroffb01bbe32007-04-25 01:22:31 +0000525 // Now handle "real" floating types (i.e. float, double, long double).
526 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
527 // if we have an integer operand, the result is the real floating type.
528 if (rhs->isIntegerType())
529 return lhs;
530 if (lhs->isIntegerType())
531 return rhs;
532
533 // we have two real floating types, float/complex combos were handled above.
Steve Naroffe4718892007-04-27 18:30:00 +0000534 return Context.maxFloatingType(lhs, rhs);
Steve Naroffb01bbe32007-04-25 01:22:31 +0000535 }
Steve Naroffe4718892007-04-27 18:30:00 +0000536 return Context.maxIntegerType(lhs, rhs);
Steve Narofff1e53692007-03-23 22:27:02 +0000537}
538
Steve Naroff3f597292007-05-11 22:18:03 +0000539// CheckPointerTypesForAssignment - This is a very tricky routine (despite
540// being closely modeled after the C99 spec:-). The odd characteristic of this
541// routine is it effectively iqnores the qualifiers on the top level pointee.
542// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
543// FIXME: add a couple examples in this comment.
544QualType Sema::CheckPointerTypesForAssignment(QualType lhsType,
545 QualType rhsType,
546 AssignmentConversionResult &r) {
547 QualType lhptee, rhptee;
Steve Naroff1f4d7272007-05-11 04:00:31 +0000548
549 // get the "pointed to" type (ignoring qualifiers at the top level)
Steve Naroff3f597292007-05-11 22:18:03 +0000550 lhptee = cast<PointerType>(lhsType.getCanonicalType())->getPointeeType();
551 rhptee = cast<PointerType>(rhsType.getCanonicalType())->getPointeeType();
Steve Naroff1f4d7272007-05-11 04:00:31 +0000552
553 // make sure we operate on the canonical type
Steve Naroff3f597292007-05-11 22:18:03 +0000554 lhptee = lhptee.getCanonicalType();
555 rhptee = rhptee.getCanonicalType();
Steve Naroff1f4d7272007-05-11 04:00:31 +0000556
Steve Naroff3f597292007-05-11 22:18:03 +0000557 // C99 6.5.16.1p1: This following citation is common to constraints
558 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
559 // qualifiers of the type *pointed to* by the right;
560 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
561 rhptee.getQualifiers())
562 r = CompatiblePointerDiscardsQualifiers;
563
564 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
565 // incomplete type and the other is a pointer to a qualified or unqualified
566 // version of void...
567 if (lhptee.getUnqualifiedType()->isVoidType() &&
568 (rhptee->isObjectType() || rhptee->isIncompleteType()))
569 ;
570 else if (rhptee.getUnqualifiedType()->isVoidType() &&
571 (lhptee->isObjectType() || lhptee->isIncompleteType()))
572 ;
573 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
574 // unqualified versions of compatible types, ...
575 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
576 rhptee.getUnqualifiedType()))
577 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
578 return rhsType;
Steve Naroff1f4d7272007-05-11 04:00:31 +0000579}
580
Steve Naroff17f76e02007-05-03 21:03:48 +0000581/// UsualAssignmentConversions (C99 6.5.16) - This routine currently
582/// has code to accommodate several GCC extensions when type checking
583/// pointers. Here are some objectionable examples that GCC considers warnings:
584///
585/// int a, *pint;
586/// short *pshort;
587/// struct foo *pfoo;
588///
589/// pint = pshort; // warning: assignment from incompatible pointer type
590/// a = pint; // warning: assignment makes integer from pointer without a cast
591/// pint = a; // warning: assignment makes pointer from integer without a cast
592/// pint = pfoo; // warning: assignment from incompatible pointer type
593///
594/// As a result, the code for dealing with pointers is more complex than the
595/// C99 spec dictates.
596/// Note: the warning above turn into errors when -pedantic-errors is enabled.
597///
Steve Naroff218bc2b2007-05-04 21:54:46 +0000598QualType Sema::UsualAssignmentConversions(QualType lhsType, QualType rhsType,
Steve Naroff17f76e02007-05-03 21:03:48 +0000599 AssignmentConversionResult &r) {
Steve Naroffb891de32007-05-02 23:51:10 +0000600 // this check seems unnatural, however it necessary to insure the proper
601 // conversion of functions/arrays. If the conversion where done for all
602 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the
603 // unary expressions that surpress this implicit conversion (&, sizeof).
604 if (rhsType->isFunctionType() || rhsType->isArrayType())
605 rhsType = UsualUnaryConversion(rhsType);
606
Steve Naroff17f76e02007-05-03 21:03:48 +0000607 r = Compatible;
Steve Naroff9eb24652007-05-02 21:58:15 +0000608 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
609 return lhsType;
610 else if (lhsType->isPointerType()) {
611 if (rhsType->isIntegerType()) {
Steve Naroff218bc2b2007-05-04 21:54:46 +0000612 r = PointerFromInt;
Steve Naroffb891de32007-05-02 23:51:10 +0000613 return rhsType;
Steve Naroff9eb24652007-05-02 21:58:15 +0000614 }
Steve Naroff3f597292007-05-11 22:18:03 +0000615 if (rhsType->isPointerType())
616 return CheckPointerTypesForAssignment(lhsType, rhsType, r);
Steve Naroff9eb24652007-05-02 21:58:15 +0000617 } else if (rhsType->isPointerType()) {
618 if (lhsType->isIntegerType()) {
619 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
620 if (lhsType != Context.BoolTy)
Steve Naroff17f76e02007-05-03 21:03:48 +0000621 r = IntFromPointer;
Steve Naroffb891de32007-05-02 23:51:10 +0000622 return rhsType;
Steve Naroff9eb24652007-05-02 21:58:15 +0000623 }
Steve Naroff3f597292007-05-11 22:18:03 +0000624 if (lhsType->isPointerType())
625 return CheckPointerTypesForAssignment(lhsType, rhsType, r);
Steve Naroff1f4d7272007-05-11 04:00:31 +0000626 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
627 if (Type::tagTypesAreCompatible(lhsType, rhsType))
Steve Naroffb891de32007-05-02 23:51:10 +0000628 return rhsType;
Steve Naroff1f4d7272007-05-11 04:00:31 +0000629 }
Steve Naroff17f76e02007-05-03 21:03:48 +0000630 r = Incompatible;
631 return QualType();
Steve Naroff9eb24652007-05-02 21:58:15 +0000632}
633
Steve Naroff218bc2b2007-05-04 21:54:46 +0000634inline QualType Sema::CheckMultiplyDivideOperands(
635 Expr *lex, Expr *rex, SourceLocation loc)
Steve Naroff5c10d4b2007-04-20 23:42:24 +0000636{
Steve Naroff1926c832007-04-24 00:23:05 +0000637 QualType resType = UsualArithmeticConversions(lex->getType(), rex->getType());
Steve Naroff5c10d4b2007-04-20 23:42:24 +0000638
Steve Naroff218bc2b2007-05-04 21:54:46 +0000639 if (resType->isArithmeticType())
640 return resType;
641 Diag(loc, diag::err_typecheck_invalid_operands);
642 return QualType();
Steve Naroff26c8ea52007-03-21 21:08:52 +0000643}
644
Steve Naroff218bc2b2007-05-04 21:54:46 +0000645inline QualType Sema::CheckRemainderOperands(
646 Expr *lex, Expr *rex, SourceLocation loc)
647{
648 QualType resType = UsualArithmeticConversions(lex->getType(), rex->getType());
649
650 if (resType->isIntegerType())
651 return resType;
652 Diag(loc, diag::err_typecheck_invalid_operands);
653 return QualType();
654}
655
656inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
657 Expr *lex, Expr *rex, SourceLocation loc)
Steve Naroff1926c832007-04-24 00:23:05 +0000658{
Steve Naroffe4718892007-04-27 18:30:00 +0000659 QualType lhsType = lex->getType(), rhsType = rex->getType();
660 QualType resType = UsualArithmeticConversions(lhsType, rhsType);
661
662 // handle the common case first (both operands are arithmetic).
663 if (resType->isArithmeticType())
Steve Naroff218bc2b2007-05-04 21:54:46 +0000664 return resType;
665
666 if ((lhsType->isPointerType() && rhsType->isIntegerType()) ||
667 (lhsType->isIntegerType() && rhsType->isPointerType()))
668 return resType;
669 Diag(loc, diag::err_typecheck_invalid_operands);
670 return QualType();
Steve Naroff26c8ea52007-03-21 21:08:52 +0000671}
672
Steve Naroff218bc2b2007-05-04 21:54:46 +0000673inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
674 Expr *lex, Expr *rex, SourceLocation loc)
675{
676 QualType lhsType = lex->getType(), rhsType = rex->getType();
677 QualType resType = UsualArithmeticConversions(lhsType, rhsType);
678
679 // handle the common case first (both operands are arithmetic).
680 if (resType->isArithmeticType())
681 return resType;
682 if ((lhsType->isPointerType() && rhsType->isIntegerType()) ||
683 (lhsType->isPointerType() && rhsType->isPointerType()))
684 return resType;
685 Diag(loc, diag::err_typecheck_invalid_operands);
686 return QualType();
687}
688
689inline QualType Sema::CheckShiftOperands( // C99 6.5.7
690 Expr *lex, Expr *rex, SourceLocation loc)
Steve Naroff1926c832007-04-24 00:23:05 +0000691{
692 QualType resType = UsualArithmeticConversions(lex->getType(), rex->getType());
693
Steve Naroff218bc2b2007-05-04 21:54:46 +0000694 if (resType->isIntegerType())
695 return resType;
696 Diag(loc, diag::err_typecheck_invalid_operands);
697 return QualType();
Steve Naroff26c8ea52007-03-21 21:08:52 +0000698}
699
Steve Naroff218bc2b2007-05-04 21:54:46 +0000700inline QualType Sema::CheckRelationalOperands( // C99 6.5.8
701 Expr *lex, Expr *rex, SourceLocation loc)
Steve Naroff1926c832007-04-24 00:23:05 +0000702{
703 QualType lType = lex->getType(), rType = rex->getType();
704
705 if (lType->isRealType() && rType->isRealType())
Steve Naroff218bc2b2007-05-04 21:54:46 +0000706 return Context.IntTy;
Steve Naroffe4718892007-04-27 18:30:00 +0000707
708 if (lType->isPointerType() && rType->isPointerType())
Steve Naroff218bc2b2007-05-04 21:54:46 +0000709 return Context.IntTy;
Steve Naroffe4718892007-04-27 18:30:00 +0000710
Steve Naroff043d45d2007-05-15 02:32:35 +0000711 if (lType->isIntegerType() || rType->isIntegerType()) { // GCC extension.
Steve Naroff218bc2b2007-05-04 21:54:46 +0000712 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer);
Steve Naroff043d45d2007-05-15 02:32:35 +0000713 return Context.IntTy;
714 }
715 Diag(loc, diag::err_typecheck_invalid_operands);
Steve Naroff218bc2b2007-05-04 21:54:46 +0000716 return QualType();
Steve Naroff26c8ea52007-03-21 21:08:52 +0000717}
718
Steve Naroff218bc2b2007-05-04 21:54:46 +0000719inline QualType Sema::CheckEqualityOperands( // C99 6.5.9
720 Expr *lex, Expr *rex, SourceLocation loc)
Steve Naroff1926c832007-04-24 00:23:05 +0000721{
722 QualType lType = lex->getType(), rType = rex->getType();
723
724 if (lType->isArithmeticType() && rType->isArithmeticType())
Steve Naroff218bc2b2007-05-04 21:54:46 +0000725 return Context.IntTy;
Steve Naroffe4718892007-04-27 18:30:00 +0000726 if (lType->isPointerType() && rType->isPointerType())
Steve Naroff218bc2b2007-05-04 21:54:46 +0000727 return Context.IntTy;
728
Steve Naroff043d45d2007-05-15 02:32:35 +0000729 if (lType->isIntegerType() || rType->isIntegerType()) { // GCC extension.
Steve Naroff218bc2b2007-05-04 21:54:46 +0000730 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer);
Steve Naroff043d45d2007-05-15 02:32:35 +0000731 return Context.IntTy;
732 }
733 Diag(loc, diag::err_typecheck_invalid_operands);
Steve Naroff218bc2b2007-05-04 21:54:46 +0000734 return QualType();
Steve Naroff26c8ea52007-03-21 21:08:52 +0000735}
736
Steve Naroff218bc2b2007-05-04 21:54:46 +0000737inline QualType Sema::CheckBitwiseOperands(
738 Expr *lex, Expr *rex, SourceLocation loc)
Steve Naroff1926c832007-04-24 00:23:05 +0000739{
740 QualType resType = UsualArithmeticConversions(lex->getType(), rex->getType());
741
Steve Naroff218bc2b2007-05-04 21:54:46 +0000742 if (resType->isIntegerType())
743 return resType;
744 Diag(loc, diag::err_typecheck_invalid_operands);
745 return QualType();
Steve Naroff26c8ea52007-03-21 21:08:52 +0000746}
747
Steve Naroff218bc2b2007-05-04 21:54:46 +0000748inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
749 Expr *lex, Expr *rex, SourceLocation loc)
Steve Naroff1926c832007-04-24 00:23:05 +0000750{
Steve Naroffe4718892007-04-27 18:30:00 +0000751 QualType lhsType = UsualUnaryConversion(lex->getType());
752 QualType rhsType = UsualUnaryConversion(rex->getType());
753
Steve Naroff218bc2b2007-05-04 21:54:46 +0000754 if (lhsType->isScalarType() || rhsType->isScalarType())
755 return Context.IntTy;
756 Diag(loc, diag::err_typecheck_invalid_operands);
757 return QualType();
Steve Naroffae4143e2007-04-26 20:39:23 +0000758}
759
Steve Naroff35d85152007-05-07 00:24:15 +0000760inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
761 Expr *lex, Expr *rex, SourceLocation loc, QualType compoundType)
Steve Naroffae4143e2007-04-26 20:39:23 +0000762{
Steve Naroff0af91202007-04-27 21:51:21 +0000763 QualType lhsType = lex->getType();
Steve Naroff35d85152007-05-07 00:24:15 +0000764 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Steve Naroff1f4d7272007-05-11 04:00:31 +0000765 bool hadError = false;
Steve Naroff218bc2b2007-05-04 21:54:46 +0000766
767 // this check is done first to give a more precise diagnostic.
Steve Naroff1f4d7272007-05-11 04:00:31 +0000768 // isModifiableLvalue() will also check for "const".
Steve Naroff218bc2b2007-05-04 21:54:46 +0000769 if (lhsType.isConstQualified()) {
770 Diag(loc, diag::err_typecheck_assign_const);
Steve Naroff1f4d7272007-05-11 04:00:31 +0000771 hadError = true;
772 } else if (!lex->isModifiableLvalue()) { // C99 6.5.16p2
773 Diag(loc, diag::err_typecheck_assign_non_lvalue);
774 return QualType(); // no need to continue checking...
Steve Naroff218bc2b2007-05-04 21:54:46 +0000775 }
776 if (lhsType == rhsType) // common case, fast path...
777 return lhsType;
778
779 AssignmentConversionResult result;
780 QualType resType = UsualAssignmentConversions(lhsType, rhsType, result);
781
782 // decode the result (notice that extensions still return a type).
783 switch (result) {
784 case Compatible:
Steve Naroff1f4d7272007-05-11 04:00:31 +0000785 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +0000786 case Incompatible:
787 Diag(loc, diag::err_typecheck_assign_incompatible);
Steve Naroff1f4d7272007-05-11 04:00:31 +0000788 hadError = true;
789 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +0000790 case PointerFromInt:
791 // check for null pointer constant (C99 6.3.2.3p3)
Steve Naroff35d85152007-05-07 00:24:15 +0000792 if (compoundType.isNull() && !rex->isNullPointerConstant())
Steve Naroff218bc2b2007-05-04 21:54:46 +0000793 Diag(loc, diag::ext_typecheck_assign_pointer_from_int);
Steve Naroff1f4d7272007-05-11 04:00:31 +0000794 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +0000795 case IntFromPointer:
796 Diag(loc, diag::ext_typecheck_assign_int_from_pointer);
Steve Naroff1f4d7272007-05-11 04:00:31 +0000797 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +0000798 case IncompatiblePointer:
799 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer);
Steve Naroff1f4d7272007-05-11 04:00:31 +0000800 break;
801 case CompatiblePointerDiscardsQualifiers:
802 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers);
803 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +0000804 }
Steve Naroff1f4d7272007-05-11 04:00:31 +0000805 return hadError ? QualType() : resType;
Steve Naroffae4143e2007-04-26 20:39:23 +0000806}
807
Steve Naroff218bc2b2007-05-04 21:54:46 +0000808inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroffae4143e2007-04-26 20:39:23 +0000809 Expr *lex, Expr *rex, SourceLocation loc)
810{
Steve Naroff218bc2b2007-05-04 21:54:46 +0000811 return UsualUnaryConversion(rex->getType());
Steve Naroff95af0132007-03-30 23:47:58 +0000812}
813
Steve Naroff35d85152007-05-07 00:24:15 +0000814QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff094046f2007-05-13 03:21:25 +0000815 QualType resType = UsualArithmeticConversions(op->getType(), Context.IntTy);
Steve Naroff35d85152007-05-07 00:24:15 +0000816 assert(!resType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +0000817
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000818 // C99 6.5.2.4p1
Steve Naroff35d85152007-05-07 00:24:15 +0000819 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
820 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000821 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
822 resType.getAsString());
Steve Naroff35d85152007-05-07 00:24:15 +0000823 return QualType();
824 }
825 } else if (!resType->isRealType()) {
Steve Naroff95af0132007-03-30 23:47:58 +0000826 // FIXME: Allow Complex as a GCC extension.
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000827 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
828 resType.getAsString());
Steve Naroff35d85152007-05-07 00:24:15 +0000829 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000830 }
Steve Naroff094046f2007-05-13 03:21:25 +0000831 // At this point, we know we have a real or pointer type. Now make sure
832 // the operand is a modifiable lvalue.
833 if (!op->isModifiableLvalue()) {
834 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr);
Steve Naroff35d85152007-05-07 00:24:15 +0000835 return QualType();
836 }
837 return resType;
Steve Naroff26c8ea52007-03-21 21:08:52 +0000838}
839
Steve Naroff1926c832007-04-24 00:23:05 +0000840/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +0000841/// This routine allows us to typecheck complex/recursive expressions
842/// where the declaration is needed for type checking. Here are some
843/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Steve Naroff1926c832007-04-24 00:23:05 +0000844static Decl *getPrimaryDeclaration(Expr *e) {
Steve Naroff47500512007-04-19 23:00:49 +0000845 switch (e->getStmtClass()) {
846 case Stmt::DeclRefExprClass:
847 return cast<DeclRefExpr>(e)->getDecl();
848 case Stmt::MemberExprClass:
Steve Naroff1926c832007-04-24 00:23:05 +0000849 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
Steve Naroff47500512007-04-19 23:00:49 +0000850 case Stmt::ArraySubscriptExprClass:
Steve Naroff1926c832007-04-24 00:23:05 +0000851 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Steve Naroff47500512007-04-19 23:00:49 +0000852 case Stmt::CallExprClass:
Steve Naroff1926c832007-04-24 00:23:05 +0000853 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
Steve Naroff47500512007-04-19 23:00:49 +0000854 case Stmt::UnaryOperatorClass:
Steve Naroff1926c832007-04-24 00:23:05 +0000855 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +0000856 case Stmt::ParenExprClass:
Steve Naroff1926c832007-04-24 00:23:05 +0000857 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +0000858 default:
859 return 0;
860 }
861}
862
863/// CheckAddressOfOperand - The operand of & must be either a function
864/// designator or an lvalue designating an object. If it is an lvalue, the
865/// object cannot be declared with storage class register or be a bit field.
866/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +0000867/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Steve Naroff35d85152007-05-07 00:24:15 +0000868QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff1926c832007-04-24 00:23:05 +0000869 Decl *dcl = getPrimaryDeclaration(op);
Steve Naroff47500512007-04-19 23:00:49 +0000870
Steve Naroff5dd642e2007-05-14 18:14:51 +0000871 if (!op->isLvalue()) { // C99 6.5.3.2p1
872 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
873 ;
Steve Naroff35d85152007-05-07 00:24:15 +0000874 else {
875 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof);
876 return QualType();
877 }
Steve Naroff47500512007-04-19 23:00:49 +0000878 } else if (dcl) {
879 // We have an lvalue with a decl. Make sure the decl is not declared
880 // with the register storage-class specifier.
881 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +0000882 if (vd->getStorageClass() == VarDecl::Register) {
883 Diag(OpLoc, diag::err_typecheck_address_of_register);
884 return QualType();
885 }
Steve Narofff633d092007-04-25 19:01:39 +0000886 } else
887 assert(0 && "Unknown/unexpected decl type");
888
Steve Naroff47500512007-04-19 23:00:49 +0000889 // FIXME: add check for bitfields!
890 }
891 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +0000892 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +0000893}
894
Steve Naroff35d85152007-05-07 00:24:15 +0000895QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
896 QualType qType = UsualUnaryConversion(op->getType());
897
Steve Naroff47500512007-04-19 23:00:49 +0000898 assert(!qType.isNull() && "no type for * expression");
899
Steve Naroff35d85152007-05-07 00:24:15 +0000900 if (PointerType *PT = dyn_cast<PointerType>(qType))
901 return PT->getPointeeType();
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000902 Diag(OpLoc, diag::err_typecheck_unary_expr, qType.getAsString());
Steve Naroff35d85152007-05-07 00:24:15 +0000903 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +0000904}
Steve Naroff218bc2b2007-05-04 21:54:46 +0000905
906static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
907 tok::TokenKind Kind) {
908 BinaryOperator::Opcode Opc;
909 switch (Kind) {
910 default: assert(0 && "Unknown binop!");
911 case tok::star: Opc = BinaryOperator::Mul; break;
912 case tok::slash: Opc = BinaryOperator::Div; break;
913 case tok::percent: Opc = BinaryOperator::Rem; break;
914 case tok::plus: Opc = BinaryOperator::Add; break;
915 case tok::minus: Opc = BinaryOperator::Sub; break;
916 case tok::lessless: Opc = BinaryOperator::Shl; break;
917 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
918 case tok::lessequal: Opc = BinaryOperator::LE; break;
919 case tok::less: Opc = BinaryOperator::LT; break;
920 case tok::greaterequal: Opc = BinaryOperator::GE; break;
921 case tok::greater: Opc = BinaryOperator::GT; break;
922 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
923 case tok::equalequal: Opc = BinaryOperator::EQ; break;
924 case tok::amp: Opc = BinaryOperator::And; break;
925 case tok::caret: Opc = BinaryOperator::Xor; break;
926 case tok::pipe: Opc = BinaryOperator::Or; break;
927 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
928 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
929 case tok::equal: Opc = BinaryOperator::Assign; break;
930 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
931 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
932 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
933 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
934 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
935 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
936 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
937 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
938 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
939 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
940 case tok::comma: Opc = BinaryOperator::Comma; break;
941 }
942 return Opc;
943}
944
Steve Naroff35d85152007-05-07 00:24:15 +0000945static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
946 tok::TokenKind Kind) {
947 UnaryOperator::Opcode Opc;
948 switch (Kind) {
949 default: assert(0 && "Unknown unary op!");
950 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
951 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
952 case tok::amp: Opc = UnaryOperator::AddrOf; break;
953 case tok::star: Opc = UnaryOperator::Deref; break;
954 case tok::plus: Opc = UnaryOperator::Plus; break;
955 case tok::minus: Opc = UnaryOperator::Minus; break;
956 case tok::tilde: Opc = UnaryOperator::Not; break;
957 case tok::exclaim: Opc = UnaryOperator::LNot; break;
958 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
959 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
960 case tok::kw___real: Opc = UnaryOperator::Real; break;
961 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
962 case tok::ampamp: Opc = UnaryOperator::AddrLabel; break;
963 // FIXME: case tok::kw___extension__:
964 }
965 return Opc;
966}
967
Steve Naroff218bc2b2007-05-04 21:54:46 +0000968// Binary Operators. 'Tok' is the token for the operator.
969Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
970 ExprTy *LHS, ExprTy *RHS) {
971 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
972 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
973
974 assert((lhs != 0) && "ParseBinOp(): missing left expression");
975 assert((rhs != 0) && "ParseBinOp(): missing right expression");
976
977 QualType result;
978
979 switch (Opc) {
980 default:
981 assert(0 && "Unknown binary expr!");
982 case BinaryOperator::Assign:
Steve Naroff35d85152007-05-07 00:24:15 +0000983 result = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
Steve Naroff218bc2b2007-05-04 21:54:46 +0000984 break;
985 case BinaryOperator::Mul:
986 case BinaryOperator::Div:
987 result = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
988 break;
989 case BinaryOperator::Rem:
990 result = CheckRemainderOperands(lhs, rhs, TokLoc);
991 break;
992 case BinaryOperator::Add:
993 result = CheckAdditionOperands(lhs, rhs, TokLoc);
994 break;
995 case BinaryOperator::Sub:
996 result = CheckSubtractionOperands(lhs, rhs, TokLoc);
997 break;
998 case BinaryOperator::Shl:
999 case BinaryOperator::Shr:
1000 result = CheckShiftOperands(lhs, rhs, TokLoc);
1001 break;
1002 case BinaryOperator::LE:
1003 case BinaryOperator::LT:
1004 case BinaryOperator::GE:
1005 case BinaryOperator::GT:
1006 result = CheckRelationalOperands(lhs, rhs, TokLoc);
1007 break;
1008 case BinaryOperator::EQ:
1009 case BinaryOperator::NE:
1010 result = CheckEqualityOperands(lhs, rhs, TokLoc);
1011 break;
1012 case BinaryOperator::And:
1013 case BinaryOperator::Xor:
1014 case BinaryOperator::Or:
1015 result = CheckBitwiseOperands(lhs, rhs, TokLoc);
1016 break;
1017 case BinaryOperator::LAnd:
1018 case BinaryOperator::LOr:
1019 result = CheckLogicalOperands(lhs, rhs, TokLoc);
1020 break;
1021 case BinaryOperator::MulAssign:
1022 case BinaryOperator::DivAssign:
1023 result = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1024 if (result.isNull())
1025 return true;
Steve Naroff35d85152007-05-07 00:24:15 +00001026 result = CheckAssignmentOperands(lhs, rhs, TokLoc, result);
Steve Naroff218bc2b2007-05-04 21:54:46 +00001027 break;
1028 case BinaryOperator::RemAssign:
1029 result = CheckRemainderOperands(lhs, rhs, TokLoc);
1030 if (result.isNull())
1031 return true;
Steve Naroff35d85152007-05-07 00:24:15 +00001032 result = CheckAssignmentOperands(lhs, rhs, TokLoc, result);
Steve Naroff218bc2b2007-05-04 21:54:46 +00001033 break;
1034 case BinaryOperator::AddAssign:
1035 result = CheckAdditionOperands(lhs, rhs, TokLoc);
1036 if (result.isNull())
1037 return true;
Steve Naroff35d85152007-05-07 00:24:15 +00001038 result = CheckAssignmentOperands(lhs, rhs, TokLoc, result);
Steve Naroff218bc2b2007-05-04 21:54:46 +00001039 break;
1040 case BinaryOperator::SubAssign:
1041 result = CheckSubtractionOperands(lhs, rhs, TokLoc);
1042 if (result.isNull())
1043 return true;
Steve Naroff35d85152007-05-07 00:24:15 +00001044 result = CheckAssignmentOperands(lhs, rhs, TokLoc, result);
Steve Naroff218bc2b2007-05-04 21:54:46 +00001045 break;
1046 case BinaryOperator::ShlAssign:
1047 case BinaryOperator::ShrAssign:
1048 result = CheckShiftOperands(lhs, rhs, TokLoc);
1049 if (result.isNull())
1050 return true;
Steve Naroff35d85152007-05-07 00:24:15 +00001051 result = CheckAssignmentOperands(lhs, rhs, TokLoc, result);
Steve Naroff218bc2b2007-05-04 21:54:46 +00001052 break;
1053 case BinaryOperator::AndAssign:
1054 case BinaryOperator::XorAssign:
1055 case BinaryOperator::OrAssign:
1056 result = CheckBitwiseOperands(lhs, rhs, TokLoc);
1057 if (result.isNull())
1058 return true;
Steve Naroff35d85152007-05-07 00:24:15 +00001059 result = CheckAssignmentOperands(lhs, rhs, TokLoc, result);
Steve Naroff218bc2b2007-05-04 21:54:46 +00001060 break;
1061 case BinaryOperator::Comma:
1062 result = CheckCommaOperands(lhs, rhs, TokLoc);
1063 break;
1064 }
1065 if (result.isNull())
1066 return true;
1067 return new BinaryOperator(lhs, rhs, Opc, result);
1068}
1069
Steve Naroff35d85152007-05-07 00:24:15 +00001070// Unary Operators. 'Tok' is the token for the operator.
1071Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1072 ExprTy *Input) {
1073 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1074 QualType resultType;
1075 switch (Opc) {
1076 default:
1077 assert(0 && "Unimplemented unary expr!");
1078 case UnaryOperator::PreInc:
1079 case UnaryOperator::PreDec:
1080 resultType = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
1081 break;
1082 case UnaryOperator::AddrOf:
1083 resultType = CheckAddressOfOperand((Expr *)Input, OpLoc);
1084 break;
1085 case UnaryOperator::Deref:
1086 resultType = CheckIndirectionOperand((Expr *)Input, OpLoc);
1087 break;
1088 case UnaryOperator::Plus:
1089 case UnaryOperator::Minus:
1090 resultType = UsualUnaryConversion(((Expr *)Input)->getType());
1091 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
Chris Lattnerc04bd6a2007-05-16 18:09:54 +00001092 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1093 resultType.getAsString());
Steve Naroff35d85152007-05-07 00:24:15 +00001094 break;
1095 case UnaryOperator::Not: // bitwise complement
1096 resultType = UsualUnaryConversion(((Expr *)Input)->getType());
1097 if (!resultType->isIntegerType()) // C99 6.5.3.3p1
Chris Lattnerc04bd6a2007-05-16 18:09:54 +00001098 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1099 resultType.getAsString());
Steve Naroff35d85152007-05-07 00:24:15 +00001100 break;
1101 case UnaryOperator::LNot: // logical negation
1102 resultType = UsualUnaryConversion(((Expr *)Input)->getType());
1103 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattnerc04bd6a2007-05-16 18:09:54 +00001104 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1105 resultType.getAsString());
Steve Naroff35d85152007-05-07 00:24:15 +00001106 break;
1107 case UnaryOperator::SizeOf:
Steve Naroff043d45d2007-05-15 02:32:35 +00001108 resultType = CheckSizeOfAlignOfOperand(((Expr *)Input)->getType(), OpLoc,
1109 true);
1110 break;
Steve Naroff35d85152007-05-07 00:24:15 +00001111 case UnaryOperator::AlignOf:
Steve Naroff043d45d2007-05-15 02:32:35 +00001112 resultType = CheckSizeOfAlignOfOperand(((Expr *)Input)->getType(), OpLoc,
1113 false);
1114 break;
Steve Naroff35d85152007-05-07 00:24:15 +00001115 }
1116 if (resultType.isNull())
1117 return true;
1118 return new UnaryOperator((Expr *)Input, Opc, resultType);
1119}