blob: bea6e999124d8ec04b9de5609cc3c8e96c2cb2ce [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.
79 if (VD->getInvalidDecl())
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
159 // Get the value in the widest-possible width.
160 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
161
162 if (Literal.GetIntegerValue(ResultVal)) {
163 // If this value didn't fit into uintmax_t, warn and force to ull.
164 Diag(Tok.getLocation(), diag::warn_integer_too_large);
165 t = Context.UnsignedLongLongTy;
166 assert(Context.getTypeSize(t, Tok.getLocation()) ==
167 ResultVal.getBitWidth() && "long long is not intmax_t?");
168 } else {
169 // If this value fits into a ULL, try to figure out what else it fits into
170 // according to the rules of C99 6.4.4.1p5.
171
172 // Octal, Hexadecimal, and integers with a U suffix are allowed to
173 // be an unsigned int.
174 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
175
176 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000177 if (!Literal.isLong && !Literal.isLongLong) {
178 // Are int/unsigned possibilities?
Chris Lattner4b009652007-07-25 00:24:17 +0000179 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
180 // Does it fit in a unsigned int?
181 if (ResultVal.isIntN(IntSize)) {
182 // Does it fit in a signed int?
183 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
184 t = Context.IntTy;
185 else if (AllowUnsigned)
186 t = Context.UnsignedIntTy;
187 }
188
189 if (!t.isNull())
190 ResultVal.trunc(IntSize);
191 }
192
193 // Are long/unsigned long possibilities?
194 if (t.isNull() && !Literal.isLongLong) {
195 unsigned LongSize = Context.getTypeSize(Context.LongTy,
196 Tok.getLocation());
197
198 // Does it fit in a unsigned long?
199 if (ResultVal.isIntN(LongSize)) {
200 // Does it fit in a signed long?
201 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
202 t = Context.LongTy;
203 else if (AllowUnsigned)
204 t = Context.UnsignedLongTy;
205 }
206 if (!t.isNull())
207 ResultVal.trunc(LongSize);
208 }
209
210 // Finally, check long long if needed.
211 if (t.isNull()) {
212 unsigned LongLongSize =
213 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
214
215 // Does it fit in a unsigned long long?
216 if (ResultVal.isIntN(LongLongSize)) {
217 // Does it fit in a signed long long?
218 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
219 t = Context.LongLongTy;
220 else if (AllowUnsigned)
221 t = Context.UnsignedLongLongTy;
222 }
223 }
224
225 // If we still couldn't decide a type, we probably have something that
226 // does not fit in a signed long long, but has no U suffix.
227 if (t.isNull()) {
228 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
229 t = Context.UnsignedLongLongTy;
230 }
231 }
232
Chris Lattner1de66eb2007-08-26 03:42:43 +0000233 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000234 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000235
236 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
237 if (Literal.isImaginary)
238 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
239
240 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000241}
242
243Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
244 ExprTy *Val) {
245 Expr *e = (Expr *)Val;
246 assert((e != 0) && "ParseParenExpr() missing expr");
247 return new ParenExpr(L, R, e);
248}
249
250/// The UsualUnaryConversions() function is *not* called by this routine.
251/// See C99 6.3.2.1p[2-4] for more details.
252QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
253 SourceLocation OpLoc, bool isSizeof) {
254 // C99 6.5.3.4p1:
255 if (isa<FunctionType>(exprType) && isSizeof)
256 // alignof(function) is allowed.
257 Diag(OpLoc, diag::ext_sizeof_function_type);
258 else if (exprType->isVoidType())
259 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
260 else if (exprType->isIncompleteType()) {
261 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
262 diag::err_alignof_incomplete_type,
263 exprType.getAsString());
264 return QualType(); // error
265 }
266 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
267 return Context.getSizeType();
268}
269
270Action::ExprResult Sema::
271ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
272 SourceLocation LPLoc, TypeTy *Ty,
273 SourceLocation RPLoc) {
274 // If error parsing type, ignore.
275 if (Ty == 0) return true;
276
277 // Verify that this is a valid expression.
278 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
279
280 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
281
282 if (resultType.isNull())
283 return true;
284 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
285}
286
Chris Lattner5110ad52007-08-24 21:41:10 +0000287QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000288 DefaultFunctionArrayConversion(V);
289
Chris Lattnera16e42d2007-08-26 05:39:26 +0000290 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000291 if (const ComplexType *CT = V->getType()->getAsComplexType())
292 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000293
294 // Otherwise they pass through real integer and floating point types here.
295 if (V->getType()->isArithmeticType())
296 return V->getType();
297
298 // Reject anything else.
299 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
300 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000301}
302
303
Chris Lattner4b009652007-07-25 00:24:17 +0000304
305Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
306 tok::TokenKind Kind,
307 ExprTy *Input) {
308 UnaryOperator::Opcode Opc;
309 switch (Kind) {
310 default: assert(0 && "Unknown unary op!");
311 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
312 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
313 }
314 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
315 if (result.isNull())
316 return true;
317 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
318}
319
320Action::ExprResult Sema::
321ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
322 ExprTy *Idx, SourceLocation RLoc) {
323 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
324
325 // Perform default conversions.
326 DefaultFunctionArrayConversion(LHSExp);
327 DefaultFunctionArrayConversion(RHSExp);
328
329 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
330
331 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
332 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
333 // in the subscript position. As a result, we need to derive the array base
334 // and index from the expression types.
335 Expr *BaseExpr, *IndexExpr;
336 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000337 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000338 BaseExpr = LHSExp;
339 IndexExpr = RHSExp;
340 // FIXME: need to deal with const...
341 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000342 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000343 // Handle the uncommon case of "123[Ptr]".
344 BaseExpr = RHSExp;
345 IndexExpr = LHSExp;
346 // FIXME: need to deal with const...
347 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000348 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
349 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000350 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000351
352 // Component access limited to variables (reject vec4.rg[1]).
353 if (!isa<DeclRefExpr>(BaseExpr))
354 return Diag(LLoc, diag::err_ocuvector_component_access,
355 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000356 // FIXME: need to deal with const...
357 ResultType = VTy->getElementType();
358 } else {
359 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
360 RHSExp->getSourceRange());
361 }
362 // C99 6.5.2.1p1
363 if (!IndexExpr->getType()->isIntegerType())
364 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
365 IndexExpr->getSourceRange());
366
367 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
368 // the following check catches trying to index a pointer to a function (e.g.
369 // void (*)(int)). Functions are not objects in C99.
370 if (!ResultType->isObjectType())
371 return Diag(BaseExpr->getLocStart(),
372 diag::err_typecheck_subscript_not_object,
373 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
374
375 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
376}
377
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000378QualType Sema::
379CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
380 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000381 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000382
383 // The vector accessor can't exceed the number of elements.
384 const char *compStr = CompName.getName();
385 if (strlen(compStr) > vecType->getNumElements()) {
386 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
387 baseType.getAsString(), SourceRange(CompLoc));
388 return QualType();
389 }
390 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000391 if (vecType->getPointAccessorIdx(*compStr) != -1) {
392 do
393 compStr++;
394 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
395 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
396 do
397 compStr++;
398 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
399 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
400 do
401 compStr++;
402 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
403 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000404
405 if (*compStr) {
406 // We didn't get to the end of the string. This means the component names
407 // didn't come from the same set *or* we encountered an illegal name.
408 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
409 std::string(compStr,compStr+1), SourceRange(CompLoc));
410 return QualType();
411 }
412 // Each component accessor can't exceed the vector type.
413 compStr = CompName.getName();
414 while (*compStr) {
415 if (vecType->isAccessorWithinNumElements(*compStr))
416 compStr++;
417 else
418 break;
419 }
420 if (*compStr) {
421 // We didn't get to the end of the string. This means a component accessor
422 // exceeds the number of elements in the vector.
423 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
424 baseType.getAsString(), SourceRange(CompLoc));
425 return QualType();
426 }
427 // The component accessor looks fine - now we need to compute the actual type.
428 // The vector type is implied by the component accessor. For example,
429 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
430 unsigned CompSize = strlen(CompName.getName());
431 if (CompSize == 1)
432 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000433
434 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
435 // Now look up the TypeDefDecl from the vector type. Without this,
436 // diagostics look bad. We want OCU vector types to appear built-in.
437 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
438 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
439 return Context.getTypedefType(OCUVectorDecls[i]);
440 }
441 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000442}
443
Chris Lattner4b009652007-07-25 00:24:17 +0000444Action::ExprResult Sema::
445ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
446 tok::TokenKind OpKind, SourceLocation MemberLoc,
447 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000448 Expr *BaseExpr = static_cast<Expr *>(Base);
449 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000450
Steve Naroff2cb66382007-07-26 03:11:44 +0000451 QualType BaseType = BaseExpr->getType();
452 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000453
Chris Lattner4b009652007-07-25 00:24:17 +0000454 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000455 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000456 BaseType = PT->getPointeeType();
457 else
458 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
459 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000460 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000461 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000462 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000463 RecordDecl *RDecl = RTy->getDecl();
464 if (RTy->isIncompleteType())
465 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
466 BaseExpr->getSourceRange());
467 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000468 FieldDecl *MemberDecl = RDecl->getMember(&Member);
469 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000470 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
471 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000472 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
473 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000474 // Component access limited to variables (reject vec4.rg.g).
475 if (!isa<DeclRefExpr>(BaseExpr))
476 return Diag(OpLoc, diag::err_ocuvector_component_access,
477 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000478 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
479 if (ret.isNull())
480 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000481 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000482 } else
483 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
484 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000485}
486
487/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
488/// This provides the location of the left/right parens and a list of comma
489/// locations.
490Action::ExprResult Sema::
491ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
492 ExprTy **args, unsigned NumArgsInCall,
493 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
494 Expr *Fn = static_cast<Expr *>(fn);
495 Expr **Args = reinterpret_cast<Expr**>(args);
496 assert(Fn && "no function call expression");
497
498 UsualUnaryConversions(Fn);
499 QualType funcType = Fn->getType();
500
501 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
502 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000503 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000504 if (PT == 0)
505 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
506 SourceRange(Fn->getLocStart(), RParenLoc));
507
Chris Lattner71225142007-07-31 21:27:01 +0000508 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000509 if (funcT == 0)
510 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
511 SourceRange(Fn->getLocStart(), RParenLoc));
512
513 // If a prototype isn't declared, the parser implicitly defines a func decl
514 QualType resultType = funcT->getResultType();
515
516 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
517 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
518 // assignment, to the types of the corresponding parameter, ...
519
520 unsigned NumArgsInProto = proto->getNumArgs();
521 unsigned NumArgsToCheck = NumArgsInCall;
522
523 if (NumArgsInCall < NumArgsInProto)
524 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
525 Fn->getSourceRange());
526 else if (NumArgsInCall > NumArgsInProto) {
527 if (!proto->isVariadic()) {
528 Diag(Args[NumArgsInProto]->getLocStart(),
529 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
530 SourceRange(Args[NumArgsInProto]->getLocStart(),
531 Args[NumArgsInCall-1]->getLocEnd()));
532 }
533 NumArgsToCheck = NumArgsInProto;
534 }
535 // Continue to check argument types (even if we have too few/many args).
536 for (unsigned i = 0; i < NumArgsToCheck; i++) {
537 Expr *argExpr = Args[i];
538 assert(argExpr && "ParseCallExpr(): missing argument expression");
539
540 QualType lhsType = proto->getArgType(i);
541 QualType rhsType = argExpr->getType();
542
Steve Naroff75644062007-07-25 20:45:33 +0000543 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000544 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000545 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000546 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000547 lhsType = Context.getPointerType(lhsType);
548
549 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
550 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000551 if (Args[i] != argExpr) // The expression was converted.
552 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000553 SourceLocation l = argExpr->getLocStart();
554
555 // decode the result (notice that AST's are still created for extensions).
556 switch (result) {
557 case Compatible:
558 break;
559 case PointerFromInt:
560 // check for null pointer constant (C99 6.3.2.3p3)
561 if (!argExpr->isNullPointerConstant(Context)) {
562 Diag(l, diag::ext_typecheck_passing_pointer_int,
563 lhsType.getAsString(), rhsType.getAsString(),
564 Fn->getSourceRange(), argExpr->getSourceRange());
565 }
566 break;
567 case IntFromPointer:
568 Diag(l, diag::ext_typecheck_passing_pointer_int,
569 lhsType.getAsString(), rhsType.getAsString(),
570 Fn->getSourceRange(), argExpr->getSourceRange());
571 break;
572 case IncompatiblePointer:
573 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
574 rhsType.getAsString(), lhsType.getAsString(),
575 Fn->getSourceRange(), argExpr->getSourceRange());
576 break;
577 case CompatiblePointerDiscardsQualifiers:
578 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
579 rhsType.getAsString(), lhsType.getAsString(),
580 Fn->getSourceRange(), argExpr->getSourceRange());
581 break;
582 case Incompatible:
583 return Diag(l, diag::err_typecheck_passing_incompatible,
584 rhsType.getAsString(), lhsType.getAsString(),
585 Fn->getSourceRange(), argExpr->getSourceRange());
586 }
587 }
588 // Even if the types checked, bail if we had the wrong number of arguments.
589 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
590 return true;
591 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000592
593 // Do special checking on direct calls to functions.
594 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
595 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
596 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000597 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args, NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000598 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000599
Chris Lattner4b009652007-07-25 00:24:17 +0000600 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
601}
602
603Action::ExprResult Sema::
604ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
605 SourceLocation RParenLoc, ExprTy *InitExpr) {
606 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
607 QualType literalType = QualType::getFromOpaquePtr(Ty);
608 // FIXME: put back this assert when initializers are worked out.
609 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
610 Expr *literalExpr = static_cast<Expr*>(InitExpr);
611
612 // FIXME: add semantic analysis (C99 6.5.2.5).
613 return new CompoundLiteralExpr(literalType, literalExpr);
614}
615
616Action::ExprResult Sema::
617ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
618 SourceLocation RParenLoc) {
619 // FIXME: add semantic analysis (C99 6.7.8). This involves
620 // knowledge of the object being intialized. As a result, the code for
621 // doing the semantic analysis will likely be located elsewhere (i.e. in
622 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
623 return false; // FIXME instantiate an InitListExpr.
624}
625
626Action::ExprResult Sema::
627ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
628 SourceLocation RParenLoc, ExprTy *Op) {
629 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
630
631 Expr *castExpr = static_cast<Expr*>(Op);
632 QualType castType = QualType::getFromOpaquePtr(Ty);
633
634 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
635 // type needs to be scalar.
636 if (!castType->isScalarType() && !castType->isVoidType()) {
637 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
638 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
639 }
640 if (!castExpr->getType()->isScalarType()) {
641 return Diag(castExpr->getLocStart(),
642 diag::err_typecheck_expect_scalar_operand,
643 castExpr->getType().getAsString(), castExpr->getSourceRange());
644 }
645 return new CastExpr(castType, castExpr, LParenLoc);
646}
647
648inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
649 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
650 UsualUnaryConversions(cond);
651 UsualUnaryConversions(lex);
652 UsualUnaryConversions(rex);
653 QualType condT = cond->getType();
654 QualType lexT = lex->getType();
655 QualType rexT = rex->getType();
656
657 // first, check the condition.
658 if (!condT->isScalarType()) { // C99 6.5.15p2
659 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
660 condT.getAsString());
661 return QualType();
662 }
663 // now check the two expressions.
664 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
665 UsualArithmeticConversions(lex, rex);
666 return lex->getType();
667 }
Chris Lattner71225142007-07-31 21:27:01 +0000668 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
669 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
670
671 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
672 return lexT;
673
Chris Lattner4b009652007-07-25 00:24:17 +0000674 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
675 lexT.getAsString(), rexT.getAsString(),
676 lex->getSourceRange(), rex->getSourceRange());
677 return QualType();
678 }
679 }
680 // C99 6.5.15p3
681 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
682 return lexT;
683 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
684 return rexT;
685
Chris Lattner71225142007-07-31 21:27:01 +0000686 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
687 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
688 // get the "pointed to" types
689 QualType lhptee = LHSPT->getPointeeType();
690 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000691
Chris Lattner71225142007-07-31 21:27:01 +0000692 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
693 if (lhptee->isVoidType() &&
694 (rhptee->isObjectType() || rhptee->isIncompleteType()))
695 return lexT;
696 if (rhptee->isVoidType() &&
697 (lhptee->isObjectType() || lhptee->isIncompleteType()))
698 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000699
Chris Lattner71225142007-07-31 21:27:01 +0000700 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
701 rhptee.getUnqualifiedType())) {
702 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
703 lexT.getAsString(), rexT.getAsString(),
704 lex->getSourceRange(), rex->getSourceRange());
705 return lexT; // FIXME: this is an _ext - is this return o.k?
706 }
707 // The pointer types are compatible.
708 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
709 // differently qualified versions of compatible types, the result type is a
710 // pointer to an appropriately qualified version of the *composite* type.
711 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000712 }
Chris Lattner4b009652007-07-25 00:24:17 +0000713 }
Chris Lattner71225142007-07-31 21:27:01 +0000714
Chris Lattner4b009652007-07-25 00:24:17 +0000715 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
716 return lexT;
717
718 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
719 lexT.getAsString(), rexT.getAsString(),
720 lex->getSourceRange(), rex->getSourceRange());
721 return QualType();
722}
723
724/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
725/// in the case of a the GNU conditional expr extension.
726Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
727 SourceLocation ColonLoc,
728 ExprTy *Cond, ExprTy *LHS,
729 ExprTy *RHS) {
730 Expr *CondExpr = (Expr *) Cond;
731 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
732 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
733 RHSExpr, QuestionLoc);
734 if (result.isNull())
735 return true;
736 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
737}
738
739// promoteExprToType - a helper function to ensure we create exactly one
740// ImplicitCastExpr. As a convenience (to the caller), we return the type.
741static void promoteExprToType(Expr *&expr, QualType type) {
742 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
743 impCast->setType(type);
744 else
745 expr = new ImplicitCastExpr(type, expr);
746 return;
747}
748
749/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
750void Sema::DefaultFunctionArrayConversion(Expr *&e) {
751 QualType t = e->getType();
752 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
753
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000754 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000755 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
756 t = e->getType();
757 }
758 if (t->isFunctionType())
759 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000760 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000761 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
762}
763
764/// UsualUnaryConversion - Performs various conversions that are common to most
765/// operators (C99 6.3). The conversions of array and function types are
766/// sometimes surpressed. For example, the array->pointer conversion doesn't
767/// apply if the array is an argument to the sizeof or address (&) operators.
768/// In these instances, this routine should *not* be called.
769void Sema::UsualUnaryConversions(Expr *&expr) {
770 QualType t = expr->getType();
771 assert(!t.isNull() && "UsualUnaryConversions - missing type");
772
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000773 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000774 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
775 t = expr->getType();
776 }
777 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
778 promoteExprToType(expr, Context.IntTy);
779 else
780 DefaultFunctionArrayConversion(expr);
781}
782
783/// UsualArithmeticConversions - Performs various conversions that are common to
784/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
785/// routine returns the first non-arithmetic type found. The client is
786/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000787QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
788 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000789 if (!isCompAssign) {
790 UsualUnaryConversions(lhsExpr);
791 UsualUnaryConversions(rhsExpr);
792 }
Chris Lattner4b009652007-07-25 00:24:17 +0000793 QualType lhs = lhsExpr->getType();
794 QualType rhs = rhsExpr->getType();
795
796 // If both types are identical, no conversion is needed.
797 if (lhs == rhs)
Steve Naroff8f708362007-08-24 19:07:16 +0000798 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000799
800 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
801 // The caller can deal with this (e.g. pointer + int).
802 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000803 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000804
805 // At this point, we have two different arithmetic types.
806
807 // Handle complex types first (C99 6.3.1.8p1).
808 if (lhs->isComplexType() || rhs->isComplexType()) {
809 // if we have an integer operand, the result is the complex type.
810 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000811 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
812 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000813 }
814 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000815 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
816 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000817 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000818 // This handles complex/complex, complex/float, or float/complex.
819 // When both operands are complex, the shorter operand is converted to the
820 // type of the longer, and that is the type of the result. This corresponds
821 // to what is done when combining two real floating-point operands.
822 // The fun begins when size promotion occur across type domains.
823 // From H&S 6.3.4: When one operand is complex and the other is a real
824 // floating-point type, the less precise type is converted, within it's
825 // real or complex domain, to the precision of the other type. For example,
826 // when combining a "long double" with a "double _Complex", the
827 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000828 int result = Context.compareFloatingType(lhs, rhs);
829
830 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000831 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
832 if (!isCompAssign)
833 promoteExprToType(rhsExpr, rhs);
834 } else if (result < 0) { // The right side is bigger, convert lhs.
835 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
836 if (!isCompAssign)
837 promoteExprToType(lhsExpr, lhs);
838 }
839 // At this point, lhs and rhs have the same rank/size. Now, make sure the
840 // domains match. This is a requirement for our implementation, C99
841 // does not require this promotion.
842 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
843 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000844 if (!isCompAssign)
845 promoteExprToType(lhsExpr, rhs);
846 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000847 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000848 if (!isCompAssign)
849 promoteExprToType(rhsExpr, lhs);
850 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000851 }
Chris Lattner4b009652007-07-25 00:24:17 +0000852 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000853 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000854 }
855 // Now handle "real" floating types (i.e. float, double, long double).
856 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
857 // if we have an integer operand, the result is the real floating type.
858 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000859 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
860 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000861 }
862 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000863 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
864 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000865 }
866 // We have two real floating types, float/complex combos were handled above.
867 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +0000868 int result = Context.compareFloatingType(lhs, rhs);
869
870 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000871 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
872 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000873 }
Steve Naroff45fc9822007-08-27 15:30:22 +0000874 if (result < 0) { // convert the lhs
875 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
876 return rhs;
877 }
878 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +0000879 }
880 // Finally, we have two differing integer types.
881 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000882 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
883 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000884 }
Steve Naroff8f708362007-08-24 19:07:16 +0000885 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
886 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000887}
888
889// CheckPointerTypesForAssignment - This is a very tricky routine (despite
890// being closely modeled after the C99 spec:-). The odd characteristic of this
891// routine is it effectively iqnores the qualifiers on the top level pointee.
892// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
893// FIXME: add a couple examples in this comment.
894Sema::AssignmentCheckResult
895Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
896 QualType lhptee, rhptee;
897
898 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000899 lhptee = lhsType->getAsPointerType()->getPointeeType();
900 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000901
902 // make sure we operate on the canonical type
903 lhptee = lhptee.getCanonicalType();
904 rhptee = rhptee.getCanonicalType();
905
906 AssignmentCheckResult r = Compatible;
907
908 // C99 6.5.16.1p1: This following citation is common to constraints
909 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
910 // qualifiers of the type *pointed to* by the right;
911 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
912 rhptee.getQualifiers())
913 r = CompatiblePointerDiscardsQualifiers;
914
915 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
916 // incomplete type and the other is a pointer to a qualified or unqualified
917 // version of void...
918 if (lhptee.getUnqualifiedType()->isVoidType() &&
919 (rhptee->isObjectType() || rhptee->isIncompleteType()))
920 ;
921 else if (rhptee.getUnqualifiedType()->isVoidType() &&
922 (lhptee->isObjectType() || lhptee->isIncompleteType()))
923 ;
924 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
925 // unqualified versions of compatible types, ...
926 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
927 rhptee.getUnqualifiedType()))
928 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
929 return r;
930}
931
932/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
933/// has code to accommodate several GCC extensions when type checking
934/// pointers. Here are some objectionable examples that GCC considers warnings:
935///
936/// int a, *pint;
937/// short *pshort;
938/// struct foo *pfoo;
939///
940/// pint = pshort; // warning: assignment from incompatible pointer type
941/// a = pint; // warning: assignment makes integer from pointer without a cast
942/// pint = a; // warning: assignment makes pointer from integer without a cast
943/// pint = pfoo; // warning: assignment from incompatible pointer type
944///
945/// As a result, the code for dealing with pointers is more complex than the
946/// C99 spec dictates.
947/// Note: the warning above turn into errors when -pedantic-errors is enabled.
948///
949Sema::AssignmentCheckResult
950Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
951 if (lhsType == rhsType) // common case, fast path...
952 return Compatible;
953
954 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
955 if (lhsType->isVectorType() || rhsType->isVectorType()) {
956 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
957 return Incompatible;
958 }
959 return Compatible;
960 } else if (lhsType->isPointerType()) {
961 if (rhsType->isIntegerType())
962 return PointerFromInt;
963
964 if (rhsType->isPointerType())
965 return CheckPointerTypesForAssignment(lhsType, rhsType);
966 } else if (rhsType->isPointerType()) {
967 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
968 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
969 return IntFromPointer;
970
971 if (lhsType->isPointerType())
972 return CheckPointerTypesForAssignment(lhsType, rhsType);
973 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
974 if (Type::tagTypesAreCompatible(lhsType, rhsType))
975 return Compatible;
976 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
977 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
978 return Compatible;
979 }
980 return Incompatible;
981}
982
983Sema::AssignmentCheckResult
984Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
985 // This check seems unnatural, however it is necessary to insure the proper
986 // conversion of functions/arrays. If the conversion were done for all
987 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
988 // expressions that surpress this implicit conversion (&, sizeof).
989 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000990
991 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +0000992
Steve Naroff0f32f432007-08-24 22:33:52 +0000993 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
994
995 // C99 6.5.16.1p2: The value of the right operand is converted to the
996 // type of the assignment expression.
997 if (rExpr->getType() != lhsType)
998 promoteExprToType(rExpr, lhsType);
999 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001000}
1001
1002Sema::AssignmentCheckResult
1003Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1004 return CheckAssignmentConstraints(lhsType, rhsType);
1005}
1006
1007inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1008 Diag(loc, diag::err_typecheck_invalid_operands,
1009 lex->getType().getAsString(), rex->getType().getAsString(),
1010 lex->getSourceRange(), rex->getSourceRange());
1011}
1012
1013inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1014 Expr *&rex) {
1015 QualType lhsType = lex->getType(), rhsType = rex->getType();
1016
1017 // make sure the vector types are identical.
1018 if (lhsType == rhsType)
1019 return lhsType;
1020 // You cannot convert between vector values of different size.
1021 Diag(loc, diag::err_typecheck_vector_not_convertable,
1022 lex->getType().getAsString(), rex->getType().getAsString(),
1023 lex->getSourceRange(), rex->getSourceRange());
1024 return QualType();
1025}
1026
1027inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001028 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001029{
1030 QualType lhsType = lex->getType(), rhsType = rex->getType();
1031
1032 if (lhsType->isVectorType() || rhsType->isVectorType())
1033 return CheckVectorOperands(loc, lex, rex);
1034
Steve Naroff8f708362007-08-24 19:07:16 +00001035 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001036
Chris Lattner4b009652007-07-25 00:24:17 +00001037 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001038 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001039 InvalidOperands(loc, lex, rex);
1040 return QualType();
1041}
1042
1043inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001044 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001045{
1046 QualType lhsType = lex->getType(), rhsType = rex->getType();
1047
Steve Naroff8f708362007-08-24 19:07:16 +00001048 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001049
Chris Lattner4b009652007-07-25 00:24:17 +00001050 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001051 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001052 InvalidOperands(loc, lex, rex);
1053 return QualType();
1054}
1055
1056inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001057 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001058{
1059 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1060 return CheckVectorOperands(loc, lex, rex);
1061
Steve Naroff8f708362007-08-24 19:07:16 +00001062 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001063
1064 // handle the common case first (both operands are arithmetic).
1065 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001066 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001067
1068 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1069 return lex->getType();
1070 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1071 return rex->getType();
1072 InvalidOperands(loc, lex, rex);
1073 return QualType();
1074}
1075
1076inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001077 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001078{
1079 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1080 return CheckVectorOperands(loc, lex, rex);
1081
Steve Naroff8f708362007-08-24 19:07:16 +00001082 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001083
1084 // handle the common case first (both operands are arithmetic).
1085 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001086 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001087
1088 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001089 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001090 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1091 return Context.getPointerDiffType();
1092 InvalidOperands(loc, lex, rex);
1093 return QualType();
1094}
1095
1096inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001097 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001098{
1099 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1100 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001101 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001102
1103 // handle the common case first (both operands are arithmetic).
1104 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001105 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001106 InvalidOperands(loc, lex, rex);
1107 return QualType();
1108}
1109
Chris Lattner254f3bc2007-08-26 01:18:55 +00001110inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1111 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001112{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001113 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001114 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1115 UsualArithmeticConversions(lex, rex);
1116 else {
1117 UsualUnaryConversions(lex);
1118 UsualUnaryConversions(rex);
1119 }
Chris Lattner4b009652007-07-25 00:24:17 +00001120 QualType lType = lex->getType();
1121 QualType rType = rex->getType();
1122
Chris Lattner254f3bc2007-08-26 01:18:55 +00001123 if (isRelational) {
1124 if (lType->isRealType() && rType->isRealType())
1125 return Context.IntTy;
1126 } else {
1127 if (lType->isArithmeticType() && rType->isArithmeticType())
1128 return Context.IntTy;
1129 }
Chris Lattner4b009652007-07-25 00:24:17 +00001130
Chris Lattner22be8422007-08-26 01:10:14 +00001131 bool LHSIsNull = lex->isNullPointerConstant(Context);
1132 bool RHSIsNull = rex->isNullPointerConstant(Context);
1133
Chris Lattner254f3bc2007-08-26 01:18:55 +00001134 // All of the following pointer related warnings are GCC extensions, except
1135 // when handling null pointer constants. One day, we can consider making them
1136 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001137 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner22be8422007-08-26 01:10:14 +00001138 if (!LHSIsNull && !RHSIsNull &&
Steve Naroffc33c0602007-08-27 04:08:11 +00001139 !Type::pointerTypesAreCompatible(lType.getUnqualifiedType(),
1140 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001141 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1142 lType.getAsString(), rType.getAsString(),
1143 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001144 }
Chris Lattner22be8422007-08-26 01:10:14 +00001145 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001146 return Context.IntTy;
1147 }
1148 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001149 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001150 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1151 lType.getAsString(), rType.getAsString(),
1152 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001153 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001154 return Context.IntTy;
1155 }
1156 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001157 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001158 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1159 lType.getAsString(), rType.getAsString(),
1160 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001161 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001162 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001163 }
1164 InvalidOperands(loc, lex, rex);
1165 return QualType();
1166}
1167
Chris Lattner4b009652007-07-25 00:24:17 +00001168inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001169 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001170{
1171 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1172 return CheckVectorOperands(loc, lex, rex);
1173
Steve Naroff8f708362007-08-24 19:07:16 +00001174 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001175
1176 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001177 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001178 InvalidOperands(loc, lex, rex);
1179 return QualType();
1180}
1181
1182inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1183 Expr *&lex, Expr *&rex, SourceLocation loc)
1184{
1185 UsualUnaryConversions(lex);
1186 UsualUnaryConversions(rex);
1187
1188 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1189 return Context.IntTy;
1190 InvalidOperands(loc, lex, rex);
1191 return QualType();
1192}
1193
1194inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001195 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001196{
1197 QualType lhsType = lex->getType();
1198 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1199 bool hadError = false;
1200 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1201
1202 switch (mlval) { // C99 6.5.16p2
1203 case Expr::MLV_Valid:
1204 break;
1205 case Expr::MLV_ConstQualified:
1206 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1207 hadError = true;
1208 break;
1209 case Expr::MLV_ArrayType:
1210 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1211 lhsType.getAsString(), lex->getSourceRange());
1212 return QualType();
1213 case Expr::MLV_NotObjectType:
1214 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1215 lhsType.getAsString(), lex->getSourceRange());
1216 return QualType();
1217 case Expr::MLV_InvalidExpression:
1218 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1219 lex->getSourceRange());
1220 return QualType();
1221 case Expr::MLV_IncompleteType:
1222 case Expr::MLV_IncompleteVoidType:
1223 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1224 lhsType.getAsString(), lex->getSourceRange());
1225 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001226 case Expr::MLV_DuplicateVectorComponents:
1227 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1228 lex->getSourceRange());
1229 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001230 }
1231 AssignmentCheckResult result;
1232
1233 if (compoundType.isNull())
1234 result = CheckSingleAssignmentConstraints(lhsType, rex);
1235 else
1236 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001237
Chris Lattner4b009652007-07-25 00:24:17 +00001238 // decode the result (notice that extensions still return a type).
1239 switch (result) {
1240 case Compatible:
1241 break;
1242 case Incompatible:
1243 Diag(loc, diag::err_typecheck_assign_incompatible,
1244 lhsType.getAsString(), rhsType.getAsString(),
1245 lex->getSourceRange(), rex->getSourceRange());
1246 hadError = true;
1247 break;
1248 case PointerFromInt:
1249 // check for null pointer constant (C99 6.3.2.3p3)
1250 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1251 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1252 lhsType.getAsString(), rhsType.getAsString(),
1253 lex->getSourceRange(), rex->getSourceRange());
1254 }
1255 break;
1256 case IntFromPointer:
1257 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1258 lhsType.getAsString(), rhsType.getAsString(),
1259 lex->getSourceRange(), rex->getSourceRange());
1260 break;
1261 case IncompatiblePointer:
1262 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1263 lhsType.getAsString(), rhsType.getAsString(),
1264 lex->getSourceRange(), rex->getSourceRange());
1265 break;
1266 case CompatiblePointerDiscardsQualifiers:
1267 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1268 lhsType.getAsString(), rhsType.getAsString(),
1269 lex->getSourceRange(), rex->getSourceRange());
1270 break;
1271 }
1272 // C99 6.5.16p3: The type of an assignment expression is the type of the
1273 // left operand unless the left operand has qualified type, in which case
1274 // it is the unqualified version of the type of the left operand.
1275 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1276 // is converted to the type of the assignment expression (above).
1277 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1278 return hadError ? QualType() : lhsType.getUnqualifiedType();
1279}
1280
1281inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1282 Expr *&lex, Expr *&rex, SourceLocation loc) {
1283 UsualUnaryConversions(rex);
1284 return rex->getType();
1285}
1286
1287/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1288/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1289QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1290 QualType resType = op->getType();
1291 assert(!resType.isNull() && "no type for increment/decrement expression");
1292
Steve Naroffd30e1932007-08-24 17:20:07 +00001293 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner4b009652007-07-25 00:24:17 +00001294 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1295 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1296 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1297 resType.getAsString(), op->getSourceRange());
1298 return QualType();
1299 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001300 } else if (!resType->isRealType()) {
1301 if (resType->isComplexType())
1302 // C99 does not support ++/-- on complex types.
1303 Diag(OpLoc, diag::ext_integer_increment_complex,
1304 resType.getAsString(), op->getSourceRange());
1305 else {
1306 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1307 resType.getAsString(), op->getSourceRange());
1308 return QualType();
1309 }
Chris Lattner4b009652007-07-25 00:24:17 +00001310 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001311 // At this point, we know we have a real, complex or pointer type.
1312 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001313 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1314 if (mlval != Expr::MLV_Valid) {
1315 // FIXME: emit a more precise diagnostic...
1316 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1317 op->getSourceRange());
1318 return QualType();
1319 }
1320 return resType;
1321}
1322
1323/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1324/// This routine allows us to typecheck complex/recursive expressions
1325/// where the declaration is needed for type checking. Here are some
1326/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1327static Decl *getPrimaryDeclaration(Expr *e) {
1328 switch (e->getStmtClass()) {
1329 case Stmt::DeclRefExprClass:
1330 return cast<DeclRefExpr>(e)->getDecl();
1331 case Stmt::MemberExprClass:
1332 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1333 case Stmt::ArraySubscriptExprClass:
1334 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1335 case Stmt::CallExprClass:
1336 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1337 case Stmt::UnaryOperatorClass:
1338 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1339 case Stmt::ParenExprClass:
1340 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1341 default:
1342 return 0;
1343 }
1344}
1345
1346/// CheckAddressOfOperand - The operand of & must be either a function
1347/// designator or an lvalue designating an object. If it is an lvalue, the
1348/// object cannot be declared with storage class register or be a bit field.
1349/// Note: The usual conversions are *not* applied to the operand of the &
1350/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1351QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1352 Decl *dcl = getPrimaryDeclaration(op);
1353 Expr::isLvalueResult lval = op->isLvalue();
1354
1355 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1356 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1357 ;
1358 else { // FIXME: emit more specific diag...
1359 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1360 op->getSourceRange());
1361 return QualType();
1362 }
1363 } else if (dcl) {
1364 // We have an lvalue with a decl. Make sure the decl is not declared
1365 // with the register storage-class specifier.
1366 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1367 if (vd->getStorageClass() == VarDecl::Register) {
1368 Diag(OpLoc, diag::err_typecheck_address_of_register,
1369 op->getSourceRange());
1370 return QualType();
1371 }
1372 } else
1373 assert(0 && "Unknown/unexpected decl type");
1374
1375 // FIXME: add check for bitfields!
1376 }
1377 // If the operand has type "type", the result has type "pointer to type".
1378 return Context.getPointerType(op->getType());
1379}
1380
1381QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1382 UsualUnaryConversions(op);
1383 QualType qType = op->getType();
1384
Chris Lattner7931f4a2007-07-31 16:53:04 +00001385 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001386 QualType ptype = PT->getPointeeType();
1387 // C99 6.5.3.2p4. "if it points to an object,...".
1388 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1389 // GCC compat: special case 'void *' (treat as warning).
1390 if (ptype->isVoidType()) {
1391 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1392 qType.getAsString(), op->getSourceRange());
1393 } else {
1394 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1395 ptype.getAsString(), op->getSourceRange());
1396 return QualType();
1397 }
1398 }
1399 return ptype;
1400 }
1401 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1402 qType.getAsString(), op->getSourceRange());
1403 return QualType();
1404}
1405
1406static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1407 tok::TokenKind Kind) {
1408 BinaryOperator::Opcode Opc;
1409 switch (Kind) {
1410 default: assert(0 && "Unknown binop!");
1411 case tok::star: Opc = BinaryOperator::Mul; break;
1412 case tok::slash: Opc = BinaryOperator::Div; break;
1413 case tok::percent: Opc = BinaryOperator::Rem; break;
1414 case tok::plus: Opc = BinaryOperator::Add; break;
1415 case tok::minus: Opc = BinaryOperator::Sub; break;
1416 case tok::lessless: Opc = BinaryOperator::Shl; break;
1417 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1418 case tok::lessequal: Opc = BinaryOperator::LE; break;
1419 case tok::less: Opc = BinaryOperator::LT; break;
1420 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1421 case tok::greater: Opc = BinaryOperator::GT; break;
1422 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1423 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1424 case tok::amp: Opc = BinaryOperator::And; break;
1425 case tok::caret: Opc = BinaryOperator::Xor; break;
1426 case tok::pipe: Opc = BinaryOperator::Or; break;
1427 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1428 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1429 case tok::equal: Opc = BinaryOperator::Assign; break;
1430 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1431 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1432 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1433 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1434 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1435 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1436 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1437 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1438 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1439 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1440 case tok::comma: Opc = BinaryOperator::Comma; break;
1441 }
1442 return Opc;
1443}
1444
1445static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1446 tok::TokenKind Kind) {
1447 UnaryOperator::Opcode Opc;
1448 switch (Kind) {
1449 default: assert(0 && "Unknown unary op!");
1450 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1451 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1452 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1453 case tok::star: Opc = UnaryOperator::Deref; break;
1454 case tok::plus: Opc = UnaryOperator::Plus; break;
1455 case tok::minus: Opc = UnaryOperator::Minus; break;
1456 case tok::tilde: Opc = UnaryOperator::Not; break;
1457 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1458 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1459 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1460 case tok::kw___real: Opc = UnaryOperator::Real; break;
1461 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1462 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1463 }
1464 return Opc;
1465}
1466
1467// Binary Operators. 'Tok' is the token for the operator.
1468Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1469 ExprTy *LHS, ExprTy *RHS) {
1470 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1471 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1472
1473 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1474 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1475
1476 QualType ResultTy; // Result type of the binary operator.
1477 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1478
1479 switch (Opc) {
1480 default:
1481 assert(0 && "Unknown binary expr!");
1482 case BinaryOperator::Assign:
1483 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1484 break;
1485 case BinaryOperator::Mul:
1486 case BinaryOperator::Div:
1487 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1488 break;
1489 case BinaryOperator::Rem:
1490 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1491 break;
1492 case BinaryOperator::Add:
1493 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1494 break;
1495 case BinaryOperator::Sub:
1496 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1497 break;
1498 case BinaryOperator::Shl:
1499 case BinaryOperator::Shr:
1500 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1501 break;
1502 case BinaryOperator::LE:
1503 case BinaryOperator::LT:
1504 case BinaryOperator::GE:
1505 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001506 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001507 break;
1508 case BinaryOperator::EQ:
1509 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001510 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001511 break;
1512 case BinaryOperator::And:
1513 case BinaryOperator::Xor:
1514 case BinaryOperator::Or:
1515 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1516 break;
1517 case BinaryOperator::LAnd:
1518 case BinaryOperator::LOr:
1519 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1520 break;
1521 case BinaryOperator::MulAssign:
1522 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001523 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001524 if (!CompTy.isNull())
1525 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1526 break;
1527 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001528 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001529 if (!CompTy.isNull())
1530 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1531 break;
1532 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001533 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001534 if (!CompTy.isNull())
1535 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1536 break;
1537 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001538 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001539 if (!CompTy.isNull())
1540 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1541 break;
1542 case BinaryOperator::ShlAssign:
1543 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001544 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001545 if (!CompTy.isNull())
1546 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1547 break;
1548 case BinaryOperator::AndAssign:
1549 case BinaryOperator::XorAssign:
1550 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001551 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001552 if (!CompTy.isNull())
1553 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1554 break;
1555 case BinaryOperator::Comma:
1556 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1557 break;
1558 }
1559 if (ResultTy.isNull())
1560 return true;
1561 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001562 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001563 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001564 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001565}
1566
1567// Unary Operators. 'Tok' is the token for the operator.
1568Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1569 ExprTy *input) {
1570 Expr *Input = (Expr*)input;
1571 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1572 QualType resultType;
1573 switch (Opc) {
1574 default:
1575 assert(0 && "Unimplemented unary expr!");
1576 case UnaryOperator::PreInc:
1577 case UnaryOperator::PreDec:
1578 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1579 break;
1580 case UnaryOperator::AddrOf:
1581 resultType = CheckAddressOfOperand(Input, OpLoc);
1582 break;
1583 case UnaryOperator::Deref:
1584 resultType = CheckIndirectionOperand(Input, OpLoc);
1585 break;
1586 case UnaryOperator::Plus:
1587 case UnaryOperator::Minus:
1588 UsualUnaryConversions(Input);
1589 resultType = Input->getType();
1590 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1591 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1592 resultType.getAsString());
1593 break;
1594 case UnaryOperator::Not: // bitwise complement
1595 UsualUnaryConversions(Input);
1596 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001597 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1598 if (!resultType->isIntegerType()) {
1599 if (resultType->isComplexType())
1600 // C99 does not support '~' for complex conjugation.
1601 Diag(OpLoc, diag::ext_integer_complement_complex,
1602 resultType.getAsString());
1603 else
1604 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1605 resultType.getAsString());
1606 }
Chris Lattner4b009652007-07-25 00:24:17 +00001607 break;
1608 case UnaryOperator::LNot: // logical negation
1609 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1610 DefaultFunctionArrayConversion(Input);
1611 resultType = Input->getType();
1612 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1613 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1614 resultType.getAsString());
1615 // LNot always has type int. C99 6.5.3.3p5.
1616 resultType = Context.IntTy;
1617 break;
1618 case UnaryOperator::SizeOf:
1619 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1620 break;
1621 case UnaryOperator::AlignOf:
1622 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1623 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001624 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001625 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001626 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001627 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001628 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001629 resultType = Input->getType();
1630 break;
1631 }
1632 if (resultType.isNull())
1633 return true;
1634 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1635}
1636
1637/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1638Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1639 SourceLocation LabLoc,
1640 IdentifierInfo *LabelII) {
1641 // Look up the record for this label identifier.
1642 LabelStmt *&LabelDecl = LabelMap[LabelII];
1643
1644 // If we haven't seen this label yet, create a forward reference.
1645 if (LabelDecl == 0)
1646 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1647
1648 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001649 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1650 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001651}
1652
1653Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1654 SourceLocation RPLoc) { // "({..})"
1655 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1656 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1657 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1658
1659 // FIXME: there are a variety of strange constraints to enforce here, for
1660 // example, it is not possible to goto into a stmt expression apparently.
1661 // More semantic analysis is needed.
1662
1663 // FIXME: the last statement in the compount stmt has its value used. We
1664 // should not warn about it being unused.
1665
1666 // If there are sub stmts in the compound stmt, take the type of the last one
1667 // as the type of the stmtexpr.
1668 QualType Ty = Context.VoidTy;
1669
1670 if (!Compound->body_empty())
1671 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1672 Ty = LastExpr->getType();
1673
1674 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1675}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001676
Steve Naroff5b528922007-08-01 23:45:51 +00001677Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001678 TypeTy *arg1, TypeTy *arg2,
1679 SourceLocation RPLoc) {
1680 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1681 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1682
1683 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1684
Steve Naroff5b528922007-08-01 23:45:51 +00001685 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001686}
1687
Steve Naroff93c53012007-08-03 21:21:27 +00001688Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1689 ExprTy *expr1, ExprTy *expr2,
1690 SourceLocation RPLoc) {
1691 Expr *CondExpr = static_cast<Expr*>(cond);
1692 Expr *LHSExpr = static_cast<Expr*>(expr1);
1693 Expr *RHSExpr = static_cast<Expr*>(expr2);
1694
1695 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1696
1697 // The conditional expression is required to be a constant expression.
1698 llvm::APSInt condEval(32);
1699 SourceLocation ExpLoc;
1700 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1701 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1702 CondExpr->getSourceRange());
1703
1704 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1705 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1706 RHSExpr->getType();
1707 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1708}
1709
Anders Carlssona66cad42007-08-21 17:43:55 +00001710// TODO: Move this to SemaObjC.cpp
Anders Carlsson8be1d402007-08-22 15:14:15 +00001711Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001712 StringLiteral* S = static_cast<StringLiteral *>(string);
1713
1714 if (CheckBuiltinCFStringArgument(S))
1715 return true;
1716
1717 QualType t = Context.getCFConstantStringType();
1718 t = t.getQualifiedType(QualType::Const);
1719 t = Context.getPointerType(t);
1720
1721 return new ObjCStringLiteral(S, t);
1722}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001723
1724Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1725 SourceLocation LParenLoc,
1726 TypeTy *Ty,
1727 SourceLocation RParenLoc) {
1728 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1729
1730 QualType t = Context.getPointerType(Context.CharTy);
1731 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1732}