blob: 8a3576aaf3a242e0ead26add7146cf770672c627 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/Expr.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/LiteralSupport.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/SmallString.h"
25using namespace clang;
26
27/// ParseStringLiteral - The specified tokens were lexed as pasted string
28/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
29/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
30/// multiple tokens. However, the common case is that StringToks points to one
31/// string.
32///
33Action::ExprResult
34Sema::ParseStringLiteral(const Token *StringToks, unsigned NumStringToks) {
35 assert(NumStringToks && "Must have at least one string!");
36
37 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
38 if (Literal.hadError)
39 return ExprResult(true);
40
41 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
42 for (unsigned i = 0; i != NumStringToks; ++i)
43 StringTokLocs.push_back(StringToks[i].getLocation());
44
45 // FIXME: handle wchar_t
46 QualType t = Context.getPointerType(Context.CharTy);
47
48 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
49 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
50 Literal.AnyWide, t, StringToks[0].getLocation(),
51 StringToks[NumStringToks-1].getLocation());
52}
53
54
55/// ParseIdentifierExpr - The parser read an identifier in expression context,
56/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
57/// identifier is used in an function call context.
58Sema::ExprResult Sema::ParseIdentifierExpr(Scope *S, SourceLocation Loc,
59 IdentifierInfo &II,
60 bool HasTrailingLParen) {
61 // Could be enum-constant or decl.
62 Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
63 if (D == 0) {
64 // Otherwise, this could be an implicitly declared function reference (legal
65 // in C90, extension in C99).
66 if (HasTrailingLParen &&
67 // Not in C++.
68 !getLangOptions().CPlusPlus)
69 D = ImplicitlyDefineFunction(Loc, II, S);
70 else {
71 // If this name wasn't predeclared and if this is not a function call,
72 // diagnose the problem.
73 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
74 }
75 }
Chris Lattner4b009652007-07-25 00:24:17 +000076 if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
77 return new DeclRefExpr(VD, VD->getType(), Loc);
78 if (isa<TypedefDecl>(D))
79 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
80
81 assert(0 && "Invalid decl");
82 abort();
83}
84
85Sema::ExprResult Sema::ParsePreDefinedExpr(SourceLocation Loc,
86 tok::TokenKind Kind) {
87 PreDefinedExpr::IdentType IT;
88
89 switch (Kind) {
90 default:
91 assert(0 && "Unknown simple primary expr!");
92 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
93 IT = PreDefinedExpr::Func;
94 break;
95 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
96 IT = PreDefinedExpr::Function;
97 break;
98 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
99 IT = PreDefinedExpr::PrettyFunction;
100 break;
101 }
102
103 // Pre-defined identifiers are always of type char *.
104 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
105}
106
107Sema::ExprResult Sema::ParseCharacterConstant(const Token &Tok) {
108 llvm::SmallString<16> CharBuffer;
109 CharBuffer.resize(Tok.getLength());
110 const char *ThisTokBegin = &CharBuffer[0];
111 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
112
113 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
114 Tok.getLocation(), PP);
115 if (Literal.hadError())
116 return ExprResult(true);
117 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
118 Tok.getLocation());
119}
120
121Action::ExprResult Sema::ParseNumericConstant(const Token &Tok) {
122 // fast path for a single digit (which is quite common). A single digit
123 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
124 if (Tok.getLength() == 1) {
125 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
126
127 unsigned IntSize = Context.getTypeSize(Context.IntTy, Tok.getLocation());
128 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
129 Context.IntTy,
130 Tok.getLocation()));
131 }
132 llvm::SmallString<512> IntegerBuffer;
133 IntegerBuffer.resize(Tok.getLength());
134 const char *ThisTokBegin = &IntegerBuffer[0];
135
136 // Get the spelling of the token, which eliminates trigraphs, etc.
137 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
138 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
139 Tok.getLocation(), PP);
140 if (Literal.hadError)
141 return ExprResult(true);
142
143 if (Literal.isIntegerLiteral()) {
144 QualType t;
145
146 // Get the value in the widest-possible width.
147 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
148
149 if (Literal.GetIntegerValue(ResultVal)) {
150 // If this value didn't fit into uintmax_t, warn and force to ull.
151 Diag(Tok.getLocation(), diag::warn_integer_too_large);
152 t = Context.UnsignedLongLongTy;
153 assert(Context.getTypeSize(t, Tok.getLocation()) ==
154 ResultVal.getBitWidth() && "long long is not intmax_t?");
155 } else {
156 // If this value fits into a ULL, try to figure out what else it fits into
157 // according to the rules of C99 6.4.4.1p5.
158
159 // Octal, Hexadecimal, and integers with a U suffix are allowed to
160 // be an unsigned int.
161 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
162
163 // Check from smallest to largest, picking the smallest type we can.
164 if (!Literal.isLong) { // Are int/unsigned possibilities?
165 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
166 // Does it fit in a unsigned int?
167 if (ResultVal.isIntN(IntSize)) {
168 // Does it fit in a signed int?
169 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
170 t = Context.IntTy;
171 else if (AllowUnsigned)
172 t = Context.UnsignedIntTy;
173 }
174
175 if (!t.isNull())
176 ResultVal.trunc(IntSize);
177 }
178
179 // Are long/unsigned long possibilities?
180 if (t.isNull() && !Literal.isLongLong) {
181 unsigned LongSize = Context.getTypeSize(Context.LongTy,
182 Tok.getLocation());
183
184 // Does it fit in a unsigned long?
185 if (ResultVal.isIntN(LongSize)) {
186 // Does it fit in a signed long?
187 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
188 t = Context.LongTy;
189 else if (AllowUnsigned)
190 t = Context.UnsignedLongTy;
191 }
192 if (!t.isNull())
193 ResultVal.trunc(LongSize);
194 }
195
196 // Finally, check long long if needed.
197 if (t.isNull()) {
198 unsigned LongLongSize =
199 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
200
201 // Does it fit in a unsigned long long?
202 if (ResultVal.isIntN(LongLongSize)) {
203 // Does it fit in a signed long long?
204 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
205 t = Context.LongLongTy;
206 else if (AllowUnsigned)
207 t = Context.UnsignedLongLongTy;
208 }
209 }
210
211 // If we still couldn't decide a type, we probably have something that
212 // does not fit in a signed long long, but has no U suffix.
213 if (t.isNull()) {
214 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
215 t = Context.UnsignedLongLongTy;
216 }
217 }
218
219 return new IntegerLiteral(ResultVal, t, Tok.getLocation());
220 } else if (Literal.isFloatingLiteral()) {
221 // FIXME: handle float values > 32 (including compute the real type...).
222 return new FloatingLiteral(Literal.GetFloatValue(), Context.FloatTy,
223 Tok.getLocation());
224 }
225 return ExprResult(true);
226}
227
228Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
229 ExprTy *Val) {
230 Expr *e = (Expr *)Val;
231 assert((e != 0) && "ParseParenExpr() missing expr");
232 return new ParenExpr(L, R, e);
233}
234
235/// The UsualUnaryConversions() function is *not* called by this routine.
236/// See C99 6.3.2.1p[2-4] for more details.
237QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
238 SourceLocation OpLoc, bool isSizeof) {
239 // C99 6.5.3.4p1:
240 if (isa<FunctionType>(exprType) && isSizeof)
241 // alignof(function) is allowed.
242 Diag(OpLoc, diag::ext_sizeof_function_type);
243 else if (exprType->isVoidType())
244 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
245 else if (exprType->isIncompleteType()) {
246 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
247 diag::err_alignof_incomplete_type,
248 exprType.getAsString());
249 return QualType(); // error
250 }
251 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
252 return Context.getSizeType();
253}
254
255Action::ExprResult Sema::
256ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
257 SourceLocation LPLoc, TypeTy *Ty,
258 SourceLocation RPLoc) {
259 // If error parsing type, ignore.
260 if (Ty == 0) return true;
261
262 // Verify that this is a valid expression.
263 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
264
265 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
266
267 if (resultType.isNull())
268 return true;
269 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
270}
271
272
273Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
274 tok::TokenKind Kind,
275 ExprTy *Input) {
276 UnaryOperator::Opcode Opc;
277 switch (Kind) {
278 default: assert(0 && "Unknown unary op!");
279 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
280 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
281 }
282 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
283 if (result.isNull())
284 return true;
285 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
286}
287
288Action::ExprResult Sema::
289ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
290 ExprTy *Idx, SourceLocation RLoc) {
291 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
292
293 // Perform default conversions.
294 DefaultFunctionArrayConversion(LHSExp);
295 DefaultFunctionArrayConversion(RHSExp);
296
297 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
298
299 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
300 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
301 // in the subscript position. As a result, we need to derive the array base
302 // and index from the expression types.
303 Expr *BaseExpr, *IndexExpr;
304 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000305 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000306 BaseExpr = LHSExp;
307 IndexExpr = RHSExp;
308 // FIXME: need to deal with const...
309 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000310 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000311 // Handle the uncommon case of "123[Ptr]".
312 BaseExpr = RHSExp;
313 IndexExpr = LHSExp;
314 // FIXME: need to deal with const...
315 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000316 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
317 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000318 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000319
320 // Component access limited to variables (reject vec4.rg[1]).
321 if (!isa<DeclRefExpr>(BaseExpr))
322 return Diag(LLoc, diag::err_ocuvector_component_access,
323 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000324 // FIXME: need to deal with const...
325 ResultType = VTy->getElementType();
326 } else {
327 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
328 RHSExp->getSourceRange());
329 }
330 // C99 6.5.2.1p1
331 if (!IndexExpr->getType()->isIntegerType())
332 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
333 IndexExpr->getSourceRange());
334
335 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
336 // the following check catches trying to index a pointer to a function (e.g.
337 // void (*)(int)). Functions are not objects in C99.
338 if (!ResultType->isObjectType())
339 return Diag(BaseExpr->getLocStart(),
340 diag::err_typecheck_subscript_not_object,
341 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
342
343 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
344}
345
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000346QualType Sema::
347CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
348 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000349 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000350
351 // The vector accessor can't exceed the number of elements.
352 const char *compStr = CompName.getName();
353 if (strlen(compStr) > vecType->getNumElements()) {
354 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
355 baseType.getAsString(), SourceRange(CompLoc));
356 return QualType();
357 }
358 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000359 if (vecType->getPointAccessorIdx(*compStr) != -1) {
360 do
361 compStr++;
362 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
363 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
364 do
365 compStr++;
366 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
367 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
368 do
369 compStr++;
370 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
371 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000372
373 if (*compStr) {
374 // We didn't get to the end of the string. This means the component names
375 // didn't come from the same set *or* we encountered an illegal name.
376 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
377 std::string(compStr,compStr+1), SourceRange(CompLoc));
378 return QualType();
379 }
380 // Each component accessor can't exceed the vector type.
381 compStr = CompName.getName();
382 while (*compStr) {
383 if (vecType->isAccessorWithinNumElements(*compStr))
384 compStr++;
385 else
386 break;
387 }
388 if (*compStr) {
389 // We didn't get to the end of the string. This means a component accessor
390 // exceeds the number of elements in the vector.
391 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
392 baseType.getAsString(), SourceRange(CompLoc));
393 return QualType();
394 }
395 // The component accessor looks fine - now we need to compute the actual type.
396 // The vector type is implied by the component accessor. For example,
397 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
398 unsigned CompSize = strlen(CompName.getName());
399 if (CompSize == 1)
400 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000401
402 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
403 // Now look up the TypeDefDecl from the vector type. Without this,
404 // diagostics look bad. We want OCU vector types to appear built-in.
405 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
406 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
407 return Context.getTypedefType(OCUVectorDecls[i]);
408 }
409 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000410}
411
Chris Lattner4b009652007-07-25 00:24:17 +0000412Action::ExprResult Sema::
413ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
414 tok::TokenKind OpKind, SourceLocation MemberLoc,
415 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000416 Expr *BaseExpr = static_cast<Expr *>(Base);
417 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000418
Steve Naroff2cb66382007-07-26 03:11:44 +0000419 QualType BaseType = BaseExpr->getType();
420 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000421
Chris Lattner4b009652007-07-25 00:24:17 +0000422 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000423 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000424 BaseType = PT->getPointeeType();
425 else
426 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
427 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000428 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000429 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000430 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000431 RecordDecl *RDecl = RTy->getDecl();
432 if (RTy->isIncompleteType())
433 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
434 BaseExpr->getSourceRange());
435 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000436 FieldDecl *MemberDecl = RDecl->getMember(&Member);
437 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000438 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
439 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000440 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
441 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000442 // Component access limited to variables (reject vec4.rg.g).
443 if (!isa<DeclRefExpr>(BaseExpr))
444 return Diag(OpLoc, diag::err_ocuvector_component_access,
445 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000446 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
447 if (ret.isNull())
448 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000449 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000450 } else
451 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
452 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000453}
454
455/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
456/// This provides the location of the left/right parens and a list of comma
457/// locations.
458Action::ExprResult Sema::
459ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
460 ExprTy **args, unsigned NumArgsInCall,
461 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
462 Expr *Fn = static_cast<Expr *>(fn);
463 Expr **Args = reinterpret_cast<Expr**>(args);
464 assert(Fn && "no function call expression");
465
466 UsualUnaryConversions(Fn);
467 QualType funcType = Fn->getType();
468
469 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
470 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000471 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000472 if (PT == 0)
473 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
474 SourceRange(Fn->getLocStart(), RParenLoc));
475
Chris Lattner71225142007-07-31 21:27:01 +0000476 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000477 if (funcT == 0)
478 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
479 SourceRange(Fn->getLocStart(), RParenLoc));
480
481 // If a prototype isn't declared, the parser implicitly defines a func decl
482 QualType resultType = funcT->getResultType();
483
484 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
485 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
486 // assignment, to the types of the corresponding parameter, ...
487
488 unsigned NumArgsInProto = proto->getNumArgs();
489 unsigned NumArgsToCheck = NumArgsInCall;
490
491 if (NumArgsInCall < NumArgsInProto)
492 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
493 Fn->getSourceRange());
494 else if (NumArgsInCall > NumArgsInProto) {
495 if (!proto->isVariadic()) {
496 Diag(Args[NumArgsInProto]->getLocStart(),
497 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
498 SourceRange(Args[NumArgsInProto]->getLocStart(),
499 Args[NumArgsInCall-1]->getLocEnd()));
500 }
501 NumArgsToCheck = NumArgsInProto;
502 }
503 // Continue to check argument types (even if we have too few/many args).
504 for (unsigned i = 0; i < NumArgsToCheck; i++) {
505 Expr *argExpr = Args[i];
506 assert(argExpr && "ParseCallExpr(): missing argument expression");
507
508 QualType lhsType = proto->getArgType(i);
509 QualType rhsType = argExpr->getType();
510
Steve Naroff75644062007-07-25 20:45:33 +0000511 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000512 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000513 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000514 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000515 lhsType = Context.getPointerType(lhsType);
516
517 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
518 argExpr);
519 SourceLocation l = argExpr->getLocStart();
520
521 // decode the result (notice that AST's are still created for extensions).
522 switch (result) {
523 case Compatible:
524 break;
525 case PointerFromInt:
526 // check for null pointer constant (C99 6.3.2.3p3)
527 if (!argExpr->isNullPointerConstant(Context)) {
528 Diag(l, diag::ext_typecheck_passing_pointer_int,
529 lhsType.getAsString(), rhsType.getAsString(),
530 Fn->getSourceRange(), argExpr->getSourceRange());
531 }
532 break;
533 case IntFromPointer:
534 Diag(l, diag::ext_typecheck_passing_pointer_int,
535 lhsType.getAsString(), rhsType.getAsString(),
536 Fn->getSourceRange(), argExpr->getSourceRange());
537 break;
538 case IncompatiblePointer:
539 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
540 rhsType.getAsString(), lhsType.getAsString(),
541 Fn->getSourceRange(), argExpr->getSourceRange());
542 break;
543 case CompatiblePointerDiscardsQualifiers:
544 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
545 rhsType.getAsString(), lhsType.getAsString(),
546 Fn->getSourceRange(), argExpr->getSourceRange());
547 break;
548 case Incompatible:
549 return Diag(l, diag::err_typecheck_passing_incompatible,
550 rhsType.getAsString(), lhsType.getAsString(),
551 Fn->getSourceRange(), argExpr->getSourceRange());
552 }
553 }
554 // Even if the types checked, bail if we had the wrong number of arguments.
555 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
556 return true;
557 }
558 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
559}
560
561Action::ExprResult Sema::
562ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
563 SourceLocation RParenLoc, ExprTy *InitExpr) {
564 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
565 QualType literalType = QualType::getFromOpaquePtr(Ty);
566 // FIXME: put back this assert when initializers are worked out.
567 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
568 Expr *literalExpr = static_cast<Expr*>(InitExpr);
569
570 // FIXME: add semantic analysis (C99 6.5.2.5).
571 return new CompoundLiteralExpr(literalType, literalExpr);
572}
573
574Action::ExprResult Sema::
575ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
576 SourceLocation RParenLoc) {
577 // FIXME: add semantic analysis (C99 6.7.8). This involves
578 // knowledge of the object being intialized. As a result, the code for
579 // doing the semantic analysis will likely be located elsewhere (i.e. in
580 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
581 return false; // FIXME instantiate an InitListExpr.
582}
583
584Action::ExprResult Sema::
585ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
586 SourceLocation RParenLoc, ExprTy *Op) {
587 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
588
589 Expr *castExpr = static_cast<Expr*>(Op);
590 QualType castType = QualType::getFromOpaquePtr(Ty);
591
592 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
593 // type needs to be scalar.
594 if (!castType->isScalarType() && !castType->isVoidType()) {
595 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
596 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
597 }
598 if (!castExpr->getType()->isScalarType()) {
599 return Diag(castExpr->getLocStart(),
600 diag::err_typecheck_expect_scalar_operand,
601 castExpr->getType().getAsString(), castExpr->getSourceRange());
602 }
603 return new CastExpr(castType, castExpr, LParenLoc);
604}
605
606inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
607 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
608 UsualUnaryConversions(cond);
609 UsualUnaryConversions(lex);
610 UsualUnaryConversions(rex);
611 QualType condT = cond->getType();
612 QualType lexT = lex->getType();
613 QualType rexT = rex->getType();
614
615 // first, check the condition.
616 if (!condT->isScalarType()) { // C99 6.5.15p2
617 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
618 condT.getAsString());
619 return QualType();
620 }
621 // now check the two expressions.
622 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
623 UsualArithmeticConversions(lex, rex);
624 return lex->getType();
625 }
Chris Lattner71225142007-07-31 21:27:01 +0000626 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
627 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
628
629 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
630 return lexT;
631
Chris Lattner4b009652007-07-25 00:24:17 +0000632 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
633 lexT.getAsString(), rexT.getAsString(),
634 lex->getSourceRange(), rex->getSourceRange());
635 return QualType();
636 }
637 }
638 // C99 6.5.15p3
639 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
640 return lexT;
641 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
642 return rexT;
643
Chris Lattner71225142007-07-31 21:27:01 +0000644 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
645 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
646 // get the "pointed to" types
647 QualType lhptee = LHSPT->getPointeeType();
648 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000649
Chris Lattner71225142007-07-31 21:27:01 +0000650 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
651 if (lhptee->isVoidType() &&
652 (rhptee->isObjectType() || rhptee->isIncompleteType()))
653 return lexT;
654 if (rhptee->isVoidType() &&
655 (lhptee->isObjectType() || lhptee->isIncompleteType()))
656 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000657
Chris Lattner71225142007-07-31 21:27:01 +0000658 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
659 rhptee.getUnqualifiedType())) {
660 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
661 lexT.getAsString(), rexT.getAsString(),
662 lex->getSourceRange(), rex->getSourceRange());
663 return lexT; // FIXME: this is an _ext - is this return o.k?
664 }
665 // The pointer types are compatible.
666 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
667 // differently qualified versions of compatible types, the result type is a
668 // pointer to an appropriately qualified version of the *composite* type.
669 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000670 }
Chris Lattner4b009652007-07-25 00:24:17 +0000671 }
Chris Lattner71225142007-07-31 21:27:01 +0000672
Chris Lattner4b009652007-07-25 00:24:17 +0000673 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
674 return lexT;
675
676 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
677 lexT.getAsString(), rexT.getAsString(),
678 lex->getSourceRange(), rex->getSourceRange());
679 return QualType();
680}
681
682/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
683/// in the case of a the GNU conditional expr extension.
684Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
685 SourceLocation ColonLoc,
686 ExprTy *Cond, ExprTy *LHS,
687 ExprTy *RHS) {
688 Expr *CondExpr = (Expr *) Cond;
689 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
690 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
691 RHSExpr, QuestionLoc);
692 if (result.isNull())
693 return true;
694 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
695}
696
697// promoteExprToType - a helper function to ensure we create exactly one
698// ImplicitCastExpr. As a convenience (to the caller), we return the type.
699static void promoteExprToType(Expr *&expr, QualType type) {
700 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
701 impCast->setType(type);
702 else
703 expr = new ImplicitCastExpr(type, expr);
704 return;
705}
706
707/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
708void Sema::DefaultFunctionArrayConversion(Expr *&e) {
709 QualType t = e->getType();
710 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
711
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000712 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000713 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
714 t = e->getType();
715 }
716 if (t->isFunctionType())
717 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000718 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000719 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
720}
721
722/// UsualUnaryConversion - Performs various conversions that are common to most
723/// operators (C99 6.3). The conversions of array and function types are
724/// sometimes surpressed. For example, the array->pointer conversion doesn't
725/// apply if the array is an argument to the sizeof or address (&) operators.
726/// In these instances, this routine should *not* be called.
727void Sema::UsualUnaryConversions(Expr *&expr) {
728 QualType t = expr->getType();
729 assert(!t.isNull() && "UsualUnaryConversions - missing type");
730
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000731 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000732 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
733 t = expr->getType();
734 }
735 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
736 promoteExprToType(expr, Context.IntTy);
737 else
738 DefaultFunctionArrayConversion(expr);
739}
740
741/// UsualArithmeticConversions - Performs various conversions that are common to
742/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
743/// routine returns the first non-arithmetic type found. The client is
744/// responsible for emitting appropriate error diagnostics.
745void Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr) {
746 UsualUnaryConversions(lhsExpr);
747 UsualUnaryConversions(rhsExpr);
748
749 QualType lhs = lhsExpr->getType();
750 QualType rhs = rhsExpr->getType();
751
752 // If both types are identical, no conversion is needed.
753 if (lhs == rhs)
754 return;
755
756 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
757 // The caller can deal with this (e.g. pointer + int).
758 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
759 return;
760
761 // At this point, we have two different arithmetic types.
762
763 // Handle complex types first (C99 6.3.1.8p1).
764 if (lhs->isComplexType() || rhs->isComplexType()) {
765 // if we have an integer operand, the result is the complex type.
766 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
767 promoteExprToType(rhsExpr, lhs);
768 return;
769 }
770 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
771 promoteExprToType(lhsExpr, rhs);
772 return;
773 }
774 // Two complex types. Convert the smaller operand to the bigger result.
775 if (Context.maxComplexType(lhs, rhs) == lhs) { // convert the rhs
776 promoteExprToType(rhsExpr, lhs);
777 return;
778 }
779 promoteExprToType(lhsExpr, rhs); // convert the lhs
780 return;
781 }
782 // Now handle "real" floating types (i.e. float, double, long double).
783 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
784 // if we have an integer operand, the result is the real floating type.
785 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
786 promoteExprToType(rhsExpr, lhs);
787 return;
788 }
789 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
790 promoteExprToType(lhsExpr, rhs);
791 return;
792 }
793 // We have two real floating types, float/complex combos were handled above.
794 // Convert the smaller operand to the bigger result.
795 if (Context.maxFloatingType(lhs, rhs) == lhs) { // convert the rhs
796 promoteExprToType(rhsExpr, lhs);
797 return;
798 }
799 promoteExprToType(lhsExpr, rhs); // convert the lhs
800 return;
801 }
802 // Finally, we have two differing integer types.
803 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
804 promoteExprToType(rhsExpr, lhs);
805 return;
806 }
807 promoteExprToType(lhsExpr, rhs); // convert the lhs
808 return;
809}
810
811// CheckPointerTypesForAssignment - This is a very tricky routine (despite
812// being closely modeled after the C99 spec:-). The odd characteristic of this
813// routine is it effectively iqnores the qualifiers on the top level pointee.
814// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
815// FIXME: add a couple examples in this comment.
816Sema::AssignmentCheckResult
817Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
818 QualType lhptee, rhptee;
819
820 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000821 lhptee = lhsType->getAsPointerType()->getPointeeType();
822 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000823
824 // make sure we operate on the canonical type
825 lhptee = lhptee.getCanonicalType();
826 rhptee = rhptee.getCanonicalType();
827
828 AssignmentCheckResult r = Compatible;
829
830 // C99 6.5.16.1p1: This following citation is common to constraints
831 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
832 // qualifiers of the type *pointed to* by the right;
833 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
834 rhptee.getQualifiers())
835 r = CompatiblePointerDiscardsQualifiers;
836
837 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
838 // incomplete type and the other is a pointer to a qualified or unqualified
839 // version of void...
840 if (lhptee.getUnqualifiedType()->isVoidType() &&
841 (rhptee->isObjectType() || rhptee->isIncompleteType()))
842 ;
843 else if (rhptee.getUnqualifiedType()->isVoidType() &&
844 (lhptee->isObjectType() || lhptee->isIncompleteType()))
845 ;
846 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
847 // unqualified versions of compatible types, ...
848 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
849 rhptee.getUnqualifiedType()))
850 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
851 return r;
852}
853
854/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
855/// has code to accommodate several GCC extensions when type checking
856/// pointers. Here are some objectionable examples that GCC considers warnings:
857///
858/// int a, *pint;
859/// short *pshort;
860/// struct foo *pfoo;
861///
862/// pint = pshort; // warning: assignment from incompatible pointer type
863/// a = pint; // warning: assignment makes integer from pointer without a cast
864/// pint = a; // warning: assignment makes pointer from integer without a cast
865/// pint = pfoo; // warning: assignment from incompatible pointer type
866///
867/// As a result, the code for dealing with pointers is more complex than the
868/// C99 spec dictates.
869/// Note: the warning above turn into errors when -pedantic-errors is enabled.
870///
871Sema::AssignmentCheckResult
872Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
873 if (lhsType == rhsType) // common case, fast path...
874 return Compatible;
875
876 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
877 if (lhsType->isVectorType() || rhsType->isVectorType()) {
878 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
879 return Incompatible;
880 }
881 return Compatible;
882 } else if (lhsType->isPointerType()) {
883 if (rhsType->isIntegerType())
884 return PointerFromInt;
885
886 if (rhsType->isPointerType())
887 return CheckPointerTypesForAssignment(lhsType, rhsType);
888 } else if (rhsType->isPointerType()) {
889 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
890 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
891 return IntFromPointer;
892
893 if (lhsType->isPointerType())
894 return CheckPointerTypesForAssignment(lhsType, rhsType);
895 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
896 if (Type::tagTypesAreCompatible(lhsType, rhsType))
897 return Compatible;
898 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
899 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
900 return Compatible;
901 }
902 return Incompatible;
903}
904
905Sema::AssignmentCheckResult
906Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
907 // This check seems unnatural, however it is necessary to insure the proper
908 // conversion of functions/arrays. If the conversion were done for all
909 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
910 // expressions that surpress this implicit conversion (&, sizeof).
911 DefaultFunctionArrayConversion(rExpr);
912
913 return CheckAssignmentConstraints(lhsType, rExpr->getType());
914}
915
916Sema::AssignmentCheckResult
917Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
918 return CheckAssignmentConstraints(lhsType, rhsType);
919}
920
921inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
922 Diag(loc, diag::err_typecheck_invalid_operands,
923 lex->getType().getAsString(), rex->getType().getAsString(),
924 lex->getSourceRange(), rex->getSourceRange());
925}
926
927inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
928 Expr *&rex) {
929 QualType lhsType = lex->getType(), rhsType = rex->getType();
930
931 // make sure the vector types are identical.
932 if (lhsType == rhsType)
933 return lhsType;
934 // You cannot convert between vector values of different size.
935 Diag(loc, diag::err_typecheck_vector_not_convertable,
936 lex->getType().getAsString(), rex->getType().getAsString(),
937 lex->getSourceRange(), rex->getSourceRange());
938 return QualType();
939}
940
941inline QualType Sema::CheckMultiplyDivideOperands(
942 Expr *&lex, Expr *&rex, SourceLocation loc)
943{
944 QualType lhsType = lex->getType(), rhsType = rex->getType();
945
946 if (lhsType->isVectorType() || rhsType->isVectorType())
947 return CheckVectorOperands(loc, lex, rex);
948
949 UsualArithmeticConversions(lex, rex);
950
951 // handle the common case first (both operands are arithmetic).
952 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
953 return lex->getType();
954 InvalidOperands(loc, lex, rex);
955 return QualType();
956}
957
958inline QualType Sema::CheckRemainderOperands(
959 Expr *&lex, Expr *&rex, SourceLocation loc)
960{
961 QualType lhsType = lex->getType(), rhsType = rex->getType();
962
963 UsualArithmeticConversions(lex, rex);
964
965 // handle the common case first (both operands are arithmetic).
966 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
967 return lex->getType();
968 InvalidOperands(loc, lex, rex);
969 return QualType();
970}
971
972inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
973 Expr *&lex, Expr *&rex, SourceLocation loc)
974{
975 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
976 return CheckVectorOperands(loc, lex, rex);
977
978 UsualArithmeticConversions(lex, rex);
979
980 // handle the common case first (both operands are arithmetic).
981 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
982 return lex->getType();
983
984 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
985 return lex->getType();
986 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
987 return rex->getType();
988 InvalidOperands(loc, lex, rex);
989 return QualType();
990}
991
992inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
993 Expr *&lex, Expr *&rex, SourceLocation loc)
994{
995 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
996 return CheckVectorOperands(loc, lex, rex);
997
998 UsualArithmeticConversions(lex, rex);
999
1000 // handle the common case first (both operands are arithmetic).
1001 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1002 return lex->getType();
1003
1004 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1005 return lex->getType();
1006 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1007 return Context.getPointerDiffType();
1008 InvalidOperands(loc, lex, rex);
1009 return QualType();
1010}
1011
1012inline QualType Sema::CheckShiftOperands( // C99 6.5.7
1013 Expr *&lex, Expr *&rex, SourceLocation loc)
1014{
1015 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1016 // for int << longlong -> the result type should be int, not long long.
1017 UsualArithmeticConversions(lex, rex);
1018
1019 // handle the common case first (both operands are arithmetic).
1020 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1021 return lex->getType();
1022 InvalidOperands(loc, lex, rex);
1023 return QualType();
1024}
1025
1026inline QualType Sema::CheckRelationalOperands( // C99 6.5.8
1027 Expr *&lex, Expr *&rex, SourceLocation loc)
1028{
Steve Naroffecc4fa12007-08-10 18:26:40 +00001029 // C99 6.5.8p3
1030 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1031 UsualArithmeticConversions(lex, rex);
1032 else {
1033 UsualUnaryConversions(lex);
1034 UsualUnaryConversions(rex);
1035 }
Chris Lattner4b009652007-07-25 00:24:17 +00001036 QualType lType = lex->getType();
1037 QualType rType = rex->getType();
1038
1039 if (lType->isRealType() && rType->isRealType())
1040 return Context.IntTy;
1041
1042 if (lType->isPointerType()) {
1043 if (rType->isPointerType())
1044 return Context.IntTy;
1045 if (rType->isIntegerType()) {
1046 if (!rex->isNullPointerConstant(Context))
1047 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1048 lex->getSourceRange(), rex->getSourceRange());
1049 return Context.IntTy; // the previous diagnostic is a GCC extension.
1050 }
1051 } else if (rType->isPointerType()) {
1052 if (lType->isIntegerType()) {
1053 if (!lex->isNullPointerConstant(Context))
1054 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1055 lex->getSourceRange(), rex->getSourceRange());
1056 return Context.IntTy; // the previous diagnostic is a GCC extension.
1057 }
1058 }
1059 InvalidOperands(loc, lex, rex);
1060 return QualType();
1061}
1062
1063inline QualType Sema::CheckEqualityOperands( // C99 6.5.9
1064 Expr *&lex, Expr *&rex, SourceLocation loc)
1065{
Steve Naroffecc4fa12007-08-10 18:26:40 +00001066 // C99 6.5.9p4
1067 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1068 UsualArithmeticConversions(lex, rex);
1069 else {
1070 UsualUnaryConversions(lex);
1071 UsualUnaryConversions(rex);
1072 }
Chris Lattner4b009652007-07-25 00:24:17 +00001073 QualType lType = lex->getType();
1074 QualType rType = rex->getType();
1075
1076 if (lType->isArithmeticType() && rType->isArithmeticType())
1077 return Context.IntTy;
1078
1079 if (lType->isPointerType()) {
1080 if (rType->isPointerType())
1081 return Context.IntTy;
1082 if (rType->isIntegerType()) {
1083 if (!rex->isNullPointerConstant(Context))
1084 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1085 lex->getSourceRange(), rex->getSourceRange());
1086 return Context.IntTy; // the previous diagnostic is a GCC extension.
1087 }
1088 } else if (rType->isPointerType()) {
1089 if (lType->isIntegerType()) {
1090 if (!lex->isNullPointerConstant(Context))
1091 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1092 lex->getSourceRange(), rex->getSourceRange());
1093 return Context.IntTy; // the previous diagnostic is a GCC extension.
1094 }
1095 }
1096 InvalidOperands(loc, lex, rex);
1097 return QualType();
1098}
1099
1100inline QualType Sema::CheckBitwiseOperands(
1101 Expr *&lex, Expr *&rex, SourceLocation loc)
1102{
1103 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1104 return CheckVectorOperands(loc, lex, rex);
1105
1106 UsualArithmeticConversions(lex, rex);
1107
1108 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1109 return lex->getType();
1110 InvalidOperands(loc, lex, rex);
1111 return QualType();
1112}
1113
1114inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1115 Expr *&lex, Expr *&rex, SourceLocation loc)
1116{
1117 UsualUnaryConversions(lex);
1118 UsualUnaryConversions(rex);
1119
1120 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1121 return Context.IntTy;
1122 InvalidOperands(loc, lex, rex);
1123 return QualType();
1124}
1125
1126inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
1127 Expr *lex, Expr *rex, SourceLocation loc, QualType compoundType)
1128{
1129 QualType lhsType = lex->getType();
1130 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1131 bool hadError = false;
1132 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1133
1134 switch (mlval) { // C99 6.5.16p2
1135 case Expr::MLV_Valid:
1136 break;
1137 case Expr::MLV_ConstQualified:
1138 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1139 hadError = true;
1140 break;
1141 case Expr::MLV_ArrayType:
1142 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1143 lhsType.getAsString(), lex->getSourceRange());
1144 return QualType();
1145 case Expr::MLV_NotObjectType:
1146 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1147 lhsType.getAsString(), lex->getSourceRange());
1148 return QualType();
1149 case Expr::MLV_InvalidExpression:
1150 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1151 lex->getSourceRange());
1152 return QualType();
1153 case Expr::MLV_IncompleteType:
1154 case Expr::MLV_IncompleteVoidType:
1155 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1156 lhsType.getAsString(), lex->getSourceRange());
1157 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001158 case Expr::MLV_DuplicateVectorComponents:
1159 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1160 lex->getSourceRange());
1161 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001162 }
1163 AssignmentCheckResult result;
1164
1165 if (compoundType.isNull())
1166 result = CheckSingleAssignmentConstraints(lhsType, rex);
1167 else
1168 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001169
Chris Lattner4b009652007-07-25 00:24:17 +00001170 // decode the result (notice that extensions still return a type).
1171 switch (result) {
1172 case Compatible:
1173 break;
1174 case Incompatible:
1175 Diag(loc, diag::err_typecheck_assign_incompatible,
1176 lhsType.getAsString(), rhsType.getAsString(),
1177 lex->getSourceRange(), rex->getSourceRange());
1178 hadError = true;
1179 break;
1180 case PointerFromInt:
1181 // check for null pointer constant (C99 6.3.2.3p3)
1182 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1183 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1184 lhsType.getAsString(), rhsType.getAsString(),
1185 lex->getSourceRange(), rex->getSourceRange());
1186 }
1187 break;
1188 case IntFromPointer:
1189 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1190 lhsType.getAsString(), rhsType.getAsString(),
1191 lex->getSourceRange(), rex->getSourceRange());
1192 break;
1193 case IncompatiblePointer:
1194 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1195 lhsType.getAsString(), rhsType.getAsString(),
1196 lex->getSourceRange(), rex->getSourceRange());
1197 break;
1198 case CompatiblePointerDiscardsQualifiers:
1199 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1200 lhsType.getAsString(), rhsType.getAsString(),
1201 lex->getSourceRange(), rex->getSourceRange());
1202 break;
1203 }
1204 // C99 6.5.16p3: The type of an assignment expression is the type of the
1205 // left operand unless the left operand has qualified type, in which case
1206 // it is the unqualified version of the type of the left operand.
1207 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1208 // is converted to the type of the assignment expression (above).
1209 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1210 return hadError ? QualType() : lhsType.getUnqualifiedType();
1211}
1212
1213inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1214 Expr *&lex, Expr *&rex, SourceLocation loc) {
1215 UsualUnaryConversions(rex);
1216 return rex->getType();
1217}
1218
1219/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1220/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1221QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1222 QualType resType = op->getType();
1223 assert(!resType.isNull() && "no type for increment/decrement expression");
1224
1225 // C99 6.5.2.4p1
1226 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1227 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1228 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1229 resType.getAsString(), op->getSourceRange());
1230 return QualType();
1231 }
1232 } else if (!resType->isRealType()) {
1233 // FIXME: Allow Complex as a GCC extension.
1234 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1235 resType.getAsString(), op->getSourceRange());
1236 return QualType();
1237 }
1238 // At this point, we know we have a real or pointer type. Now make sure
1239 // the operand is a modifiable lvalue.
1240 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1241 if (mlval != Expr::MLV_Valid) {
1242 // FIXME: emit a more precise diagnostic...
1243 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1244 op->getSourceRange());
1245 return QualType();
1246 }
1247 return resType;
1248}
1249
1250/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1251/// This routine allows us to typecheck complex/recursive expressions
1252/// where the declaration is needed for type checking. Here are some
1253/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1254static Decl *getPrimaryDeclaration(Expr *e) {
1255 switch (e->getStmtClass()) {
1256 case Stmt::DeclRefExprClass:
1257 return cast<DeclRefExpr>(e)->getDecl();
1258 case Stmt::MemberExprClass:
1259 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1260 case Stmt::ArraySubscriptExprClass:
1261 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1262 case Stmt::CallExprClass:
1263 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1264 case Stmt::UnaryOperatorClass:
1265 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1266 case Stmt::ParenExprClass:
1267 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1268 default:
1269 return 0;
1270 }
1271}
1272
1273/// CheckAddressOfOperand - The operand of & must be either a function
1274/// designator or an lvalue designating an object. If it is an lvalue, the
1275/// object cannot be declared with storage class register or be a bit field.
1276/// Note: The usual conversions are *not* applied to the operand of the &
1277/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1278QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1279 Decl *dcl = getPrimaryDeclaration(op);
1280 Expr::isLvalueResult lval = op->isLvalue();
1281
1282 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1283 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1284 ;
1285 else { // FIXME: emit more specific diag...
1286 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1287 op->getSourceRange());
1288 return QualType();
1289 }
1290 } else if (dcl) {
1291 // We have an lvalue with a decl. Make sure the decl is not declared
1292 // with the register storage-class specifier.
1293 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1294 if (vd->getStorageClass() == VarDecl::Register) {
1295 Diag(OpLoc, diag::err_typecheck_address_of_register,
1296 op->getSourceRange());
1297 return QualType();
1298 }
1299 } else
1300 assert(0 && "Unknown/unexpected decl type");
1301
1302 // FIXME: add check for bitfields!
1303 }
1304 // If the operand has type "type", the result has type "pointer to type".
1305 return Context.getPointerType(op->getType());
1306}
1307
1308QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1309 UsualUnaryConversions(op);
1310 QualType qType = op->getType();
1311
Chris Lattner7931f4a2007-07-31 16:53:04 +00001312 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001313 QualType ptype = PT->getPointeeType();
1314 // C99 6.5.3.2p4. "if it points to an object,...".
1315 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1316 // GCC compat: special case 'void *' (treat as warning).
1317 if (ptype->isVoidType()) {
1318 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1319 qType.getAsString(), op->getSourceRange());
1320 } else {
1321 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1322 ptype.getAsString(), op->getSourceRange());
1323 return QualType();
1324 }
1325 }
1326 return ptype;
1327 }
1328 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1329 qType.getAsString(), op->getSourceRange());
1330 return QualType();
1331}
1332
1333static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1334 tok::TokenKind Kind) {
1335 BinaryOperator::Opcode Opc;
1336 switch (Kind) {
1337 default: assert(0 && "Unknown binop!");
1338 case tok::star: Opc = BinaryOperator::Mul; break;
1339 case tok::slash: Opc = BinaryOperator::Div; break;
1340 case tok::percent: Opc = BinaryOperator::Rem; break;
1341 case tok::plus: Opc = BinaryOperator::Add; break;
1342 case tok::minus: Opc = BinaryOperator::Sub; break;
1343 case tok::lessless: Opc = BinaryOperator::Shl; break;
1344 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1345 case tok::lessequal: Opc = BinaryOperator::LE; break;
1346 case tok::less: Opc = BinaryOperator::LT; break;
1347 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1348 case tok::greater: Opc = BinaryOperator::GT; break;
1349 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1350 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1351 case tok::amp: Opc = BinaryOperator::And; break;
1352 case tok::caret: Opc = BinaryOperator::Xor; break;
1353 case tok::pipe: Opc = BinaryOperator::Or; break;
1354 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1355 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1356 case tok::equal: Opc = BinaryOperator::Assign; break;
1357 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1358 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1359 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1360 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1361 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1362 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1363 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1364 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1365 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1366 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1367 case tok::comma: Opc = BinaryOperator::Comma; break;
1368 }
1369 return Opc;
1370}
1371
1372static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1373 tok::TokenKind Kind) {
1374 UnaryOperator::Opcode Opc;
1375 switch (Kind) {
1376 default: assert(0 && "Unknown unary op!");
1377 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1378 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1379 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1380 case tok::star: Opc = UnaryOperator::Deref; break;
1381 case tok::plus: Opc = UnaryOperator::Plus; break;
1382 case tok::minus: Opc = UnaryOperator::Minus; break;
1383 case tok::tilde: Opc = UnaryOperator::Not; break;
1384 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1385 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1386 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1387 case tok::kw___real: Opc = UnaryOperator::Real; break;
1388 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1389 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1390 }
1391 return Opc;
1392}
1393
1394// Binary Operators. 'Tok' is the token for the operator.
1395Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1396 ExprTy *LHS, ExprTy *RHS) {
1397 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1398 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1399
1400 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1401 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1402
1403 QualType ResultTy; // Result type of the binary operator.
1404 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1405
1406 switch (Opc) {
1407 default:
1408 assert(0 && "Unknown binary expr!");
1409 case BinaryOperator::Assign:
1410 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1411 break;
1412 case BinaryOperator::Mul:
1413 case BinaryOperator::Div:
1414 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1415 break;
1416 case BinaryOperator::Rem:
1417 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1418 break;
1419 case BinaryOperator::Add:
1420 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1421 break;
1422 case BinaryOperator::Sub:
1423 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1424 break;
1425 case BinaryOperator::Shl:
1426 case BinaryOperator::Shr:
1427 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1428 break;
1429 case BinaryOperator::LE:
1430 case BinaryOperator::LT:
1431 case BinaryOperator::GE:
1432 case BinaryOperator::GT:
1433 ResultTy = CheckRelationalOperands(lhs, rhs, TokLoc);
1434 break;
1435 case BinaryOperator::EQ:
1436 case BinaryOperator::NE:
1437 ResultTy = CheckEqualityOperands(lhs, rhs, TokLoc);
1438 break;
1439 case BinaryOperator::And:
1440 case BinaryOperator::Xor:
1441 case BinaryOperator::Or:
1442 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1443 break;
1444 case BinaryOperator::LAnd:
1445 case BinaryOperator::LOr:
1446 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1447 break;
1448 case BinaryOperator::MulAssign:
1449 case BinaryOperator::DivAssign:
1450 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1451 if (!CompTy.isNull())
1452 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1453 break;
1454 case BinaryOperator::RemAssign:
1455 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1456 if (!CompTy.isNull())
1457 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1458 break;
1459 case BinaryOperator::AddAssign:
1460 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1461 if (!CompTy.isNull())
1462 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1463 break;
1464 case BinaryOperator::SubAssign:
1465 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1466 if (!CompTy.isNull())
1467 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1468 break;
1469 case BinaryOperator::ShlAssign:
1470 case BinaryOperator::ShrAssign:
1471 CompTy = CheckShiftOperands(lhs, rhs, TokLoc);
1472 if (!CompTy.isNull())
1473 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1474 break;
1475 case BinaryOperator::AndAssign:
1476 case BinaryOperator::XorAssign:
1477 case BinaryOperator::OrAssign:
1478 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1479 if (!CompTy.isNull())
1480 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1481 break;
1482 case BinaryOperator::Comma:
1483 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1484 break;
1485 }
1486 if (ResultTy.isNull())
1487 return true;
1488 if (CompTy.isNull())
1489 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1490 else
1491 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1492}
1493
1494// Unary Operators. 'Tok' is the token for the operator.
1495Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1496 ExprTy *input) {
1497 Expr *Input = (Expr*)input;
1498 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1499 QualType resultType;
1500 switch (Opc) {
1501 default:
1502 assert(0 && "Unimplemented unary expr!");
1503 case UnaryOperator::PreInc:
1504 case UnaryOperator::PreDec:
1505 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1506 break;
1507 case UnaryOperator::AddrOf:
1508 resultType = CheckAddressOfOperand(Input, OpLoc);
1509 break;
1510 case UnaryOperator::Deref:
1511 resultType = CheckIndirectionOperand(Input, OpLoc);
1512 break;
1513 case UnaryOperator::Plus:
1514 case UnaryOperator::Minus:
1515 UsualUnaryConversions(Input);
1516 resultType = Input->getType();
1517 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1518 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1519 resultType.getAsString());
1520 break;
1521 case UnaryOperator::Not: // bitwise complement
1522 UsualUnaryConversions(Input);
1523 resultType = Input->getType();
1524 if (!resultType->isIntegerType()) // C99 6.5.3.3p1
1525 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1526 resultType.getAsString());
1527 break;
1528 case UnaryOperator::LNot: // logical negation
1529 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1530 DefaultFunctionArrayConversion(Input);
1531 resultType = Input->getType();
1532 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1533 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1534 resultType.getAsString());
1535 // LNot always has type int. C99 6.5.3.3p5.
1536 resultType = Context.IntTy;
1537 break;
1538 case UnaryOperator::SizeOf:
1539 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1540 break;
1541 case UnaryOperator::AlignOf:
1542 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1543 break;
1544 case UnaryOperator::Extension:
1545 // FIXME: does __extension__ cause any promotions? I would think not.
1546 resultType = Input->getType();
1547 break;
1548 }
1549 if (resultType.isNull())
1550 return true;
1551 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1552}
1553
1554/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1555Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1556 SourceLocation LabLoc,
1557 IdentifierInfo *LabelII) {
1558 // Look up the record for this label identifier.
1559 LabelStmt *&LabelDecl = LabelMap[LabelII];
1560
1561 // If we haven't seen this label yet, create a forward reference.
1562 if (LabelDecl == 0)
1563 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1564
1565 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001566 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1567 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001568}
1569
1570Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1571 SourceLocation RPLoc) { // "({..})"
1572 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1573 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1574 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1575
1576 // FIXME: there are a variety of strange constraints to enforce here, for
1577 // example, it is not possible to goto into a stmt expression apparently.
1578 // More semantic analysis is needed.
1579
1580 // FIXME: the last statement in the compount stmt has its value used. We
1581 // should not warn about it being unused.
1582
1583 // If there are sub stmts in the compound stmt, take the type of the last one
1584 // as the type of the stmtexpr.
1585 QualType Ty = Context.VoidTy;
1586
1587 if (!Compound->body_empty())
1588 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1589 Ty = LastExpr->getType();
1590
1591 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1592}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001593
Steve Naroff5b528922007-08-01 23:45:51 +00001594Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001595 TypeTy *arg1, TypeTy *arg2,
1596 SourceLocation RPLoc) {
1597 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1598 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1599
1600 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1601
Steve Naroff5b528922007-08-01 23:45:51 +00001602 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001603}
1604
Steve Naroff93c53012007-08-03 21:21:27 +00001605Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1606 ExprTy *expr1, ExprTy *expr2,
1607 SourceLocation RPLoc) {
1608 Expr *CondExpr = static_cast<Expr*>(cond);
1609 Expr *LHSExpr = static_cast<Expr*>(expr1);
1610 Expr *RHSExpr = static_cast<Expr*>(expr2);
1611
1612 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1613
1614 // The conditional expression is required to be a constant expression.
1615 llvm::APSInt condEval(32);
1616 SourceLocation ExpLoc;
1617 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1618 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1619 CondExpr->getSourceRange());
1620
1621 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1622 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1623 RHSExpr->getType();
1624 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1625}
1626