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