blob: 615b2433348fec538314b9a93fc6a8e68d15beb9 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/Expr.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/LiteralSupport.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/SmallString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
28/// ParseStringLiteral - The specified tokens were lexed as pasted string
29/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
Chris Lattnerd2177732007-07-20 16:59:19 +000035Sema::ParseStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +000036 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
45
46 // FIXME: handle wchar_t
47 QualType t = Context.getPointerType(Context.CharTy);
48
49 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
50 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
51 Literal.AnyWide, t, StringToks[0].getLocation(),
52 StringToks[NumStringToks-1].getLocation());
53}
54
55
56/// ParseIdentifierExpr - The parser read an identifier in expression context,
57/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
58/// identifier is used in an function call context.
59Sema::ExprResult Sema::ParseIdentifierExpr(Scope *S, SourceLocation Loc,
60 IdentifierInfo &II,
61 bool HasTrailingLParen) {
62 // Could be enum-constant or decl.
63 Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
64 if (D == 0) {
65 // Otherwise, this could be an implicitly declared function reference (legal
66 // in C90, extension in C99).
67 if (HasTrailingLParen &&
68 // Not in C++.
69 !getLangOptions().CPlusPlus)
70 D = ImplicitlyDefineFunction(Loc, II, S);
71 else {
72 // If this name wasn't predeclared and if this is not a function call,
73 // diagnose the problem.
74 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
75 }
76 }
Steve Naroffe1223f72007-08-28 03:03:08 +000077 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroff53a32342007-08-28 18:45:29 +000078 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +000079 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +000080 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +000081 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +000082 }
Reid Spencer5f016e22007-07-11 17:01:13 +000083 if (isa<TypedefDecl>(D))
84 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
85
86 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +000087 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +000088}
89
Anders Carlsson22742662007-07-21 05:21:51 +000090Sema::ExprResult Sema::ParsePreDefinedExpr(SourceLocation Loc,
91 tok::TokenKind Kind) {
92 PreDefinedExpr::IdentType IT;
93
Reid Spencer5f016e22007-07-11 17:01:13 +000094 switch (Kind) {
95 default:
96 assert(0 && "Unknown simple primary expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +000097 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
Anders Carlsson22742662007-07-21 05:21:51 +000098 IT = PreDefinedExpr::Func;
99 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000101 IT = PreDefinedExpr::Function;
102 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000104 IT = PreDefinedExpr::PrettyFunction;
105 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 }
Anders Carlsson22742662007-07-21 05:21:51 +0000107
108 // Pre-defined identifiers are always of type char *.
109 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000110}
111
Chris Lattnerd2177732007-07-20 16:59:19 +0000112Sema::ExprResult Sema::ParseCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 llvm::SmallString<16> CharBuffer;
114 CharBuffer.resize(Tok.getLength());
115 const char *ThisTokBegin = &CharBuffer[0];
116 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
117
118 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
119 Tok.getLocation(), PP);
120 if (Literal.hadError())
121 return ExprResult(true);
122 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
123 Tok.getLocation());
124}
125
Chris Lattnerd2177732007-07-20 16:59:19 +0000126Action::ExprResult Sema::ParseNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 // fast path for a single digit (which is quite common). A single digit
128 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
129 if (Tok.getLength() == 1) {
130 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
131
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000132 unsigned IntSize = Context.getTypeSize(Context.IntTy, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000133 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
134 Context.IntTy,
135 Tok.getLocation()));
136 }
137 llvm::SmallString<512> IntegerBuffer;
138 IntegerBuffer.resize(Tok.getLength());
139 const char *ThisTokBegin = &IntegerBuffer[0];
140
141 // Get the spelling of the token, which eliminates trigraphs, etc.
142 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
143 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
144 Tok.getLocation(), PP);
145 if (Literal.hadError)
146 return ExprResult(true);
147
Chris Lattner5d661452007-08-26 03:42:43 +0000148 Expr *Res;
149
150 if (Literal.isFloatingLiteral()) {
151 // FIXME: handle float values > 32 (including compute the real type...).
152 QualType Ty = Literal.isFloat ? Context.FloatTy : Context.DoubleTy;
153 Res = new FloatingLiteral(Literal.GetFloatValue(), Ty, Tok.getLocation());
154 } else if (!Literal.isIntegerLiteral()) {
155 return ExprResult(true);
156 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 QualType t;
158
Neil Boothb9449512007-08-29 22:00:19 +0000159 // long long is a C99 feature.
160 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000161 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000162 Diag(Tok.getLocation(), diag::ext_longlong);
163
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 // Get the value in the widest-possible width.
165 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
166
167 if (Literal.GetIntegerValue(ResultVal)) {
168 // If this value didn't fit into uintmax_t, warn and force to ull.
169 Diag(Tok.getLocation(), diag::warn_integer_too_large);
170 t = Context.UnsignedLongLongTy;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000171 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 ResultVal.getBitWidth() && "long long is not intmax_t?");
173 } else {
174 // If this value fits into a ULL, try to figure out what else it fits into
175 // according to the rules of C99 6.4.4.1p5.
176
177 // Octal, Hexadecimal, and integers with a U suffix are allowed to
178 // be an unsigned int.
179 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
180
181 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner97c51562007-08-23 21:58:08 +0000182 if (!Literal.isLong && !Literal.isLongLong) {
183 // Are int/unsigned possibilities?
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000184 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 // Does it fit in a unsigned int?
186 if (ResultVal.isIntN(IntSize)) {
187 // Does it fit in a signed int?
188 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
189 t = Context.IntTy;
190 else if (AllowUnsigned)
191 t = Context.UnsignedIntTy;
192 }
193
194 if (!t.isNull())
195 ResultVal.trunc(IntSize);
196 }
197
198 // Are long/unsigned long possibilities?
199 if (t.isNull() && !Literal.isLongLong) {
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000200 unsigned LongSize = Context.getTypeSize(Context.LongTy,
201 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000202
203 // Does it fit in a unsigned long?
204 if (ResultVal.isIntN(LongSize)) {
205 // Does it fit in a signed long?
206 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
207 t = Context.LongTy;
208 else if (AllowUnsigned)
209 t = Context.UnsignedLongTy;
210 }
211 if (!t.isNull())
212 ResultVal.trunc(LongSize);
213 }
214
215 // Finally, check long long if needed.
216 if (t.isNull()) {
217 unsigned LongLongSize =
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000218 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000219
220 // Does it fit in a unsigned long long?
221 if (ResultVal.isIntN(LongLongSize)) {
222 // Does it fit in a signed long long?
223 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
224 t = Context.LongLongTy;
225 else if (AllowUnsigned)
226 t = Context.UnsignedLongLongTy;
227 }
228 }
229
230 // If we still couldn't decide a type, we probably have something that
231 // does not fit in a signed long long, but has no U suffix.
232 if (t.isNull()) {
233 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
234 t = Context.UnsignedLongLongTy;
235 }
236 }
237
Chris Lattner5d661452007-08-26 03:42:43 +0000238 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 }
Chris Lattner5d661452007-08-26 03:42:43 +0000240
241 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
242 if (Literal.isImaginary)
243 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
244
245 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000246}
247
248Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
249 ExprTy *Val) {
250 Expr *e = (Expr *)Val;
251 assert((e != 0) && "ParseParenExpr() missing expr");
252 return new ParenExpr(L, R, e);
253}
254
255/// The UsualUnaryConversions() function is *not* called by this routine.
256/// See C99 6.3.2.1p[2-4] for more details.
257QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
258 SourceLocation OpLoc, bool isSizeof) {
259 // C99 6.5.3.4p1:
260 if (isa<FunctionType>(exprType) && isSizeof)
261 // alignof(function) is allowed.
262 Diag(OpLoc, diag::ext_sizeof_function_type);
263 else if (exprType->isVoidType())
264 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
265 else if (exprType->isIncompleteType()) {
266 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
267 diag::err_alignof_incomplete_type,
268 exprType.getAsString());
269 return QualType(); // error
270 }
271 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
272 return Context.getSizeType();
273}
274
275Action::ExprResult Sema::
276ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
277 SourceLocation LPLoc, TypeTy *Ty,
278 SourceLocation RPLoc) {
279 // If error parsing type, ignore.
280 if (Ty == 0) return true;
281
282 // Verify that this is a valid expression.
283 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
284
285 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
286
287 if (resultType.isNull())
288 return true;
289 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
290}
291
Chris Lattner5d794252007-08-24 21:41:10 +0000292QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000293 DefaultFunctionArrayConversion(V);
294
Chris Lattnercc26ed72007-08-26 05:39:26 +0000295 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000296 if (const ComplexType *CT = V->getType()->getAsComplexType())
297 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000298
299 // Otherwise they pass through real integer and floating point types here.
300 if (V->getType()->isArithmeticType())
301 return V->getType();
302
303 // Reject anything else.
304 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
305 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000306}
307
308
Reid Spencer5f016e22007-07-11 17:01:13 +0000309
310Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
311 tok::TokenKind Kind,
312 ExprTy *Input) {
313 UnaryOperator::Opcode Opc;
314 switch (Kind) {
315 default: assert(0 && "Unknown unary op!");
316 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
317 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
318 }
319 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
320 if (result.isNull())
321 return true;
322 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
323}
324
325Action::ExprResult Sema::
326ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
327 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000328 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000329
330 // Perform default conversions.
331 DefaultFunctionArrayConversion(LHSExp);
332 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000333
Chris Lattner12d9ff62007-07-16 00:14:47 +0000334 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000335
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000337 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 // in the subscript position. As a result, we need to derive the array base
339 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000340 Expr *BaseExpr, *IndexExpr;
341 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000342 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000343 BaseExpr = LHSExp;
344 IndexExpr = RHSExp;
345 // FIXME: need to deal with const...
346 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000347 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000348 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000349 BaseExpr = RHSExp;
350 IndexExpr = LHSExp;
351 // FIXME: need to deal with const...
352 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000353 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
354 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000355 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000356
357 // Component access limited to variables (reject vec4.rg[1]).
358 if (!isa<DeclRefExpr>(BaseExpr))
359 return Diag(LLoc, diag::err_ocuvector_component_access,
360 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000361 // FIXME: need to deal with const...
362 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000364 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
365 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 }
367 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000368 if (!IndexExpr->getType()->isIntegerType())
369 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
370 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000371
Chris Lattner12d9ff62007-07-16 00:14:47 +0000372 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
373 // the following check catches trying to index a pointer to a function (e.g.
374 // void (*)(int)). Functions are not objects in C99.
375 if (!ResultType->isObjectType())
376 return Diag(BaseExpr->getLocStart(),
377 diag::err_typecheck_subscript_not_object,
378 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
379
380 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000381}
382
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000383QualType Sema::
384CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
385 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnerc8629632007-07-31 19:29:30 +0000386 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000387
388 // The vector accessor can't exceed the number of elements.
389 const char *compStr = CompName.getName();
390 if (strlen(compStr) > vecType->getNumElements()) {
391 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
392 baseType.getAsString(), SourceRange(CompLoc));
393 return QualType();
394 }
395 // The component names must come from the same set.
Chris Lattner88dca042007-08-02 22:33:49 +0000396 if (vecType->getPointAccessorIdx(*compStr) != -1) {
397 do
398 compStr++;
399 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
400 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
401 do
402 compStr++;
403 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
404 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
405 do
406 compStr++;
407 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
408 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000409
410 if (*compStr) {
411 // We didn't get to the end of the string. This means the component names
412 // didn't come from the same set *or* we encountered an illegal name.
413 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
414 std::string(compStr,compStr+1), SourceRange(CompLoc));
415 return QualType();
416 }
417 // Each component accessor can't exceed the vector type.
418 compStr = CompName.getName();
419 while (*compStr) {
420 if (vecType->isAccessorWithinNumElements(*compStr))
421 compStr++;
422 else
423 break;
424 }
425 if (*compStr) {
426 // We didn't get to the end of the string. This means a component accessor
427 // exceeds the number of elements in the vector.
428 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
429 baseType.getAsString(), SourceRange(CompLoc));
430 return QualType();
431 }
432 // The component accessor looks fine - now we need to compute the actual type.
433 // The vector type is implied by the component accessor. For example,
434 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
435 unsigned CompSize = strlen(CompName.getName());
436 if (CompSize == 1)
437 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000438
439 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
440 // Now look up the TypeDefDecl from the vector type. Without this,
441 // diagostics look bad. We want OCU vector types to appear built-in.
442 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
443 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
444 return Context.getTypedefType(OCUVectorDecls[i]);
445 }
446 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000447}
448
Reid Spencer5f016e22007-07-11 17:01:13 +0000449Action::ExprResult Sema::
450ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
451 tok::TokenKind OpKind, SourceLocation MemberLoc,
452 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000453 Expr *BaseExpr = static_cast<Expr *>(Base);
454 assert(BaseExpr && "no record expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000455
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000456 QualType BaseType = BaseExpr->getType();
457 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000458
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000460 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000461 BaseType = PT->getPointeeType();
462 else
463 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
464 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000466 // The base type is either a record or an OCUVectorType.
Chris Lattnerc8629632007-07-31 19:29:30 +0000467 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000468 RecordDecl *RDecl = RTy->getDecl();
469 if (RTy->isIncompleteType())
470 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
471 BaseExpr->getSourceRange());
472 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000473 FieldDecl *MemberDecl = RDecl->getMember(&Member);
474 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000475 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
476 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000477 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
478 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff608e0ee2007-08-03 22:40:33 +0000479 // Component access limited to variables (reject vec4.rg.g).
480 if (!isa<DeclRefExpr>(BaseExpr))
481 return Diag(OpLoc, diag::err_ocuvector_component_access,
482 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000483 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
484 if (ret.isNull())
485 return true;
Chris Lattner6481a572007-08-03 17:31:20 +0000486 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000487 } else
488 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
489 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000490}
491
492/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
493/// This provides the location of the left/right parens and a list of comma
494/// locations.
495Action::ExprResult Sema::
Chris Lattner74c469f2007-07-21 03:03:59 +0000496ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
497 ExprTy **args, unsigned NumArgsInCall,
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000499 Expr *Fn = static_cast<Expr *>(fn);
500 Expr **Args = reinterpret_cast<Expr**>(args);
501 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000502
Chris Lattner74c469f2007-07-21 03:03:59 +0000503 UsualUnaryConversions(Fn);
504 QualType funcType = Fn->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000505
506 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
507 // type pointer to function".
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000508 const PointerType *PT = funcType->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000510 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
511 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000512
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000513 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 if (funcT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000515 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
516 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000517
518 // If a prototype isn't declared, the parser implicitly defines a func decl
519 QualType resultType = funcT->getResultType();
520
521 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
522 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
523 // assignment, to the types of the corresponding parameter, ...
524
525 unsigned NumArgsInProto = proto->getNumArgs();
526 unsigned NumArgsToCheck = NumArgsInCall;
527
528 if (NumArgsInCall < NumArgsInProto)
529 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
Chris Lattner74c469f2007-07-21 03:03:59 +0000530 Fn->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000531 else if (NumArgsInCall > NumArgsInProto) {
532 if (!proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000533 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000534 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000535 SourceRange(Args[NumArgsInProto]->getLocStart(),
536 Args[NumArgsInCall-1]->getLocEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 }
538 NumArgsToCheck = NumArgsInProto;
539 }
540 // Continue to check argument types (even if we have too few/many args).
541 for (unsigned i = 0; i < NumArgsToCheck; i++) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000542 Expr *argExpr = Args[i];
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 assert(argExpr && "ParseCallExpr(): missing argument expression");
544
545 QualType lhsType = proto->getArgType(i);
546 QualType rhsType = argExpr->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000547
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000548 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnerc8629632007-07-31 19:29:30 +0000549 if (const ArrayType *ary = lhsType->getAsArrayType())
Steve Naroff700204c2007-07-24 21:46:40 +0000550 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000551 else if (lhsType->isFunctionType())
Steve Naroff700204c2007-07-24 21:46:40 +0000552 lhsType = Context.getPointerType(lhsType);
553
Steve Naroff90045e82007-07-13 23:32:42 +0000554 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
555 argExpr);
Steve Narofff1120de2007-08-24 22:33:52 +0000556 if (Args[i] != argExpr) // The expression was converted.
557 Args[i] = argExpr; // Make sure we store the converted expression.
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 SourceLocation l = argExpr->getLocStart();
559
560 // decode the result (notice that AST's are still created for extensions).
561 switch (result) {
562 case Compatible:
563 break;
564 case PointerFromInt:
565 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +0000566 if (!argExpr->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 Diag(l, diag::ext_typecheck_passing_pointer_int,
568 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000569 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 }
571 break;
572 case IntFromPointer:
573 Diag(l, diag::ext_typecheck_passing_pointer_int,
574 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000575 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 break;
577 case IncompatiblePointer:
578 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
579 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000580 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 break;
582 case CompatiblePointerDiscardsQualifiers:
583 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
584 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000585 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 break;
587 case Incompatible:
588 return Diag(l, diag::err_typecheck_passing_incompatible,
589 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000590 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 }
592 }
Steve Naroffb291ab62007-08-28 23:30:39 +0000593 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
594 // Promote the arguments (C99 6.5.2.2p7).
595 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
596 Expr *argExpr = Args[i];
597 assert(argExpr && "ParseCallExpr(): missing argument expression");
598
599 DefaultArgumentPromotion(argExpr);
600 if (Args[i] != argExpr) // The expression was converted.
601 Args[i] = argExpr; // Make sure we store the converted expression.
602 }
603 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
604 // Even if the types checked, bail if the number of arguments don't match.
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 return true;
Steve Naroffb291ab62007-08-28 23:30:39 +0000606 }
607 } else if (isa<FunctionTypeNoProto>(funcT)) {
608 // Promote the arguments (C99 6.5.2.2p6).
609 for (unsigned i = 0; i < NumArgsInCall; i++) {
610 Expr *argExpr = Args[i];
611 assert(argExpr && "ParseCallExpr(): missing argument expression");
612
613 DefaultArgumentPromotion(argExpr);
614 if (Args[i] != argExpr) // The expression was converted.
615 Args[i] = argExpr; // Make sure we store the converted expression.
616 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000617 }
Chris Lattner59907c42007-08-10 20:18:51 +0000618 // Do special checking on direct calls to functions.
619 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
620 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
621 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000622 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
623 NumArgsInCall))
Anders Carlsson71993dd2007-08-17 05:31:46 +0000624 return true;
Chris Lattner59907c42007-08-10 20:18:51 +0000625
Chris Lattner74c469f2007-07-21 03:03:59 +0000626 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000627}
628
629Action::ExprResult Sema::
Steve Naroff4aa88f82007-07-19 01:06:55 +0000630ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000631 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff4aa88f82007-07-19 01:06:55 +0000632 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
633 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000634 // FIXME: put back this assert when initializers are worked out.
635 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
636 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000637
638 // FIXME: add semantic analysis (C99 6.5.2.5).
Steve Naroffaff1edd2007-07-19 21:32:11 +0000639 return new CompoundLiteralExpr(literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000640}
641
642Action::ExprResult Sema::
643ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
644 SourceLocation RParenLoc) {
645 // FIXME: add semantic analysis (C99 6.7.8). This involves
646 // knowledge of the object being intialized. As a result, the code for
647 // doing the semantic analysis will likely be located elsewhere (i.e. in
648 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
649 return false; // FIXME instantiate an InitListExpr.
650}
651
652Action::ExprResult Sema::
Reid Spencer5f016e22007-07-11 17:01:13 +0000653ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
654 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff16beff82007-07-16 23:25:18 +0000655 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
656
657 Expr *castExpr = static_cast<Expr*>(Op);
658 QualType castType = QualType::getFromOpaquePtr(Ty);
659
Chris Lattner75af4802007-07-18 16:00:06 +0000660 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
661 // type needs to be scalar.
662 if (!castType->isScalarType() && !castType->isVoidType()) {
Steve Naroff16beff82007-07-16 23:25:18 +0000663 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
664 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
665 }
666 if (!castExpr->getType()->isScalarType()) {
667 return Diag(castExpr->getLocStart(),
668 diag::err_typecheck_expect_scalar_operand,
669 castExpr->getType().getAsString(), castExpr->getSourceRange());
670 }
671 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000672}
673
674inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000675 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000676 UsualUnaryConversions(cond);
677 UsualUnaryConversions(lex);
678 UsualUnaryConversions(rex);
679 QualType condT = cond->getType();
680 QualType lexT = lex->getType();
681 QualType rexT = rex->getType();
682
Reid Spencer5f016e22007-07-11 17:01:13 +0000683 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000684 if (!condT->isScalarType()) { // C99 6.5.15p2
685 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
686 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000687 return QualType();
688 }
689 // now check the two expressions.
Steve Naroffa4332e22007-07-17 00:58:39 +0000690 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
691 UsualArithmeticConversions(lex, rex);
692 return lex->getType();
693 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000694 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
695 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
696
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000697 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000698 return lexT;
699
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000701 lexT.getAsString(), rexT.getAsString(),
702 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 return QualType();
704 }
705 }
Chris Lattner590b6642007-07-15 23:26:56 +0000706 // C99 6.5.15p3
707 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
Steve Naroff49b45262007-07-13 16:58:59 +0000708 return lexT;
Chris Lattner590b6642007-07-15 23:26:56 +0000709 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
Steve Naroff49b45262007-07-13 16:58:59 +0000710 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000711
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000712 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
713 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
714 // get the "pointed to" types
715 QualType lhptee = LHSPT->getPointeeType();
716 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000717
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000718 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
719 if (lhptee->isVoidType() &&
720 (rhptee->isObjectType() || rhptee->isIncompleteType()))
721 return lexT;
722 if (rhptee->isVoidType() &&
723 (lhptee->isObjectType() || lhptee->isIncompleteType()))
724 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000725
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000726 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
727 rhptee.getUnqualifiedType())) {
728 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
729 lexT.getAsString(), rexT.getAsString(),
730 lex->getSourceRange(), rex->getSourceRange());
731 return lexT; // FIXME: this is an _ext - is this return o.k?
732 }
733 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000734 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
735 // differently qualified versions of compatible types, the result type is
736 // a pointer to an appropriately qualified version of the *composite*
737 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000738 return lexT; // FIXME: Need to return the composite type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 }
740 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000741
Steve Naroff49b45262007-07-13 16:58:59 +0000742 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
743 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000744
745 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000746 lexT.getAsString(), rexT.getAsString(),
747 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 return QualType();
749}
750
751/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
752/// in the case of a the GNU conditional expr extension.
753Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
754 SourceLocation ColonLoc,
755 ExprTy *Cond, ExprTy *LHS,
756 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000757 Expr *CondExpr = (Expr *) Cond;
758 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
759 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
760 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 if (result.isNull())
762 return true;
Chris Lattner26824902007-07-16 21:39:03 +0000763 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000764}
765
Steve Narofffa2eaab2007-07-15 02:02:06 +0000766// promoteExprToType - a helper function to ensure we create exactly one
767// ImplicitCastExpr. As a convenience (to the caller), we return the type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000768static void promoteExprToType(Expr *&expr, QualType type) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000769 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
770 impCast->setType(type);
771 else
772 expr = new ImplicitCastExpr(type, expr);
Steve Naroffa4332e22007-07-17 00:58:39 +0000773 return;
Steve Narofffa2eaab2007-07-15 02:02:06 +0000774}
775
Steve Naroffb291ab62007-08-28 23:30:39 +0000776/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
777/// do not have a prototype. Integer promotions are performed on each
778/// argument, and arguments that have type float are promoted to double.
779void Sema::DefaultArgumentPromotion(Expr *&expr) {
780 QualType t = expr->getType();
781 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
782
783 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
784 promoteExprToType(expr, Context.IntTy);
785 if (t == Context.FloatTy)
786 promoteExprToType(expr, Context.DoubleTy);
787}
788
Steve Narofffa2eaab2007-07-15 02:02:06 +0000789/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000790void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000791 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000792 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000793
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000794 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000795 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
796 t = e->getType();
797 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000798 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000799 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnerc8629632007-07-31 19:29:30 +0000800 else if (const ArrayType *ary = t->getAsArrayType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000801 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000802}
803
804/// UsualUnaryConversion - Performs various conversions that are common to most
805/// operators (C99 6.3). The conversions of array and function types are
806/// sometimes surpressed. For example, the array->pointer conversion doesn't
807/// apply if the array is an argument to the sizeof or address (&) operators.
808/// In these instances, this routine should *not* be called.
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000809void Sema::UsualUnaryConversions(Expr *&expr) {
Steve Naroff49b45262007-07-13 16:58:59 +0000810 QualType t = expr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 assert(!t.isNull() && "UsualUnaryConversions - missing type");
812
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000813 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000814 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
815 t = expr->getType();
816 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000817 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000818 promoteExprToType(expr, Context.IntTy);
819 else
820 DefaultFunctionArrayConversion(expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000821}
822
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000823/// UsualArithmeticConversions - Performs various conversions that are common to
Reid Spencer5f016e22007-07-11 17:01:13 +0000824/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
825/// routine returns the first non-arithmetic type found. The client is
826/// responsible for emitting appropriate error diagnostics.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000827QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
828 bool isCompAssign) {
Steve Naroff8702a0f2007-08-25 19:54:59 +0000829 if (!isCompAssign) {
830 UsualUnaryConversions(lhsExpr);
831 UsualUnaryConversions(rhsExpr);
832 }
Steve Naroff3e5e5562007-07-16 22:23:01 +0000833 QualType lhs = lhsExpr->getType();
834 QualType rhs = rhsExpr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000835
836 // If both types are identical, no conversion is needed.
837 if (lhs == rhs)
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000838 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000839
840 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
841 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000842 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000843 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000844
845 // At this point, we have two different arithmetic types.
846
847 // Handle complex types first (C99 6.3.1.8p1).
848 if (lhs->isComplexType() || rhs->isComplexType()) {
849 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000850 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000851 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
852 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000853 }
854 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000855 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
856 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000857 }
Steve Narofff1448a02007-08-27 01:27:54 +0000858 // This handles complex/complex, complex/float, or float/complex.
859 // When both operands are complex, the shorter operand is converted to the
860 // type of the longer, and that is the type of the result. This corresponds
861 // to what is done when combining two real floating-point operands.
862 // The fun begins when size promotion occur across type domains.
863 // From H&S 6.3.4: When one operand is complex and the other is a real
864 // floating-point type, the less precise type is converted, within it's
865 // real or complex domain, to the precision of the other type. For example,
866 // when combining a "long double" with a "double _Complex", the
867 // "double _Complex" is promoted to "long double _Complex".
Steve Narofffb0d4962007-08-27 15:30:22 +0000868 int result = Context.compareFloatingType(lhs, rhs);
869
870 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff55fe4552007-08-27 21:32:55 +0000871 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
872 if (!isCompAssign)
873 promoteExprToType(rhsExpr, rhs);
874 } else if (result < 0) { // The right side is bigger, convert lhs.
875 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
876 if (!isCompAssign)
877 promoteExprToType(lhsExpr, lhs);
878 }
879 // At this point, lhs and rhs have the same rank/size. Now, make sure the
880 // domains match. This is a requirement for our implementation, C99
881 // does not require this promotion.
882 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
883 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff29960362007-08-27 21:43:43 +0000884 if (!isCompAssign)
885 promoteExprToType(lhsExpr, rhs);
886 return rhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000887 } else { // handle "_Complex double, double".
Steve Naroff29960362007-08-27 21:43:43 +0000888 if (!isCompAssign)
889 promoteExprToType(rhsExpr, lhs);
890 return lhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000891 }
Steve Naroffa4332e22007-07-17 00:58:39 +0000892 }
Steve Naroff29960362007-08-27 21:43:43 +0000893 return lhs; // The domain/size match exactly.
Reid Spencer5f016e22007-07-11 17:01:13 +0000894 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 // Now handle "real" floating types (i.e. float, double, long double).
896 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
897 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000898 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000899 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
900 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000901 }
902 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000903 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
904 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000905 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000906 // We have two real floating types, float/complex combos were handled above.
907 // Convert the smaller operand to the bigger result.
Steve Narofffb0d4962007-08-27 15:30:22 +0000908 int result = Context.compareFloatingType(lhs, rhs);
909
910 if (result > 0) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000911 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
912 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000913 }
Steve Narofffb0d4962007-08-27 15:30:22 +0000914 if (result < 0) { // convert the lhs
915 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
916 return rhs;
917 }
918 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Reid Spencer5f016e22007-07-11 17:01:13 +0000919 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000920 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +0000921 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000922 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
923 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000924 }
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000925 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
926 return rhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000927}
928
929// CheckPointerTypesForAssignment - This is a very tricky routine (despite
930// being closely modeled after the C99 spec:-). The odd characteristic of this
931// routine is it effectively iqnores the qualifiers on the top level pointee.
932// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
933// FIXME: add a couple examples in this comment.
934Sema::AssignmentCheckResult
935Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
936 QualType lhptee, rhptee;
937
938 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000939 lhptee = lhsType->getAsPointerType()->getPointeeType();
940 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000941
942 // make sure we operate on the canonical type
943 lhptee = lhptee.getCanonicalType();
944 rhptee = rhptee.getCanonicalType();
945
946 AssignmentCheckResult r = Compatible;
947
948 // C99 6.5.16.1p1: This following citation is common to constraints
949 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
950 // qualifiers of the type *pointed to* by the right;
951 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
952 rhptee.getQualifiers())
953 r = CompatiblePointerDiscardsQualifiers;
954
955 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
956 // incomplete type and the other is a pointer to a qualified or unqualified
957 // version of void...
958 if (lhptee.getUnqualifiedType()->isVoidType() &&
959 (rhptee->isObjectType() || rhptee->isIncompleteType()))
960 ;
961 else if (rhptee.getUnqualifiedType()->isVoidType() &&
962 (lhptee->isObjectType() || lhptee->isIncompleteType()))
963 ;
964 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
965 // unqualified versions of compatible types, ...
966 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
967 rhptee.getUnqualifiedType()))
968 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
969 return r;
970}
971
972/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
973/// has code to accommodate several GCC extensions when type checking
974/// pointers. Here are some objectionable examples that GCC considers warnings:
975///
976/// int a, *pint;
977/// short *pshort;
978/// struct foo *pfoo;
979///
980/// pint = pshort; // warning: assignment from incompatible pointer type
981/// a = pint; // warning: assignment makes integer from pointer without a cast
982/// pint = a; // warning: assignment makes pointer from integer without a cast
983/// pint = pfoo; // warning: assignment from incompatible pointer type
984///
985/// As a result, the code for dealing with pointers is more complex than the
986/// C99 spec dictates.
987/// Note: the warning above turn into errors when -pedantic-errors is enabled.
988///
989Sema::AssignmentCheckResult
990Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroff700204c2007-07-24 21:46:40 +0000991 if (lhsType == rhsType) // common case, fast path...
992 return Compatible;
993
Reid Spencer5f016e22007-07-11 17:01:13 +0000994 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
995 if (lhsType->isVectorType() || rhsType->isVectorType()) {
996 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
997 return Incompatible;
998 }
999 return Compatible;
1000 } else if (lhsType->isPointerType()) {
1001 if (rhsType->isIntegerType())
1002 return PointerFromInt;
1003
1004 if (rhsType->isPointerType())
1005 return CheckPointerTypesForAssignment(lhsType, rhsType);
1006 } else if (rhsType->isPointerType()) {
1007 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1008 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1009 return IntFromPointer;
1010
1011 if (lhsType->isPointerType())
1012 return CheckPointerTypesForAssignment(lhsType, rhsType);
1013 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1014 if (Type::tagTypesAreCompatible(lhsType, rhsType))
1015 return Compatible;
1016 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1017 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
1018 return Compatible;
1019 }
1020 return Incompatible;
1021}
1022
Steve Naroff90045e82007-07-13 23:32:42 +00001023Sema::AssignmentCheckResult
1024Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1025 // This check seems unnatural, however it is necessary to insure the proper
1026 // conversion of functions/arrays. If the conversion were done for all
1027 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
1028 // expressions that surpress this implicit conversion (&, sizeof).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001029 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001030
1031 Sema::AssignmentCheckResult result;
Steve Naroff90045e82007-07-13 23:32:42 +00001032
Steve Narofff1120de2007-08-24 22:33:52 +00001033 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1034
1035 // C99 6.5.16.1p2: The value of the right operand is converted to the
1036 // type of the assignment expression.
1037 if (rExpr->getType() != lhsType)
1038 promoteExprToType(rExpr, lhsType);
1039 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001040}
1041
1042Sema::AssignmentCheckResult
1043Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1044 return CheckAssignmentConstraints(lhsType, rhsType);
1045}
1046
Steve Naroff49b45262007-07-13 16:58:59 +00001047inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001048 Diag(loc, diag::err_typecheck_invalid_operands,
1049 lex->getType().getAsString(), rex->getType().getAsString(),
1050 lex->getSourceRange(), rex->getSourceRange());
1051}
1052
Steve Naroff49b45262007-07-13 16:58:59 +00001053inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1054 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 QualType lhsType = lex->getType(), rhsType = rex->getType();
1056
1057 // make sure the vector types are identical.
1058 if (lhsType == rhsType)
1059 return lhsType;
1060 // You cannot convert between vector values of different size.
1061 Diag(loc, diag::err_typecheck_vector_not_convertable,
1062 lex->getType().getAsString(), rex->getType().getAsString(),
1063 lex->getSourceRange(), rex->getSourceRange());
1064 return QualType();
1065}
1066
1067inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001068 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001069{
Steve Naroff90045e82007-07-13 23:32:42 +00001070 QualType lhsType = lex->getType(), rhsType = rex->getType();
1071
1072 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001074
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001075 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001076
Steve Naroffa4332e22007-07-17 00:58:39 +00001077 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001078 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001079 InvalidOperands(loc, lex, rex);
1080 return QualType();
1081}
1082
1083inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001084 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001085{
Steve Naroff90045e82007-07-13 23:32:42 +00001086 QualType lhsType = lex->getType(), rhsType = rex->getType();
1087
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001088 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001089
Steve Naroffa4332e22007-07-17 00:58:39 +00001090 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001091 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 InvalidOperands(loc, lex, rex);
1093 return QualType();
1094}
1095
1096inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001097 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001098{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001099 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001100 return CheckVectorOperands(loc, lex, rex);
1101
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001102 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Steve Naroff3e5e5562007-07-16 22:23:01 +00001103
Reid Spencer5f016e22007-07-11 17:01:13 +00001104 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001105 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001106 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001107
Steve Naroffa4332e22007-07-17 00:58:39 +00001108 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1109 return lex->getType();
1110 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1111 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 InvalidOperands(loc, lex, rex);
1113 return QualType();
1114}
1115
1116inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001117 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001118{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001119 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001121
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001122 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001123
1124 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001125 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001126 return compType;
Steve Naroff3e5e5562007-07-16 22:23:01 +00001127
1128 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001129 return compType;
Steve Naroff3e5e5562007-07-16 22:23:01 +00001130 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
Chris Lattner8b9023b2007-07-13 03:05:23 +00001131 return Context.getPointerDiffType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 InvalidOperands(loc, lex, rex);
1133 return QualType();
1134}
1135
1136inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001137 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001138{
1139 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1140 // for int << longlong -> the result type should be int, not long long.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001141 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001142
Steve Naroffa4332e22007-07-17 00:58:39 +00001143 // handle the common case first (both operands are arithmetic).
1144 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001145 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 InvalidOperands(loc, lex, rex);
1147 return QualType();
1148}
1149
Chris Lattnera5937dd2007-08-26 01:18:55 +00001150inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1151 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Reid Spencer5f016e22007-07-11 17:01:13 +00001152{
Chris Lattnera5937dd2007-08-26 01:18:55 +00001153 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001154 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1155 UsualArithmeticConversions(lex, rex);
1156 else {
1157 UsualUnaryConversions(lex);
1158 UsualUnaryConversions(rex);
1159 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001160 QualType lType = lex->getType();
1161 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001162
Chris Lattnera5937dd2007-08-26 01:18:55 +00001163 if (isRelational) {
1164 if (lType->isRealType() && rType->isRealType())
1165 return Context.IntTy;
1166 } else {
Chris Lattner915311c2007-08-30 06:10:41 +00001167 if (lType->isFloatingType() && rType->isFloatingType())
Ted Kremenek9b3d3a92007-08-29 18:06:12 +00001168 Diag(loc, diag::warn_floatingpoint_eq);
1169
Chris Lattnera5937dd2007-08-26 01:18:55 +00001170 if (lType->isArithmeticType() && rType->isArithmeticType())
1171 return Context.IntTy;
1172 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001173
Chris Lattnerd28f8152007-08-26 01:10:14 +00001174 bool LHSIsNull = lex->isNullPointerConstant(Context);
1175 bool RHSIsNull = rex->isNullPointerConstant(Context);
1176
Chris Lattnera5937dd2007-08-26 01:18:55 +00001177 // All of the following pointer related warnings are GCC extensions, except
1178 // when handling null pointer constants. One day, we can consider making them
1179 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001180 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerd28f8152007-08-26 01:10:14 +00001181 if (!LHSIsNull && !RHSIsNull &&
Steve Naroff77878cc2007-08-27 04:08:11 +00001182 !Type::pointerTypesAreCompatible(lType.getUnqualifiedType(),
1183 rType.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001184 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1185 lType.getAsString(), rType.getAsString(),
1186 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 }
Chris Lattnerd28f8152007-08-26 01:10:14 +00001188 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001189 return Context.IntTy;
1190 }
1191 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001192 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001193 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1194 lType.getAsString(), rType.getAsString(),
1195 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001196 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001197 return Context.IntTy;
1198 }
1199 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001200 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001201 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1202 lType.getAsString(), rType.getAsString(),
1203 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001204 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001205 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 }
1207 InvalidOperands(loc, lex, rex);
1208 return QualType();
1209}
1210
Reid Spencer5f016e22007-07-11 17:01:13 +00001211inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001212 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001213{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001214 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001216
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001217 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001218
Steve Naroffa4332e22007-07-17 00:58:39 +00001219 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001220 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 InvalidOperands(loc, lex, rex);
1222 return QualType();
1223}
1224
1225inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001226 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001227{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001228 UsualUnaryConversions(lex);
1229 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001230
Steve Naroffa4332e22007-07-17 00:58:39 +00001231 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001232 return Context.IntTy;
1233 InvalidOperands(loc, lex, rex);
1234 return QualType();
1235}
1236
1237inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001238 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001239{
1240 QualType lhsType = lex->getType();
1241 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1242 bool hadError = false;
1243 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1244
1245 switch (mlval) { // C99 6.5.16p2
1246 case Expr::MLV_Valid:
1247 break;
1248 case Expr::MLV_ConstQualified:
1249 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1250 hadError = true;
1251 break;
1252 case Expr::MLV_ArrayType:
1253 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1254 lhsType.getAsString(), lex->getSourceRange());
1255 return QualType();
1256 case Expr::MLV_NotObjectType:
1257 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1258 lhsType.getAsString(), lex->getSourceRange());
1259 return QualType();
1260 case Expr::MLV_InvalidExpression:
1261 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1262 lex->getSourceRange());
1263 return QualType();
1264 case Expr::MLV_IncompleteType:
1265 case Expr::MLV_IncompleteVoidType:
1266 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1267 lhsType.getAsString(), lex->getSourceRange());
1268 return QualType();
Steve Narofffec0b492007-07-30 03:29:09 +00001269 case Expr::MLV_DuplicateVectorComponents:
1270 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1271 lex->getSourceRange());
1272 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 }
Steve Naroff90045e82007-07-13 23:32:42 +00001274 AssignmentCheckResult result;
1275
1276 if (compoundType.isNull())
1277 result = CheckSingleAssignmentConstraints(lhsType, rex);
1278 else
1279 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001280
Reid Spencer5f016e22007-07-11 17:01:13 +00001281 // decode the result (notice that extensions still return a type).
1282 switch (result) {
1283 case Compatible:
1284 break;
1285 case Incompatible:
1286 Diag(loc, diag::err_typecheck_assign_incompatible,
1287 lhsType.getAsString(), rhsType.getAsString(),
1288 lex->getSourceRange(), rex->getSourceRange());
1289 hadError = true;
1290 break;
1291 case PointerFromInt:
1292 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +00001293 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1295 lhsType.getAsString(), rhsType.getAsString(),
1296 lex->getSourceRange(), rex->getSourceRange());
1297 }
1298 break;
1299 case IntFromPointer:
1300 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1301 lhsType.getAsString(), rhsType.getAsString(),
1302 lex->getSourceRange(), rex->getSourceRange());
1303 break;
1304 case IncompatiblePointer:
1305 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1306 lhsType.getAsString(), rhsType.getAsString(),
1307 lex->getSourceRange(), rex->getSourceRange());
1308 break;
1309 case CompatiblePointerDiscardsQualifiers:
1310 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1311 lhsType.getAsString(), rhsType.getAsString(),
1312 lex->getSourceRange(), rex->getSourceRange());
1313 break;
1314 }
1315 // C99 6.5.16p3: The type of an assignment expression is the type of the
1316 // left operand unless the left operand has qualified type, in which case
1317 // it is the unqualified version of the type of the left operand.
1318 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1319 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001320 // C++ 5.17p1: the type of the assignment expression is that of its left
1321 // oprdu.
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 return hadError ? QualType() : lhsType.getUnqualifiedType();
1323}
1324
1325inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001326 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001327 UsualUnaryConversions(rex);
1328 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001329}
1330
Steve Naroff49b45262007-07-13 16:58:59 +00001331/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1332/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001333QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001334 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 assert(!resType.isNull() && "no type for increment/decrement expression");
1336
Steve Naroff084f9ed2007-08-24 17:20:07 +00001337 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1339 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1340 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1341 resType.getAsString(), op->getSourceRange());
1342 return QualType();
1343 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001344 } else if (!resType->isRealType()) {
1345 if (resType->isComplexType())
1346 // C99 does not support ++/-- on complex types.
1347 Diag(OpLoc, diag::ext_integer_increment_complex,
1348 resType.getAsString(), op->getSourceRange());
1349 else {
1350 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1351 resType.getAsString(), op->getSourceRange());
1352 return QualType();
1353 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001355 // At this point, we know we have a real, complex or pointer type.
1356 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1358 if (mlval != Expr::MLV_Valid) {
1359 // FIXME: emit a more precise diagnostic...
1360 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1361 op->getSourceRange());
1362 return QualType();
1363 }
1364 return resType;
1365}
1366
1367/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1368/// This routine allows us to typecheck complex/recursive expressions
1369/// where the declaration is needed for type checking. Here are some
1370/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1371static Decl *getPrimaryDeclaration(Expr *e) {
1372 switch (e->getStmtClass()) {
1373 case Stmt::DeclRefExprClass:
1374 return cast<DeclRefExpr>(e)->getDecl();
1375 case Stmt::MemberExprClass:
1376 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1377 case Stmt::ArraySubscriptExprClass:
1378 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1379 case Stmt::CallExprClass:
1380 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1381 case Stmt::UnaryOperatorClass:
1382 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1383 case Stmt::ParenExprClass:
1384 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1385 default:
1386 return 0;
1387 }
1388}
1389
1390/// CheckAddressOfOperand - The operand of & must be either a function
1391/// designator or an lvalue designating an object. If it is an lvalue, the
1392/// object cannot be declared with storage class register or be a bit field.
1393/// Note: The usual conversions are *not* applied to the operand of the &
1394/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1395QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1396 Decl *dcl = getPrimaryDeclaration(op);
1397 Expr::isLvalueResult lval = op->isLvalue();
1398
1399 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1400 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1401 ;
1402 else { // FIXME: emit more specific diag...
1403 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1404 op->getSourceRange());
1405 return QualType();
1406 }
1407 } else if (dcl) {
1408 // We have an lvalue with a decl. Make sure the decl is not declared
1409 // with the register storage-class specifier.
1410 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1411 if (vd->getStorageClass() == VarDecl::Register) {
1412 Diag(OpLoc, diag::err_typecheck_address_of_register,
1413 op->getSourceRange());
1414 return QualType();
1415 }
1416 } else
1417 assert(0 && "Unknown/unexpected decl type");
1418
1419 // FIXME: add check for bitfields!
1420 }
1421 // If the operand has type "type", the result has type "pointer to type".
1422 return Context.getPointerType(op->getType());
1423}
1424
1425QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001426 UsualUnaryConversions(op);
1427 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001428
Chris Lattnerbefee482007-07-31 16:53:04 +00001429 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001430 QualType ptype = PT->getPointeeType();
1431 // C99 6.5.3.2p4. "if it points to an object,...".
1432 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1433 // GCC compat: special case 'void *' (treat as warning).
1434 if (ptype->isVoidType()) {
1435 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1436 qType.getAsString(), op->getSourceRange());
1437 } else {
1438 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1439 ptype.getAsString(), op->getSourceRange());
1440 return QualType();
1441 }
1442 }
1443 return ptype;
1444 }
1445 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1446 qType.getAsString(), op->getSourceRange());
1447 return QualType();
1448}
1449
1450static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1451 tok::TokenKind Kind) {
1452 BinaryOperator::Opcode Opc;
1453 switch (Kind) {
1454 default: assert(0 && "Unknown binop!");
1455 case tok::star: Opc = BinaryOperator::Mul; break;
1456 case tok::slash: Opc = BinaryOperator::Div; break;
1457 case tok::percent: Opc = BinaryOperator::Rem; break;
1458 case tok::plus: Opc = BinaryOperator::Add; break;
1459 case tok::minus: Opc = BinaryOperator::Sub; break;
1460 case tok::lessless: Opc = BinaryOperator::Shl; break;
1461 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1462 case tok::lessequal: Opc = BinaryOperator::LE; break;
1463 case tok::less: Opc = BinaryOperator::LT; break;
1464 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1465 case tok::greater: Opc = BinaryOperator::GT; break;
1466 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1467 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1468 case tok::amp: Opc = BinaryOperator::And; break;
1469 case tok::caret: Opc = BinaryOperator::Xor; break;
1470 case tok::pipe: Opc = BinaryOperator::Or; break;
1471 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1472 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1473 case tok::equal: Opc = BinaryOperator::Assign; break;
1474 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1475 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1476 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1477 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1478 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1479 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1480 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1481 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1482 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1483 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1484 case tok::comma: Opc = BinaryOperator::Comma; break;
1485 }
1486 return Opc;
1487}
1488
1489static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1490 tok::TokenKind Kind) {
1491 UnaryOperator::Opcode Opc;
1492 switch (Kind) {
1493 default: assert(0 && "Unknown unary op!");
1494 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1495 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1496 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1497 case tok::star: Opc = UnaryOperator::Deref; break;
1498 case tok::plus: Opc = UnaryOperator::Plus; break;
1499 case tok::minus: Opc = UnaryOperator::Minus; break;
1500 case tok::tilde: Opc = UnaryOperator::Not; break;
1501 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1502 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1503 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1504 case tok::kw___real: Opc = UnaryOperator::Real; break;
1505 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1506 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1507 }
1508 return Opc;
1509}
1510
1511// Binary Operators. 'Tok' is the token for the operator.
1512Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1513 ExprTy *LHS, ExprTy *RHS) {
1514 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1515 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1516
1517 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1518 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1519
1520 QualType ResultTy; // Result type of the binary operator.
1521 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1522
1523 switch (Opc) {
1524 default:
1525 assert(0 && "Unknown binary expr!");
1526 case BinaryOperator::Assign:
1527 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1528 break;
1529 case BinaryOperator::Mul:
1530 case BinaryOperator::Div:
1531 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1532 break;
1533 case BinaryOperator::Rem:
1534 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1535 break;
1536 case BinaryOperator::Add:
1537 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1538 break;
1539 case BinaryOperator::Sub:
1540 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1541 break;
1542 case BinaryOperator::Shl:
1543 case BinaryOperator::Shr:
1544 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1545 break;
1546 case BinaryOperator::LE:
1547 case BinaryOperator::LT:
1548 case BinaryOperator::GE:
1549 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001550 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 break;
1552 case BinaryOperator::EQ:
1553 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001554 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 break;
1556 case BinaryOperator::And:
1557 case BinaryOperator::Xor:
1558 case BinaryOperator::Or:
1559 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1560 break;
1561 case BinaryOperator::LAnd:
1562 case BinaryOperator::LOr:
1563 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1564 break;
1565 case BinaryOperator::MulAssign:
1566 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001567 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 if (!CompTy.isNull())
1569 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1570 break;
1571 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001572 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 if (!CompTy.isNull())
1574 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1575 break;
1576 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001577 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 if (!CompTy.isNull())
1579 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1580 break;
1581 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001582 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 if (!CompTy.isNull())
1584 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1585 break;
1586 case BinaryOperator::ShlAssign:
1587 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001588 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 if (!CompTy.isNull())
1590 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1591 break;
1592 case BinaryOperator::AndAssign:
1593 case BinaryOperator::XorAssign:
1594 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001595 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 if (!CompTy.isNull())
1597 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1598 break;
1599 case BinaryOperator::Comma:
1600 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1601 break;
1602 }
1603 if (ResultTy.isNull())
1604 return true;
1605 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001606 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001608 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001609}
1610
1611// Unary Operators. 'Tok' is the token for the operator.
1612Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1613 ExprTy *input) {
1614 Expr *Input = (Expr*)input;
1615 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1616 QualType resultType;
1617 switch (Opc) {
1618 default:
1619 assert(0 && "Unimplemented unary expr!");
1620 case UnaryOperator::PreInc:
1621 case UnaryOperator::PreDec:
1622 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1623 break;
1624 case UnaryOperator::AddrOf:
1625 resultType = CheckAddressOfOperand(Input, OpLoc);
1626 break;
1627 case UnaryOperator::Deref:
1628 resultType = CheckIndirectionOperand(Input, OpLoc);
1629 break;
1630 case UnaryOperator::Plus:
1631 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001632 UsualUnaryConversions(Input);
1633 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1635 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1636 resultType.getAsString());
1637 break;
1638 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001639 UsualUnaryConversions(Input);
1640 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00001641 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1642 if (!resultType->isIntegerType()) {
1643 if (resultType->isComplexType())
1644 // C99 does not support '~' for complex conjugation.
1645 Diag(OpLoc, diag::ext_integer_complement_complex,
1646 resultType.getAsString());
1647 else
1648 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1649 resultType.getAsString());
1650 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 break;
1652 case UnaryOperator::LNot: // logical negation
1653 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001654 DefaultFunctionArrayConversion(Input);
1655 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1657 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1658 resultType.getAsString());
1659 // LNot always has type int. C99 6.5.3.3p5.
1660 resultType = Context.IntTy;
1661 break;
1662 case UnaryOperator::SizeOf:
1663 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1664 break;
1665 case UnaryOperator::AlignOf:
1666 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1667 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001668 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00001669 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00001670 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00001671 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 resultType = Input->getType();
1674 break;
1675 }
1676 if (resultType.isNull())
1677 return true;
1678 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1679}
1680
1681/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1682Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1683 SourceLocation LabLoc,
1684 IdentifierInfo *LabelII) {
1685 // Look up the record for this label identifier.
1686 LabelStmt *&LabelDecl = LabelMap[LabelII];
1687
1688 // If we haven't seen this label yet, create a forward reference.
1689 if (LabelDecl == 0)
1690 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1691
1692 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001693 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1694 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001695}
1696
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001697Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1698 SourceLocation RPLoc) { // "({..})"
1699 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1700 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1701 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1702
1703 // FIXME: there are a variety of strange constraints to enforce here, for
1704 // example, it is not possible to goto into a stmt expression apparently.
1705 // More semantic analysis is needed.
1706
1707 // FIXME: the last statement in the compount stmt has its value used. We
1708 // should not warn about it being unused.
1709
1710 // If there are sub stmts in the compound stmt, take the type of the last one
1711 // as the type of the stmtexpr.
1712 QualType Ty = Context.VoidTy;
1713
1714 if (!Compound->body_empty())
1715 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1716 Ty = LastExpr->getType();
1717
1718 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1719}
Steve Naroffd34e9152007-08-01 22:05:33 +00001720
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001721Sema::ExprResult Sema::ParseBuiltinOffsetOf(SourceLocation BuiltinLoc,
1722 SourceLocation TypeLoc,
1723 TypeTy *argty,
1724 OffsetOfComponent *CompPtr,
1725 unsigned NumComponents,
1726 SourceLocation RPLoc) {
1727 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1728 assert(!ArgTy.isNull() && "Missing type argument!");
1729
1730 // We must have at least one component that refers to the type, and the first
1731 // one is known to be a field designator. Verify that the ArgTy represents
1732 // a struct/union/class.
1733 if (!ArgTy->isRecordType())
1734 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1735
1736 // Otherwise, create a compound literal expression as the base, and
1737 // iteratively process the offsetof designators.
1738 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1739
1740 for (unsigned i = 0; i != NumComponents; ++i) {
1741 const OffsetOfComponent &OC = CompPtr[i];
1742 if (OC.isBrackets) {
1743 // Offset of an array sub-field. TODO: Should we allow vector elements?
1744 const ArrayType *AT = Res->getType()->getAsArrayType();
1745 if (!AT) {
1746 delete Res;
1747 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1748 Res->getType().getAsString());
1749 }
1750
Chris Lattner704fe352007-08-30 17:59:59 +00001751 // FIXME: C++: Verify that operator[] isn't overloaded.
1752
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001753 // C99 6.5.2.1p1
1754 Expr *Idx = static_cast<Expr*>(OC.U.E);
1755 if (!Idx->getType()->isIntegerType())
1756 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1757 Idx->getSourceRange());
1758
1759 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1760 continue;
1761 }
1762
1763 const RecordType *RC = Res->getType()->getAsRecordType();
1764 if (!RC) {
1765 delete Res;
1766 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1767 Res->getType().getAsString());
1768 }
1769
1770 // Get the decl corresponding to this.
1771 RecordDecl *RD = RC->getDecl();
1772 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1773 if (!MemberDecl)
1774 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1775 OC.U.IdentInfo->getName(),
1776 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00001777
1778 // FIXME: C++: Verify that MemberDecl isn't a static field.
1779 // FIXME: Verify that MemberDecl isn't a bitfield.
1780
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001781 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1782 }
1783
1784 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1785 BuiltinLoc);
1786}
1787
1788
Steve Naroff363bcff2007-08-01 23:45:51 +00001789Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00001790 TypeTy *arg1, TypeTy *arg2,
1791 SourceLocation RPLoc) {
1792 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1793 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1794
1795 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1796
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001797 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00001798}
1799
Steve Naroffd04fdd52007-08-03 21:21:27 +00001800Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1801 ExprTy *expr1, ExprTy *expr2,
1802 SourceLocation RPLoc) {
1803 Expr *CondExpr = static_cast<Expr*>(cond);
1804 Expr *LHSExpr = static_cast<Expr*>(expr1);
1805 Expr *RHSExpr = static_cast<Expr*>(expr2);
1806
1807 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1808
1809 // The conditional expression is required to be a constant expression.
1810 llvm::APSInt condEval(32);
1811 SourceLocation ExpLoc;
1812 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1813 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1814 CondExpr->getSourceRange());
1815
1816 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1817 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1818 RHSExpr->getType();
1819 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1820}
1821
Anders Carlsson55085182007-08-21 17:43:55 +00001822// TODO: Move this to SemaObjC.cpp
Anders Carlssonf9bcf012007-08-22 15:14:15 +00001823Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlsson55085182007-08-21 17:43:55 +00001824 StringLiteral* S = static_cast<StringLiteral *>(string);
1825
1826 if (CheckBuiltinCFStringArgument(S))
1827 return true;
1828
1829 QualType t = Context.getCFConstantStringType();
1830 t = t.getQualifiedType(QualType::Const);
1831 t = Context.getPointerType(t);
1832
1833 return new ObjCStringLiteral(S, t);
1834}
Anders Carlssonf9bcf012007-08-22 15:14:15 +00001835
1836Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1837 SourceLocation LParenLoc,
1838 TypeTy *Ty,
1839 SourceLocation RParenLoc) {
1840 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1841
1842 QualType t = Context.getPointerType(Context.CharTy);
1843 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1844}