blob: a32e607aa4103550bb9df6354f95f193ded69ad9 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/Expr.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/LiteralSupport.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +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
35Sema::ParseStringLiteral(const Token *StringToks, unsigned NumStringToks) {
36 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 Naroff91b03f72007-08-28 03:03:08 +000077 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +000078 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +000079 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +000080 return true;
Chris Lattner4b009652007-07-25 00:24:17 +000081 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +000082 }
Chris Lattner4b009652007-07-25 00:24:17 +000083 if (isa<TypedefDecl>(D))
84 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
85
86 assert(0 && "Invalid decl");
87 abort();
88}
89
90Sema::ExprResult Sema::ParsePreDefinedExpr(SourceLocation Loc,
91 tok::TokenKind Kind) {
92 PreDefinedExpr::IdentType IT;
93
94 switch (Kind) {
95 default:
96 assert(0 && "Unknown simple primary expr!");
97 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
98 IT = PreDefinedExpr::Func;
99 break;
100 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
101 IT = PreDefinedExpr::Function;
102 break;
103 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
104 IT = PreDefinedExpr::PrettyFunction;
105 break;
106 }
107
108 // Pre-defined identifiers are always of type char *.
109 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
110}
111
112Sema::ExprResult Sema::ParseCharacterConstant(const Token &Tok) {
113 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
126Action::ExprResult Sema::ParseNumericConstant(const Token &Tok) {
127 // 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
132 unsigned IntSize = Context.getTypeSize(Context.IntTy, Tok.getLocation());
133 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 Lattner1de66eb2007-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 {
Chris Lattner4b009652007-07-25 00:24:17 +0000157 QualType t;
158
Neil Booth7421e9c2007-08-29 22:00:19 +0000159 // long long is a C99 feature.
160 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000161 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000162 Diag(Tok.getLocation(), diag::ext_longlong);
163
Chris Lattner4b009652007-07-25 00:24:17 +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;
171 assert(Context.getTypeSize(t, Tok.getLocation()) ==
172 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 Lattner98540b62007-08-23 21:58:08 +0000182 if (!Literal.isLong && !Literal.isLongLong) {
183 // Are int/unsigned possibilities?
Chris Lattner4b009652007-07-25 00:24:17 +0000184 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
185 // 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) {
200 unsigned LongSize = Context.getTypeSize(Context.LongTy,
201 Tok.getLocation());
202
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 =
218 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
219
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 Lattner1de66eb2007-08-26 03:42:43 +0000238 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000239 }
Chris Lattner1de66eb2007-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;
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner5110ad52007-08-24 21:41:10 +0000292QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000293 DefaultFunctionArrayConversion(V);
294
Chris Lattnera16e42d2007-08-26 05:39:26 +0000295 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000296 if (const ComplexType *CT = V->getType()->getAsComplexType())
297 return CT->getElementType();
Chris Lattnera16e42d2007-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 Lattner03931a72007-08-24 21:16:53 +0000306}
307
308
Chris Lattner4b009652007-07-25 00:24:17 +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) {
328 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
329
330 // Perform default conversions.
331 DefaultFunctionArrayConversion(LHSExp);
332 DefaultFunctionArrayConversion(RHSExp);
333
334 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
335
336 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000337 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000338 // in the subscript position. As a result, we need to derive the array base
339 // and index from the expression types.
340 Expr *BaseExpr, *IndexExpr;
341 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000342 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000343 BaseExpr = LHSExp;
344 IndexExpr = RHSExp;
345 // FIXME: need to deal with const...
346 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000347 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000348 // Handle the uncommon case of "123[Ptr]".
349 BaseExpr = RHSExp;
350 IndexExpr = LHSExp;
351 // FIXME: need to deal with const...
352 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000353 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
354 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000355 IndexExpr = RHSExp;
Steve Naroff89345522007-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 Lattner4b009652007-07-25 00:24:17 +0000361 // FIXME: need to deal with const...
362 ResultType = VTy->getElementType();
363 } else {
364 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
365 RHSExp->getSourceRange());
366 }
367 // C99 6.5.2.1p1
368 if (!IndexExpr->getType()->isIntegerType())
369 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
370 IndexExpr->getSourceRange());
371
372 // 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);
381}
382
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000383QualType Sema::
384CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
385 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000386 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-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 Lattner9096b792007-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 Naroff1b8a46c2007-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 Naroff82113e32007-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 Naroff1b8a46c2007-07-27 22:15:19 +0000447}
448
Chris Lattner4b009652007-07-25 00:24:17 +0000449Action::ExprResult Sema::
450ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
451 tok::TokenKind OpKind, SourceLocation MemberLoc,
452 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000453 Expr *BaseExpr = static_cast<Expr *>(Base);
454 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000455
Steve Naroff2cb66382007-07-26 03:11:44 +0000456 QualType BaseType = BaseExpr->getType();
457 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000458
Chris Lattner4b009652007-07-25 00:24:17 +0000459 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000460 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000461 BaseType = PT->getPointeeType();
462 else
463 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
464 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000465 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000466 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000467 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-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 Naroff1b8a46c2007-07-27 22:15:19 +0000473 FieldDecl *MemberDecl = RDecl->getMember(&Member);
474 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000475 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
476 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000477 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
478 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-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 Naroff1b8a46c2007-07-27 22:15:19 +0000483 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
484 if (ret.isNull())
485 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000486 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000487 } else
488 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
489 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +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::
496ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
497 ExprTy **args, unsigned NumArgsInCall,
498 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
499 Expr *Fn = static_cast<Expr *>(fn);
500 Expr **Args = reinterpret_cast<Expr**>(args);
501 assert(Fn && "no function call expression");
502
503 UsualUnaryConversions(Fn);
504 QualType funcType = Fn->getType();
505
506 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
507 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000508 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000509 if (PT == 0)
510 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
511 SourceRange(Fn->getLocStart(), RParenLoc));
512
Chris Lattner71225142007-07-31 21:27:01 +0000513 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000514 if (funcT == 0)
515 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
516 SourceRange(Fn->getLocStart(), RParenLoc));
517
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,
530 Fn->getSourceRange());
531 else if (NumArgsInCall > NumArgsInProto) {
532 if (!proto->isVariadic()) {
533 Diag(Args[NumArgsInProto]->getLocStart(),
534 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
535 SourceRange(Args[NumArgsInProto]->getLocStart(),
536 Args[NumArgsInCall-1]->getLocEnd()));
537 }
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++) {
542 Expr *argExpr = Args[i];
543 assert(argExpr && "ParseCallExpr(): missing argument expression");
544
545 QualType lhsType = proto->getArgType(i);
546 QualType rhsType = argExpr->getType();
547
Steve Naroff75644062007-07-25 20:45:33 +0000548 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000549 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000550 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000551 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000552 lhsType = Context.getPointerType(lhsType);
553
554 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
555 argExpr);
Steve Naroff0f32f432007-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.
Chris Lattner4b009652007-07-25 00:24:17 +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)
566 if (!argExpr->isNullPointerConstant(Context)) {
567 Diag(l, diag::ext_typecheck_passing_pointer_int,
568 lhsType.getAsString(), rhsType.getAsString(),
569 Fn->getSourceRange(), argExpr->getSourceRange());
570 }
571 break;
572 case IntFromPointer:
573 Diag(l, diag::ext_typecheck_passing_pointer_int,
574 lhsType.getAsString(), rhsType.getAsString(),
575 Fn->getSourceRange(), argExpr->getSourceRange());
576 break;
577 case IncompatiblePointer:
578 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
579 rhsType.getAsString(), lhsType.getAsString(),
580 Fn->getSourceRange(), argExpr->getSourceRange());
581 break;
582 case CompatiblePointerDiscardsQualifiers:
583 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
584 rhsType.getAsString(), lhsType.getAsString(),
585 Fn->getSourceRange(), argExpr->getSourceRange());
586 break;
587 case Incompatible:
588 return Diag(l, diag::err_typecheck_passing_incompatible,
589 rhsType.getAsString(), lhsType.getAsString(),
590 Fn->getSourceRange(), argExpr->getSourceRange());
591 }
592 }
Steve Naroffdb65e052007-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.
Chris Lattner4b009652007-07-25 00:24:17 +0000605 return true;
Steve Naroffdb65e052007-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 }
Chris Lattner4b009652007-07-25 00:24:17 +0000617 }
Chris Lattner2e64c072007-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 Lattner0d9bcea2007-08-30 17:45:32 +0000622 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
623 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000624 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000625
Chris Lattner4b009652007-07-25 00:24:17 +0000626 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
627}
628
629Action::ExprResult Sema::
630ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
631 SourceLocation RParenLoc, ExprTy *InitExpr) {
632 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
633 QualType literalType = QualType::getFromOpaquePtr(Ty);
634 // FIXME: put back this assert when initializers are worked out.
635 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
636 Expr *literalExpr = static_cast<Expr*>(InitExpr);
637
638 // FIXME: add semantic analysis (C99 6.5.2.5).
639 return new CompoundLiteralExpr(literalType, literalExpr);
640}
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::
653ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
654 SourceLocation RParenLoc, ExprTy *Op) {
655 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
Steve Naroff68adb482007-08-31 00:32:44 +0000660 UsualUnaryConversions(castExpr);
661
Chris Lattner4b009652007-07-25 00:24:17 +0000662 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
663 // type needs to be scalar.
664 if (!castType->isScalarType() && !castType->isVoidType()) {
665 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
666 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
667 }
668 if (!castExpr->getType()->isScalarType()) {
669 return Diag(castExpr->getLocStart(),
670 diag::err_typecheck_expect_scalar_operand,
671 castExpr->getType().getAsString(), castExpr->getSourceRange());
672 }
673 return new CastExpr(castType, castExpr, LParenLoc);
674}
675
676inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
677 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
678 UsualUnaryConversions(cond);
679 UsualUnaryConversions(lex);
680 UsualUnaryConversions(rex);
681 QualType condT = cond->getType();
682 QualType lexT = lex->getType();
683 QualType rexT = rex->getType();
684
685 // first, check the condition.
686 if (!condT->isScalarType()) { // C99 6.5.15p2
687 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
688 condT.getAsString());
689 return QualType();
690 }
691 // now check the two expressions.
692 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
693 UsualArithmeticConversions(lex, rex);
694 return lex->getType();
695 }
Chris Lattner71225142007-07-31 21:27:01 +0000696 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
697 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
698
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000699 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
Chris Lattner71225142007-07-31 21:27:01 +0000700 return lexT;
701
Chris Lattner4b009652007-07-25 00:24:17 +0000702 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
703 lexT.getAsString(), rexT.getAsString(),
704 lex->getSourceRange(), rex->getSourceRange());
705 return QualType();
706 }
707 }
708 // C99 6.5.15p3
709 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
710 return lexT;
711 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
712 return rexT;
713
Chris Lattner71225142007-07-31 21:27:01 +0000714 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
715 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
716 // get the "pointed to" types
717 QualType lhptee = LHSPT->getPointeeType();
718 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000719
Chris Lattner71225142007-07-31 21:27:01 +0000720 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
721 if (lhptee->isVoidType() &&
722 (rhptee->isObjectType() || rhptee->isIncompleteType()))
723 return lexT;
724 if (rhptee->isVoidType() &&
725 (lhptee->isObjectType() || lhptee->isIncompleteType()))
726 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000727
Chris Lattner71225142007-07-31 21:27:01 +0000728 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
729 rhptee.getUnqualifiedType())) {
730 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
731 lexT.getAsString(), rexT.getAsString(),
732 lex->getSourceRange(), rex->getSourceRange());
733 return lexT; // FIXME: this is an _ext - is this return o.k?
734 }
735 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000736 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
737 // differently qualified versions of compatible types, the result type is
738 // a pointer to an appropriately qualified version of the *composite*
739 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000740 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000741 }
Chris Lattner4b009652007-07-25 00:24:17 +0000742 }
Chris Lattner71225142007-07-31 21:27:01 +0000743
Chris Lattner4b009652007-07-25 00:24:17 +0000744 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
745 return lexT;
746
747 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
748 lexT.getAsString(), rexT.getAsString(),
749 lex->getSourceRange(), rex->getSourceRange());
750 return QualType();
751}
752
753/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
754/// in the case of a the GNU conditional expr extension.
755Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
756 SourceLocation ColonLoc,
757 ExprTy *Cond, ExprTy *LHS,
758 ExprTy *RHS) {
759 Expr *CondExpr = (Expr *) Cond;
760 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
761 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
762 RHSExpr, QuestionLoc);
763 if (result.isNull())
764 return true;
765 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
766}
767
768// promoteExprToType - a helper function to ensure we create exactly one
769// ImplicitCastExpr. As a convenience (to the caller), we return the type.
770static void promoteExprToType(Expr *&expr, QualType type) {
771 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
772 impCast->setType(type);
773 else
774 expr = new ImplicitCastExpr(type, expr);
775 return;
776}
777
Steve Naroffdb65e052007-08-28 23:30:39 +0000778/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
779/// do not have a prototype. Integer promotions are performed on each
780/// argument, and arguments that have type float are promoted to double.
781void Sema::DefaultArgumentPromotion(Expr *&expr) {
782 QualType t = expr->getType();
783 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
784
785 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
786 promoteExprToType(expr, Context.IntTy);
787 if (t == Context.FloatTy)
788 promoteExprToType(expr, Context.DoubleTy);
789}
790
Chris Lattner4b009652007-07-25 00:24:17 +0000791/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
792void Sema::DefaultFunctionArrayConversion(Expr *&e) {
793 QualType t = e->getType();
794 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
795
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000796 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000797 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
798 t = e->getType();
799 }
800 if (t->isFunctionType())
801 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000802 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000803 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
804}
805
806/// UsualUnaryConversion - Performs various conversions that are common to most
807/// operators (C99 6.3). The conversions of array and function types are
808/// sometimes surpressed. For example, the array->pointer conversion doesn't
809/// apply if the array is an argument to the sizeof or address (&) operators.
810/// In these instances, this routine should *not* be called.
811void Sema::UsualUnaryConversions(Expr *&expr) {
812 QualType t = expr->getType();
813 assert(!t.isNull() && "UsualUnaryConversions - missing type");
814
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000815 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000816 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
817 t = expr->getType();
818 }
819 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
820 promoteExprToType(expr, Context.IntTy);
821 else
822 DefaultFunctionArrayConversion(expr);
823}
824
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000825/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000826/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
827/// routine returns the first non-arithmetic type found. The client is
828/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000829QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
830 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000831 if (!isCompAssign) {
832 UsualUnaryConversions(lhsExpr);
833 UsualUnaryConversions(rhsExpr);
834 }
Chris Lattner4b009652007-07-25 00:24:17 +0000835 QualType lhs = lhsExpr->getType();
836 QualType rhs = rhsExpr->getType();
837
838 // If both types are identical, no conversion is needed.
839 if (lhs == rhs)
Steve Naroff8f708362007-08-24 19:07:16 +0000840 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000841
842 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
843 // The caller can deal with this (e.g. pointer + int).
844 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000845 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000846
847 // At this point, we have two different arithmetic types.
848
849 // Handle complex types first (C99 6.3.1.8p1).
850 if (lhs->isComplexType() || rhs->isComplexType()) {
851 // if we have an integer operand, the result is the complex type.
852 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000853 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
854 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000855 }
856 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000857 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
858 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000859 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000860 // This handles complex/complex, complex/float, or float/complex.
861 // When both operands are complex, the shorter operand is converted to the
862 // type of the longer, and that is the type of the result. This corresponds
863 // to what is done when combining two real floating-point operands.
864 // The fun begins when size promotion occur across type domains.
865 // From H&S 6.3.4: When one operand is complex and the other is a real
866 // floating-point type, the less precise type is converted, within it's
867 // real or complex domain, to the precision of the other type. For example,
868 // when combining a "long double" with a "double _Complex", the
869 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000870 int result = Context.compareFloatingType(lhs, rhs);
871
872 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000873 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
874 if (!isCompAssign)
875 promoteExprToType(rhsExpr, rhs);
876 } else if (result < 0) { // The right side is bigger, convert lhs.
877 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
878 if (!isCompAssign)
879 promoteExprToType(lhsExpr, lhs);
880 }
881 // At this point, lhs and rhs have the same rank/size. Now, make sure the
882 // domains match. This is a requirement for our implementation, C99
883 // does not require this promotion.
884 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
885 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000886 if (!isCompAssign)
887 promoteExprToType(lhsExpr, rhs);
888 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000889 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000890 if (!isCompAssign)
891 promoteExprToType(rhsExpr, lhs);
892 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000893 }
Chris Lattner4b009652007-07-25 00:24:17 +0000894 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000895 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000896 }
897 // Now handle "real" floating types (i.e. float, double, long double).
898 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
899 // if we have an integer operand, the result is the real floating type.
900 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000901 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
902 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000903 }
904 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000905 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
906 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000907 }
908 // We have two real floating types, float/complex combos were handled above.
909 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +0000910 int result = Context.compareFloatingType(lhs, rhs);
911
912 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000913 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
914 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000915 }
Steve Naroff45fc9822007-08-27 15:30:22 +0000916 if (result < 0) { // convert the lhs
917 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
918 return rhs;
919 }
920 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +0000921 }
922 // Finally, we have two differing integer types.
923 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000924 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
925 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000926 }
Steve Naroff8f708362007-08-24 19:07:16 +0000927 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
928 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000929}
930
931// CheckPointerTypesForAssignment - This is a very tricky routine (despite
932// being closely modeled after the C99 spec:-). The odd characteristic of this
933// routine is it effectively iqnores the qualifiers on the top level pointee.
934// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
935// FIXME: add a couple examples in this comment.
936Sema::AssignmentCheckResult
937Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
938 QualType lhptee, rhptee;
939
940 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000941 lhptee = lhsType->getAsPointerType()->getPointeeType();
942 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000943
944 // make sure we operate on the canonical type
945 lhptee = lhptee.getCanonicalType();
946 rhptee = rhptee.getCanonicalType();
947
948 AssignmentCheckResult r = Compatible;
949
950 // C99 6.5.16.1p1: This following citation is common to constraints
951 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
952 // qualifiers of the type *pointed to* by the right;
953 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
954 rhptee.getQualifiers())
955 r = CompatiblePointerDiscardsQualifiers;
956
957 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
958 // incomplete type and the other is a pointer to a qualified or unqualified
959 // version of void...
960 if (lhptee.getUnqualifiedType()->isVoidType() &&
961 (rhptee->isObjectType() || rhptee->isIncompleteType()))
962 ;
963 else if (rhptee.getUnqualifiedType()->isVoidType() &&
964 (lhptee->isObjectType() || lhptee->isIncompleteType()))
965 ;
966 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
967 // unqualified versions of compatible types, ...
968 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
969 rhptee.getUnqualifiedType()))
970 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
971 return r;
972}
973
974/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
975/// has code to accommodate several GCC extensions when type checking
976/// pointers. Here are some objectionable examples that GCC considers warnings:
977///
978/// int a, *pint;
979/// short *pshort;
980/// struct foo *pfoo;
981///
982/// pint = pshort; // warning: assignment from incompatible pointer type
983/// a = pint; // warning: assignment makes integer from pointer without a cast
984/// pint = a; // warning: assignment makes pointer from integer without a cast
985/// pint = pfoo; // warning: assignment from incompatible pointer type
986///
987/// As a result, the code for dealing with pointers is more complex than the
988/// C99 spec dictates.
989/// Note: the warning above turn into errors when -pedantic-errors is enabled.
990///
991Sema::AssignmentCheckResult
992Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
993 if (lhsType == rhsType) // common case, fast path...
994 return Compatible;
995
996 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
997 if (lhsType->isVectorType() || rhsType->isVectorType()) {
998 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
999 return Incompatible;
1000 }
1001 return Compatible;
1002 } else if (lhsType->isPointerType()) {
1003 if (rhsType->isIntegerType())
1004 return PointerFromInt;
1005
1006 if (rhsType->isPointerType())
1007 return CheckPointerTypesForAssignment(lhsType, rhsType);
1008 } else if (rhsType->isPointerType()) {
1009 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1010 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1011 return IntFromPointer;
1012
1013 if (lhsType->isPointerType())
1014 return CheckPointerTypesForAssignment(lhsType, rhsType);
1015 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1016 if (Type::tagTypesAreCompatible(lhsType, rhsType))
1017 return Compatible;
1018 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1019 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
1020 return Compatible;
1021 }
1022 return Incompatible;
1023}
1024
1025Sema::AssignmentCheckResult
1026Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1027 // This check seems unnatural, however it is necessary to insure the proper
1028 // conversion of functions/arrays. If the conversion were done for all
1029 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
1030 // expressions that surpress this implicit conversion (&, sizeof).
1031 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001032
1033 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001034
Steve Naroff0f32f432007-08-24 22:33:52 +00001035 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1036
1037 // C99 6.5.16.1p2: The value of the right operand is converted to the
1038 // type of the assignment expression.
1039 if (rExpr->getType() != lhsType)
1040 promoteExprToType(rExpr, lhsType);
1041 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001042}
1043
1044Sema::AssignmentCheckResult
1045Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1046 return CheckAssignmentConstraints(lhsType, rhsType);
1047}
1048
1049inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1050 Diag(loc, diag::err_typecheck_invalid_operands,
1051 lex->getType().getAsString(), rex->getType().getAsString(),
1052 lex->getSourceRange(), rex->getSourceRange());
1053}
1054
1055inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1056 Expr *&rex) {
1057 QualType lhsType = lex->getType(), rhsType = rex->getType();
1058
1059 // make sure the vector types are identical.
1060 if (lhsType == rhsType)
1061 return lhsType;
1062 // You cannot convert between vector values of different size.
1063 Diag(loc, diag::err_typecheck_vector_not_convertable,
1064 lex->getType().getAsString(), rex->getType().getAsString(),
1065 lex->getSourceRange(), rex->getSourceRange());
1066 return QualType();
1067}
1068
1069inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001070 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001071{
1072 QualType lhsType = lex->getType(), rhsType = rex->getType();
1073
1074 if (lhsType->isVectorType() || rhsType->isVectorType())
1075 return CheckVectorOperands(loc, lex, rex);
1076
Steve Naroff8f708362007-08-24 19:07:16 +00001077 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001078
Chris Lattner4b009652007-07-25 00:24:17 +00001079 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001080 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001081 InvalidOperands(loc, lex, rex);
1082 return QualType();
1083}
1084
1085inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001086 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001087{
1088 QualType lhsType = lex->getType(), rhsType = rex->getType();
1089
Steve Naroff8f708362007-08-24 19:07:16 +00001090 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001091
Chris Lattner4b009652007-07-25 00:24:17 +00001092 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001093 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001094 InvalidOperands(loc, lex, rex);
1095 return QualType();
1096}
1097
1098inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001099 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001100{
1101 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1102 return CheckVectorOperands(loc, lex, rex);
1103
Steve Naroff8f708362007-08-24 19:07:16 +00001104 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001105
1106 // handle the common case first (both operands are arithmetic).
1107 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001108 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001109
1110 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1111 return lex->getType();
1112 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1113 return rex->getType();
1114 InvalidOperands(loc, lex, rex);
1115 return QualType();
1116}
1117
1118inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001119 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001120{
1121 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1122 return CheckVectorOperands(loc, lex, rex);
1123
Steve Naroff8f708362007-08-24 19:07:16 +00001124 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001125
1126 // handle the common case first (both operands are arithmetic).
1127 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001128 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001129
1130 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001131 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001132 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1133 return Context.getPointerDiffType();
1134 InvalidOperands(loc, lex, rex);
1135 return QualType();
1136}
1137
1138inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001139 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001140{
1141 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1142 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001143 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001144
1145 // handle the common case first (both operands are arithmetic).
1146 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001147 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001148 InvalidOperands(loc, lex, rex);
1149 return QualType();
1150}
1151
Chris Lattner254f3bc2007-08-26 01:18:55 +00001152inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1153 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001154{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001155 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001156 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1157 UsualArithmeticConversions(lex, rex);
1158 else {
1159 UsualUnaryConversions(lex);
1160 UsualUnaryConversions(rex);
1161 }
Chris Lattner4b009652007-07-25 00:24:17 +00001162 QualType lType = lex->getType();
1163 QualType rType = rex->getType();
1164
Chris Lattner254f3bc2007-08-26 01:18:55 +00001165 if (isRelational) {
1166 if (lType->isRealType() && rType->isRealType())
1167 return Context.IntTy;
1168 } else {
Chris Lattnerbd3cc222007-08-30 06:10:41 +00001169 if (lType->isFloatingType() && rType->isFloatingType())
Ted Kremenekec761af2007-08-29 18:06:12 +00001170 Diag(loc, diag::warn_floatingpoint_eq);
1171
Chris Lattner254f3bc2007-08-26 01:18:55 +00001172 if (lType->isArithmeticType() && rType->isArithmeticType())
1173 return Context.IntTy;
1174 }
Chris Lattner4b009652007-07-25 00:24:17 +00001175
Chris Lattner22be8422007-08-26 01:10:14 +00001176 bool LHSIsNull = lex->isNullPointerConstant(Context);
1177 bool RHSIsNull = rex->isNullPointerConstant(Context);
1178
Chris Lattner254f3bc2007-08-26 01:18:55 +00001179 // All of the following pointer related warnings are GCC extensions, except
1180 // when handling null pointer constants. One day, we can consider making them
1181 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001182 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner22be8422007-08-26 01:10:14 +00001183 if (!LHSIsNull && !RHSIsNull &&
Steve Naroffc33c0602007-08-27 04:08:11 +00001184 !Type::pointerTypesAreCompatible(lType.getUnqualifiedType(),
1185 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001186 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1187 lType.getAsString(), rType.getAsString(),
1188 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001189 }
Chris Lattner22be8422007-08-26 01:10:14 +00001190 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001191 return Context.IntTy;
1192 }
1193 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001194 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001195 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1196 lType.getAsString(), rType.getAsString(),
1197 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001198 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001199 return Context.IntTy;
1200 }
1201 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001202 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001203 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1204 lType.getAsString(), rType.getAsString(),
1205 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001206 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001207 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001208 }
1209 InvalidOperands(loc, lex, rex);
1210 return QualType();
1211}
1212
Chris Lattner4b009652007-07-25 00:24:17 +00001213inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001214 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001215{
1216 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1217 return CheckVectorOperands(loc, lex, rex);
1218
Steve Naroff8f708362007-08-24 19:07:16 +00001219 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001220
1221 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001222 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001223 InvalidOperands(loc, lex, rex);
1224 return QualType();
1225}
1226
1227inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1228 Expr *&lex, Expr *&rex, SourceLocation loc)
1229{
1230 UsualUnaryConversions(lex);
1231 UsualUnaryConversions(rex);
1232
1233 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1234 return Context.IntTy;
1235 InvalidOperands(loc, lex, rex);
1236 return QualType();
1237}
1238
1239inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001240 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001241{
1242 QualType lhsType = lex->getType();
1243 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1244 bool hadError = false;
1245 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1246
1247 switch (mlval) { // C99 6.5.16p2
1248 case Expr::MLV_Valid:
1249 break;
1250 case Expr::MLV_ConstQualified:
1251 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1252 hadError = true;
1253 break;
1254 case Expr::MLV_ArrayType:
1255 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1256 lhsType.getAsString(), lex->getSourceRange());
1257 return QualType();
1258 case Expr::MLV_NotObjectType:
1259 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1260 lhsType.getAsString(), lex->getSourceRange());
1261 return QualType();
1262 case Expr::MLV_InvalidExpression:
1263 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1264 lex->getSourceRange());
1265 return QualType();
1266 case Expr::MLV_IncompleteType:
1267 case Expr::MLV_IncompleteVoidType:
1268 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1269 lhsType.getAsString(), lex->getSourceRange());
1270 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001271 case Expr::MLV_DuplicateVectorComponents:
1272 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1273 lex->getSourceRange());
1274 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001275 }
1276 AssignmentCheckResult result;
1277
1278 if (compoundType.isNull())
1279 result = CheckSingleAssignmentConstraints(lhsType, rex);
1280 else
1281 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001282
Chris Lattner4b009652007-07-25 00:24:17 +00001283 // decode the result (notice that extensions still return a type).
1284 switch (result) {
1285 case Compatible:
1286 break;
1287 case Incompatible:
1288 Diag(loc, diag::err_typecheck_assign_incompatible,
1289 lhsType.getAsString(), rhsType.getAsString(),
1290 lex->getSourceRange(), rex->getSourceRange());
1291 hadError = true;
1292 break;
1293 case PointerFromInt:
1294 // check for null pointer constant (C99 6.3.2.3p3)
1295 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1296 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1297 lhsType.getAsString(), rhsType.getAsString(),
1298 lex->getSourceRange(), rex->getSourceRange());
1299 }
1300 break;
1301 case IntFromPointer:
1302 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1303 lhsType.getAsString(), rhsType.getAsString(),
1304 lex->getSourceRange(), rex->getSourceRange());
1305 break;
1306 case IncompatiblePointer:
1307 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1308 lhsType.getAsString(), rhsType.getAsString(),
1309 lex->getSourceRange(), rex->getSourceRange());
1310 break;
1311 case CompatiblePointerDiscardsQualifiers:
1312 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1313 lhsType.getAsString(), rhsType.getAsString(),
1314 lex->getSourceRange(), rex->getSourceRange());
1315 break;
1316 }
1317 // C99 6.5.16p3: The type of an assignment expression is the type of the
1318 // left operand unless the left operand has qualified type, in which case
1319 // it is the unqualified version of the type of the left operand.
1320 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1321 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001322 // C++ 5.17p1: the type of the assignment expression is that of its left
1323 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001324 return hadError ? QualType() : lhsType.getUnqualifiedType();
1325}
1326
1327inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1328 Expr *&lex, Expr *&rex, SourceLocation loc) {
1329 UsualUnaryConversions(rex);
1330 return rex->getType();
1331}
1332
1333/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1334/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1335QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1336 QualType resType = op->getType();
1337 assert(!resType.isNull() && "no type for increment/decrement expression");
1338
Steve Naroffd30e1932007-08-24 17:20:07 +00001339 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner4b009652007-07-25 00:24:17 +00001340 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1341 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1342 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1343 resType.getAsString(), op->getSourceRange());
1344 return QualType();
1345 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001346 } else if (!resType->isRealType()) {
1347 if (resType->isComplexType())
1348 // C99 does not support ++/-- on complex types.
1349 Diag(OpLoc, diag::ext_integer_increment_complex,
1350 resType.getAsString(), op->getSourceRange());
1351 else {
1352 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1353 resType.getAsString(), op->getSourceRange());
1354 return QualType();
1355 }
Chris Lattner4b009652007-07-25 00:24:17 +00001356 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001357 // At this point, we know we have a real, complex or pointer type.
1358 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001359 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1360 if (mlval != Expr::MLV_Valid) {
1361 // FIXME: emit a more precise diagnostic...
1362 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1363 op->getSourceRange());
1364 return QualType();
1365 }
1366 return resType;
1367}
1368
1369/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1370/// This routine allows us to typecheck complex/recursive expressions
1371/// where the declaration is needed for type checking. Here are some
1372/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1373static Decl *getPrimaryDeclaration(Expr *e) {
1374 switch (e->getStmtClass()) {
1375 case Stmt::DeclRefExprClass:
1376 return cast<DeclRefExpr>(e)->getDecl();
1377 case Stmt::MemberExprClass:
1378 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1379 case Stmt::ArraySubscriptExprClass:
1380 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1381 case Stmt::CallExprClass:
1382 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1383 case Stmt::UnaryOperatorClass:
1384 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1385 case Stmt::ParenExprClass:
1386 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1387 default:
1388 return 0;
1389 }
1390}
1391
1392/// CheckAddressOfOperand - The operand of & must be either a function
1393/// designator or an lvalue designating an object. If it is an lvalue, the
1394/// object cannot be declared with storage class register or be a bit field.
1395/// Note: The usual conversions are *not* applied to the operand of the &
1396/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1397QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1398 Decl *dcl = getPrimaryDeclaration(op);
1399 Expr::isLvalueResult lval = op->isLvalue();
1400
1401 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1402 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1403 ;
1404 else { // FIXME: emit more specific diag...
1405 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1406 op->getSourceRange());
1407 return QualType();
1408 }
1409 } else if (dcl) {
1410 // We have an lvalue with a decl. Make sure the decl is not declared
1411 // with the register storage-class specifier.
1412 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1413 if (vd->getStorageClass() == VarDecl::Register) {
1414 Diag(OpLoc, diag::err_typecheck_address_of_register,
1415 op->getSourceRange());
1416 return QualType();
1417 }
1418 } else
1419 assert(0 && "Unknown/unexpected decl type");
1420
1421 // FIXME: add check for bitfields!
1422 }
1423 // If the operand has type "type", the result has type "pointer to type".
1424 return Context.getPointerType(op->getType());
1425}
1426
1427QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1428 UsualUnaryConversions(op);
1429 QualType qType = op->getType();
1430
Chris Lattner7931f4a2007-07-31 16:53:04 +00001431 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001432 QualType ptype = PT->getPointeeType();
1433 // C99 6.5.3.2p4. "if it points to an object,...".
1434 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1435 // GCC compat: special case 'void *' (treat as warning).
1436 if (ptype->isVoidType()) {
1437 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1438 qType.getAsString(), op->getSourceRange());
1439 } else {
1440 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1441 ptype.getAsString(), op->getSourceRange());
1442 return QualType();
1443 }
1444 }
1445 return ptype;
1446 }
1447 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1448 qType.getAsString(), op->getSourceRange());
1449 return QualType();
1450}
1451
1452static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1453 tok::TokenKind Kind) {
1454 BinaryOperator::Opcode Opc;
1455 switch (Kind) {
1456 default: assert(0 && "Unknown binop!");
1457 case tok::star: Opc = BinaryOperator::Mul; break;
1458 case tok::slash: Opc = BinaryOperator::Div; break;
1459 case tok::percent: Opc = BinaryOperator::Rem; break;
1460 case tok::plus: Opc = BinaryOperator::Add; break;
1461 case tok::minus: Opc = BinaryOperator::Sub; break;
1462 case tok::lessless: Opc = BinaryOperator::Shl; break;
1463 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1464 case tok::lessequal: Opc = BinaryOperator::LE; break;
1465 case tok::less: Opc = BinaryOperator::LT; break;
1466 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1467 case tok::greater: Opc = BinaryOperator::GT; break;
1468 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1469 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1470 case tok::amp: Opc = BinaryOperator::And; break;
1471 case tok::caret: Opc = BinaryOperator::Xor; break;
1472 case tok::pipe: Opc = BinaryOperator::Or; break;
1473 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1474 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1475 case tok::equal: Opc = BinaryOperator::Assign; break;
1476 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1477 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1478 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1479 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1480 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1481 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1482 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1483 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1484 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1485 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1486 case tok::comma: Opc = BinaryOperator::Comma; break;
1487 }
1488 return Opc;
1489}
1490
1491static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1492 tok::TokenKind Kind) {
1493 UnaryOperator::Opcode Opc;
1494 switch (Kind) {
1495 default: assert(0 && "Unknown unary op!");
1496 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1497 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1498 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1499 case tok::star: Opc = UnaryOperator::Deref; break;
1500 case tok::plus: Opc = UnaryOperator::Plus; break;
1501 case tok::minus: Opc = UnaryOperator::Minus; break;
1502 case tok::tilde: Opc = UnaryOperator::Not; break;
1503 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1504 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1505 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1506 case tok::kw___real: Opc = UnaryOperator::Real; break;
1507 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1508 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1509 }
1510 return Opc;
1511}
1512
1513// Binary Operators. 'Tok' is the token for the operator.
1514Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1515 ExprTy *LHS, ExprTy *RHS) {
1516 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1517 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1518
1519 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1520 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1521
1522 QualType ResultTy; // Result type of the binary operator.
1523 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1524
1525 switch (Opc) {
1526 default:
1527 assert(0 && "Unknown binary expr!");
1528 case BinaryOperator::Assign:
1529 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1530 break;
1531 case BinaryOperator::Mul:
1532 case BinaryOperator::Div:
1533 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1534 break;
1535 case BinaryOperator::Rem:
1536 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1537 break;
1538 case BinaryOperator::Add:
1539 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1540 break;
1541 case BinaryOperator::Sub:
1542 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1543 break;
1544 case BinaryOperator::Shl:
1545 case BinaryOperator::Shr:
1546 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1547 break;
1548 case BinaryOperator::LE:
1549 case BinaryOperator::LT:
1550 case BinaryOperator::GE:
1551 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001552 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001553 break;
1554 case BinaryOperator::EQ:
1555 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001556 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001557 break;
1558 case BinaryOperator::And:
1559 case BinaryOperator::Xor:
1560 case BinaryOperator::Or:
1561 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1562 break;
1563 case BinaryOperator::LAnd:
1564 case BinaryOperator::LOr:
1565 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1566 break;
1567 case BinaryOperator::MulAssign:
1568 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001569 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001570 if (!CompTy.isNull())
1571 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1572 break;
1573 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001574 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001575 if (!CompTy.isNull())
1576 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1577 break;
1578 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001579 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001580 if (!CompTy.isNull())
1581 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1582 break;
1583 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001584 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001585 if (!CompTy.isNull())
1586 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1587 break;
1588 case BinaryOperator::ShlAssign:
1589 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001590 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001591 if (!CompTy.isNull())
1592 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1593 break;
1594 case BinaryOperator::AndAssign:
1595 case BinaryOperator::XorAssign:
1596 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001597 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001598 if (!CompTy.isNull())
1599 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1600 break;
1601 case BinaryOperator::Comma:
1602 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1603 break;
1604 }
1605 if (ResultTy.isNull())
1606 return true;
1607 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001608 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001609 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001610 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001611}
1612
1613// Unary Operators. 'Tok' is the token for the operator.
1614Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1615 ExprTy *input) {
1616 Expr *Input = (Expr*)input;
1617 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1618 QualType resultType;
1619 switch (Opc) {
1620 default:
1621 assert(0 && "Unimplemented unary expr!");
1622 case UnaryOperator::PreInc:
1623 case UnaryOperator::PreDec:
1624 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1625 break;
1626 case UnaryOperator::AddrOf:
1627 resultType = CheckAddressOfOperand(Input, OpLoc);
1628 break;
1629 case UnaryOperator::Deref:
1630 resultType = CheckIndirectionOperand(Input, OpLoc);
1631 break;
1632 case UnaryOperator::Plus:
1633 case UnaryOperator::Minus:
1634 UsualUnaryConversions(Input);
1635 resultType = Input->getType();
1636 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1637 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1638 resultType.getAsString());
1639 break;
1640 case UnaryOperator::Not: // bitwise complement
1641 UsualUnaryConversions(Input);
1642 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001643 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1644 if (!resultType->isIntegerType()) {
1645 if (resultType->isComplexType())
1646 // C99 does not support '~' for complex conjugation.
1647 Diag(OpLoc, diag::ext_integer_complement_complex,
1648 resultType.getAsString());
1649 else
1650 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1651 resultType.getAsString());
1652 }
Chris Lattner4b009652007-07-25 00:24:17 +00001653 break;
1654 case UnaryOperator::LNot: // logical negation
1655 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1656 DefaultFunctionArrayConversion(Input);
1657 resultType = Input->getType();
1658 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1659 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1660 resultType.getAsString());
1661 // LNot always has type int. C99 6.5.3.3p5.
1662 resultType = Context.IntTy;
1663 break;
1664 case UnaryOperator::SizeOf:
1665 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1666 break;
1667 case UnaryOperator::AlignOf:
1668 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1669 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001670 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001671 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001672 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001673 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001674 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001675 resultType = Input->getType();
1676 break;
1677 }
1678 if (resultType.isNull())
1679 return true;
1680 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1681}
1682
1683/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1684Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1685 SourceLocation LabLoc,
1686 IdentifierInfo *LabelII) {
1687 // Look up the record for this label identifier.
1688 LabelStmt *&LabelDecl = LabelMap[LabelII];
1689
1690 // If we haven't seen this label yet, create a forward reference.
1691 if (LabelDecl == 0)
1692 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1693
1694 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001695 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1696 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001697}
1698
1699Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1700 SourceLocation RPLoc) { // "({..})"
1701 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1702 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1703 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1704
1705 // FIXME: there are a variety of strange constraints to enforce here, for
1706 // example, it is not possible to goto into a stmt expression apparently.
1707 // More semantic analysis is needed.
1708
1709 // FIXME: the last statement in the compount stmt has its value used. We
1710 // should not warn about it being unused.
1711
1712 // If there are sub stmts in the compound stmt, take the type of the last one
1713 // as the type of the stmtexpr.
1714 QualType Ty = Context.VoidTy;
1715
1716 if (!Compound->body_empty())
1717 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1718 Ty = LastExpr->getType();
1719
1720 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1721}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001722
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001723Sema::ExprResult Sema::ParseBuiltinOffsetOf(SourceLocation BuiltinLoc,
1724 SourceLocation TypeLoc,
1725 TypeTy *argty,
1726 OffsetOfComponent *CompPtr,
1727 unsigned NumComponents,
1728 SourceLocation RPLoc) {
1729 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1730 assert(!ArgTy.isNull() && "Missing type argument!");
1731
1732 // We must have at least one component that refers to the type, and the first
1733 // one is known to be a field designator. Verify that the ArgTy represents
1734 // a struct/union/class.
1735 if (!ArgTy->isRecordType())
1736 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1737
1738 // Otherwise, create a compound literal expression as the base, and
1739 // iteratively process the offsetof designators.
1740 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1741
1742 for (unsigned i = 0; i != NumComponents; ++i) {
1743 const OffsetOfComponent &OC = CompPtr[i];
1744 if (OC.isBrackets) {
1745 // Offset of an array sub-field. TODO: Should we allow vector elements?
1746 const ArrayType *AT = Res->getType()->getAsArrayType();
1747 if (!AT) {
1748 delete Res;
1749 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1750 Res->getType().getAsString());
1751 }
1752
Chris Lattner2af6a802007-08-30 17:59:59 +00001753 // FIXME: C++: Verify that operator[] isn't overloaded.
1754
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001755 // C99 6.5.2.1p1
1756 Expr *Idx = static_cast<Expr*>(OC.U.E);
1757 if (!Idx->getType()->isIntegerType())
1758 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1759 Idx->getSourceRange());
1760
1761 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1762 continue;
1763 }
1764
1765 const RecordType *RC = Res->getType()->getAsRecordType();
1766 if (!RC) {
1767 delete Res;
1768 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1769 Res->getType().getAsString());
1770 }
1771
1772 // Get the decl corresponding to this.
1773 RecordDecl *RD = RC->getDecl();
1774 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1775 if (!MemberDecl)
1776 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1777 OC.U.IdentInfo->getName(),
1778 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001779
1780 // FIXME: C++: Verify that MemberDecl isn't a static field.
1781 // FIXME: Verify that MemberDecl isn't a bitfield.
1782
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001783 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1784 }
1785
1786 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1787 BuiltinLoc);
1788}
1789
1790
Steve Naroff5b528922007-08-01 23:45:51 +00001791Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001792 TypeTy *arg1, TypeTy *arg2,
1793 SourceLocation RPLoc) {
1794 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1795 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1796
1797 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1798
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001799 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001800}
1801
Steve Naroff93c53012007-08-03 21:21:27 +00001802Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1803 ExprTy *expr1, ExprTy *expr2,
1804 SourceLocation RPLoc) {
1805 Expr *CondExpr = static_cast<Expr*>(cond);
1806 Expr *LHSExpr = static_cast<Expr*>(expr1);
1807 Expr *RHSExpr = static_cast<Expr*>(expr2);
1808
1809 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1810
1811 // The conditional expression is required to be a constant expression.
1812 llvm::APSInt condEval(32);
1813 SourceLocation ExpLoc;
1814 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1815 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1816 CondExpr->getSourceRange());
1817
1818 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1819 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1820 RHSExpr->getType();
1821 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1822}
1823
Anders Carlssona66cad42007-08-21 17:43:55 +00001824// TODO: Move this to SemaObjC.cpp
Anders Carlsson8be1d402007-08-22 15:14:15 +00001825Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001826 StringLiteral* S = static_cast<StringLiteral *>(string);
1827
1828 if (CheckBuiltinCFStringArgument(S))
1829 return true;
1830
1831 QualType t = Context.getCFConstantStringType();
1832 t = t.getQualifiedType(QualType::Const);
1833 t = Context.getPointerType(t);
1834
1835 return new ObjCStringLiteral(S, t);
1836}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001837
1838Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1839 SourceLocation LParenLoc,
1840 TypeTy *Ty,
1841 SourceLocation RParenLoc) {
1842 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1843
1844 QualType t = Context.getPointerType(Context.CharTy);
1845 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1846}