blob: 1e81d5c24290b2fbd0b5dbfdd97cead5799b8bd2 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000015#include "SemaUtil.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000018#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000023#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Steve Naroff87d58b42007-09-16 03:34:24 +000028/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000029/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000035Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000036 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
45
46 // FIXME: handle wchar_t
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000047 QualType t;
48
49 if (Literal.Pascal)
50 t = Context.getPointerType(Context.UnsignedCharTy);
51 else
52 t = Context.getPointerType(Context.CharTy);
53
54 if (Literal.Pascal && Literal.GetStringLength() > 256)
55 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
56 SourceRange(StringToks[0].getLocation(),
57 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000058
59 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
60 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000061 Literal.AnyWide, t,
62 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000063 StringToks[NumStringToks-1].getLocation());
64}
65
66
Steve Naroff0acc9c92007-09-15 18:49:24 +000067/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000068/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
69/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000070Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000071 IdentifierInfo &II,
72 bool HasTrailingLParen) {
73 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000074 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000075 if (D == 0) {
76 // Otherwise, this could be an implicitly declared function reference (legal
77 // in C90, extension in C99).
78 if (HasTrailingLParen &&
79 // Not in C++.
80 !getLangOptions().CPlusPlus)
81 D = ImplicitlyDefineFunction(Loc, II, S);
82 else {
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000083 if (CurMethodDecl) {
Ted Kremenek42730c52008-01-07 19:49:32 +000084 ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
85 ObjCInterfaceDecl *clsDeclared;
86 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
Steve Naroff6b759ce2007-11-15 02:58:25 +000087 IdentifierInfo &II = Context.Idents.get("self");
88 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
89 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
90 static_cast<Expr*>(SelfExpr.Val), true, true);
91 }
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000092 }
Chris Lattner4b009652007-07-25 00:24:17 +000093 // If this name wasn't predeclared and if this is not a function call,
94 // diagnose the problem.
95 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
96 }
97 }
Steve Naroff91b03f72007-08-28 03:03:08 +000098 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +000099 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000100 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000101 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000102 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000103 }
Chris Lattner4b009652007-07-25 00:24:17 +0000104 if (isa<TypedefDecl>(D))
105 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000106 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000107 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000108
109 assert(0 && "Invalid decl");
110 abort();
111}
112
Steve Naroff87d58b42007-09-16 03:34:24 +0000113Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000114 tok::TokenKind Kind) {
115 PreDefinedExpr::IdentType IT;
116
117 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000118 default: assert(0 && "Unknown simple primary expr!");
119 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
120 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
121 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000122 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000123
124 // Verify that this is in a function context.
125 if (CurFunctionDecl == 0)
126 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000127
Chris Lattner7e637512008-01-12 08:14:25 +0000128 // Pre-defined identifiers are of type char[x], where x is the length of the
129 // string.
130 llvm::APSInt Length(32);
131 Length = CurFunctionDecl->getIdentifier()->getLength() + 1;
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000132
133 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
134 ResTy = Context.getConstantArrayType(ResTy, Length, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000135 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000136}
137
Steve Naroff87d58b42007-09-16 03:34:24 +0000138Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000139 llvm::SmallString<16> CharBuffer;
140 CharBuffer.resize(Tok.getLength());
141 const char *ThisTokBegin = &CharBuffer[0];
142 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
143
144 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
145 Tok.getLocation(), PP);
146 if (Literal.hadError())
147 return ExprResult(true);
148 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
149 Tok.getLocation());
150}
151
Steve Naroff87d58b42007-09-16 03:34:24 +0000152Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000153 // fast path for a single digit (which is quite common). A single digit
154 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
155 if (Tok.getLength() == 1) {
156 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
157
Chris Lattner3496d522007-09-04 02:45:27 +0000158 unsigned IntSize = static_cast<unsigned>(
159 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000160 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
161 Context.IntTy,
162 Tok.getLocation()));
163 }
164 llvm::SmallString<512> IntegerBuffer;
165 IntegerBuffer.resize(Tok.getLength());
166 const char *ThisTokBegin = &IntegerBuffer[0];
167
168 // Get the spelling of the token, which eliminates trigraphs, etc.
169 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
170 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
171 Tok.getLocation(), PP);
172 if (Literal.hadError)
173 return ExprResult(true);
174
Chris Lattner1de66eb2007-08-26 03:42:43 +0000175 Expr *Res;
176
177 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000178 QualType Ty;
179 const llvm::fltSemantics *Format;
180 uint64_t Size; unsigned Align;
181
182 if (Literal.isFloat) {
183 Ty = Context.FloatTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000184 Context.Target.getFloatInfo(Size, Align, Format,
185 Context.getFullLoc(Tok.getLocation()));
186
Chris Lattner858eece2007-09-22 18:29:59 +0000187 } else if (Literal.isLong) {
188 Ty = Context.LongDoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000189 Context.Target.getLongDoubleInfo(Size, Align, Format,
190 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000191 } else {
192 Ty = Context.DoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000193 Context.Target.getDoubleInfo(Size, Align, Format,
194 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000195 }
196
Ted Kremenekddedbe22007-11-29 00:56:49 +0000197 // isExact will be set by GetFloatValue().
198 bool isExact = false;
199
200 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
201 Ty, Tok.getLocation());
202
Chris Lattner1de66eb2007-08-26 03:42:43 +0000203 } else if (!Literal.isIntegerLiteral()) {
204 return ExprResult(true);
205 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000206 QualType t;
207
Neil Booth7421e9c2007-08-29 22:00:19 +0000208 // long long is a C99 feature.
209 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000210 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000211 Diag(Tok.getLocation(), diag::ext_longlong);
212
Chris Lattner4b009652007-07-25 00:24:17 +0000213 // Get the value in the widest-possible width.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000214 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
215 Context.getFullLoc(Tok.getLocation())), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000216
217 if (Literal.GetIntegerValue(ResultVal)) {
218 // If this value didn't fit into uintmax_t, warn and force to ull.
219 Diag(Tok.getLocation(), diag::warn_integer_too_large);
220 t = Context.UnsignedLongLongTy;
221 assert(Context.getTypeSize(t, Tok.getLocation()) ==
222 ResultVal.getBitWidth() && "long long is not intmax_t?");
223 } else {
224 // If this value fits into a ULL, try to figure out what else it fits into
225 // according to the rules of C99 6.4.4.1p5.
226
227 // Octal, Hexadecimal, and integers with a U suffix are allowed to
228 // be an unsigned int.
229 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
230
231 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000232 if (!Literal.isLong && !Literal.isLongLong) {
233 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000234 unsigned IntSize = static_cast<unsigned>(
235 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000236 // Does it fit in a unsigned int?
237 if (ResultVal.isIntN(IntSize)) {
238 // Does it fit in a signed int?
239 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
240 t = Context.IntTy;
241 else if (AllowUnsigned)
242 t = Context.UnsignedIntTy;
243 }
244
245 if (!t.isNull())
246 ResultVal.trunc(IntSize);
247 }
248
249 // Are long/unsigned long possibilities?
250 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000251 unsigned LongSize = static_cast<unsigned>(
252 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000253
254 // Does it fit in a unsigned long?
255 if (ResultVal.isIntN(LongSize)) {
256 // Does it fit in a signed long?
257 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
258 t = Context.LongTy;
259 else if (AllowUnsigned)
260 t = Context.UnsignedLongTy;
261 }
262 if (!t.isNull())
263 ResultVal.trunc(LongSize);
264 }
265
266 // Finally, check long long if needed.
267 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000268 unsigned LongLongSize = static_cast<unsigned>(
269 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000270
271 // Does it fit in a unsigned long long?
272 if (ResultVal.isIntN(LongLongSize)) {
273 // Does it fit in a signed long long?
274 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
275 t = Context.LongLongTy;
276 else if (AllowUnsigned)
277 t = Context.UnsignedLongLongTy;
278 }
279 }
280
281 // If we still couldn't decide a type, we probably have something that
282 // does not fit in a signed long long, but has no U suffix.
283 if (t.isNull()) {
284 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
285 t = Context.UnsignedLongLongTy;
286 }
287 }
288
Chris Lattner1de66eb2007-08-26 03:42:43 +0000289 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000290 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000291
292 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
293 if (Literal.isImaginary)
294 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
295
296 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000297}
298
Steve Naroff87d58b42007-09-16 03:34:24 +0000299Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000300 ExprTy *Val) {
301 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000302 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000303 return new ParenExpr(L, R, e);
304}
305
306/// The UsualUnaryConversions() function is *not* called by this routine.
307/// See C99 6.3.2.1p[2-4] for more details.
308QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
309 SourceLocation OpLoc, bool isSizeof) {
310 // C99 6.5.3.4p1:
311 if (isa<FunctionType>(exprType) && isSizeof)
312 // alignof(function) is allowed.
313 Diag(OpLoc, diag::ext_sizeof_function_type);
314 else if (exprType->isVoidType())
315 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
316 else if (exprType->isIncompleteType()) {
317 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
318 diag::err_alignof_incomplete_type,
319 exprType.getAsString());
320 return QualType(); // error
321 }
322 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
323 return Context.getSizeType();
324}
325
326Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000327ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000328 SourceLocation LPLoc, TypeTy *Ty,
329 SourceLocation RPLoc) {
330 // If error parsing type, ignore.
331 if (Ty == 0) return true;
332
333 // Verify that this is a valid expression.
334 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
335
336 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
337
338 if (resultType.isNull())
339 return true;
340 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
341}
342
Chris Lattner5110ad52007-08-24 21:41:10 +0000343QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000344 DefaultFunctionArrayConversion(V);
345
Chris Lattnera16e42d2007-08-26 05:39:26 +0000346 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000347 if (const ComplexType *CT = V->getType()->getAsComplexType())
348 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000349
350 // Otherwise they pass through real integer and floating point types here.
351 if (V->getType()->isArithmeticType())
352 return V->getType();
353
354 // Reject anything else.
355 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
356 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000357}
358
359
Chris Lattner4b009652007-07-25 00:24:17 +0000360
Steve Naroff87d58b42007-09-16 03:34:24 +0000361Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000362 tok::TokenKind Kind,
363 ExprTy *Input) {
364 UnaryOperator::Opcode Opc;
365 switch (Kind) {
366 default: assert(0 && "Unknown unary op!");
367 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
368 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
369 }
370 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
371 if (result.isNull())
372 return true;
373 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
374}
375
376Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000377ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000378 ExprTy *Idx, SourceLocation RLoc) {
379 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
380
381 // Perform default conversions.
382 DefaultFunctionArrayConversion(LHSExp);
383 DefaultFunctionArrayConversion(RHSExp);
384
385 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
386
387 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000388 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000389 // in the subscript position. As a result, we need to derive the array base
390 // and index from the expression types.
391 Expr *BaseExpr, *IndexExpr;
392 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000393 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000394 BaseExpr = LHSExp;
395 IndexExpr = RHSExp;
396 // FIXME: need to deal with const...
397 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000398 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000399 // Handle the uncommon case of "123[Ptr]".
400 BaseExpr = RHSExp;
401 IndexExpr = LHSExp;
402 // FIXME: need to deal with const...
403 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000404 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
405 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000406 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000407
408 // Component access limited to variables (reject vec4.rg[1]).
409 if (!isa<DeclRefExpr>(BaseExpr))
410 return Diag(LLoc, diag::err_ocuvector_component_access,
411 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000412 // FIXME: need to deal with const...
413 ResultType = VTy->getElementType();
414 } else {
415 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
416 RHSExp->getSourceRange());
417 }
418 // C99 6.5.2.1p1
419 if (!IndexExpr->getType()->isIntegerType())
420 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
421 IndexExpr->getSourceRange());
422
423 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
424 // the following check catches trying to index a pointer to a function (e.g.
425 // void (*)(int)). Functions are not objects in C99.
426 if (!ResultType->isObjectType())
427 return Diag(BaseExpr->getLocStart(),
428 diag::err_typecheck_subscript_not_object,
429 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
430
431 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
432}
433
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000434QualType Sema::
435CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
436 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000437 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000438
439 // The vector accessor can't exceed the number of elements.
440 const char *compStr = CompName.getName();
441 if (strlen(compStr) > vecType->getNumElements()) {
442 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
443 baseType.getAsString(), SourceRange(CompLoc));
444 return QualType();
445 }
446 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000447 if (vecType->getPointAccessorIdx(*compStr) != -1) {
448 do
449 compStr++;
450 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
451 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
452 do
453 compStr++;
454 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
455 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
456 do
457 compStr++;
458 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
459 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000460
461 if (*compStr) {
462 // We didn't get to the end of the string. This means the component names
463 // didn't come from the same set *or* we encountered an illegal name.
464 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
465 std::string(compStr,compStr+1), SourceRange(CompLoc));
466 return QualType();
467 }
468 // Each component accessor can't exceed the vector type.
469 compStr = CompName.getName();
470 while (*compStr) {
471 if (vecType->isAccessorWithinNumElements(*compStr))
472 compStr++;
473 else
474 break;
475 }
476 if (*compStr) {
477 // We didn't get to the end of the string. This means a component accessor
478 // exceeds the number of elements in the vector.
479 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
480 baseType.getAsString(), SourceRange(CompLoc));
481 return QualType();
482 }
483 // The component accessor looks fine - now we need to compute the actual type.
484 // The vector type is implied by the component accessor. For example,
485 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
486 unsigned CompSize = strlen(CompName.getName());
487 if (CompSize == 1)
488 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000489
490 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
491 // Now look up the TypeDefDecl from the vector type. Without this,
492 // diagostics look bad. We want OCU vector types to appear built-in.
493 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
494 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
495 return Context.getTypedefType(OCUVectorDecls[i]);
496 }
497 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000498}
499
Chris Lattner4b009652007-07-25 00:24:17 +0000500Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000501ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000502 tok::TokenKind OpKind, SourceLocation MemberLoc,
503 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000504 Expr *BaseExpr = static_cast<Expr *>(Base);
505 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000506
507 // Perform default conversions.
508 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000509
Steve Naroff2cb66382007-07-26 03:11:44 +0000510 QualType BaseType = BaseExpr->getType();
511 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000512
Chris Lattner4b009652007-07-25 00:24:17 +0000513 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000514 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000515 BaseType = PT->getPointeeType();
516 else
517 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
518 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000519 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000520 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000521 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000522 RecordDecl *RDecl = RTy->getDecl();
523 if (RTy->isIncompleteType())
524 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
525 BaseExpr->getSourceRange());
526 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000527 FieldDecl *MemberDecl = RDecl->getMember(&Member);
528 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000529 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
530 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000531 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
532 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000533 // Component access limited to variables (reject vec4.rg.g).
534 if (!isa<DeclRefExpr>(BaseExpr))
535 return Diag(OpLoc, diag::err_ocuvector_component_access,
536 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000537 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
538 if (ret.isNull())
539 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000540 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000541 } else if (BaseType->isObjCInterfaceType()) {
542 ObjCInterfaceDecl *IFace;
543 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
544 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000545 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000546 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
547 ObjCInterfaceDecl *clsDeclared;
548 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000549 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
550 OpKind==tok::arrow);
551 }
552 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
553 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000554}
555
Steve Naroff87d58b42007-09-16 03:34:24 +0000556/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000557/// This provides the location of the left/right parens and a list of comma
558/// locations.
559Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000560ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000561 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000562 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
563 Expr *Fn = static_cast<Expr *>(fn);
564 Expr **Args = reinterpret_cast<Expr**>(args);
565 assert(Fn && "no function call expression");
566
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000567 // Make the call expr early, before semantic checks. This guarantees cleanup
568 // of arguments and function on error.
569 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
570 Context.BoolTy, RParenLoc));
571
572 // Promote the function operand.
573 TheCall->setCallee(UsualUnaryConversions(Fn));
574
Chris Lattner4b009652007-07-25 00:24:17 +0000575 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
576 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000577 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000578 if (PT == 0)
579 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
580 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000581 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
582 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000583 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
584 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000585
586 // We know the result type of the call, set it.
587 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000588
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000589 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000590 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
591 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000592 unsigned NumArgsInProto = Proto->getNumArgs();
593 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000594
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000595 // If too few arguments are available, don't make the call.
596 if (NumArgs < NumArgsInProto)
597 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
598 Fn->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000599
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000600 // If too many are passed and not variadic, error on the extras and drop
601 // them.
602 if (NumArgs > NumArgsInProto) {
603 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000604 Diag(Args[NumArgsInProto]->getLocStart(),
605 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
606 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000607 Args[NumArgs-1]->getLocEnd()));
608 // This deletes the extra arguments.
609 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000610 }
611 NumArgsToCheck = NumArgsInProto;
612 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000613
Chris Lattner4b009652007-07-25 00:24:17 +0000614 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000615 for (unsigned i = 0; i != NumArgsToCheck; i++) {
616 Expr *Arg = Args[i];
Chris Lattner005ed752008-01-04 18:04:52 +0000617 QualType ProtoArgType = Proto->getArgType(i);
618 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000619
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000620 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000621 AssignConvertType ConvTy =
622 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000623 TheCall->setArg(i, Arg);
624
Chris Lattner005ed752008-01-04 18:04:52 +0000625 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
626 ArgType, Arg, "passing"))
627 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000628 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000629
630 // If this is a variadic call, handle args passed through "...".
631 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000632 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000633 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
634 Expr *Arg = Args[i];
635 DefaultArgumentPromotion(Arg);
636 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000637 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000638 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000639 } else {
640 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
641
Steve Naroffdb65e052007-08-28 23:30:39 +0000642 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000643 for (unsigned i = 0; i != NumArgs; i++) {
644 Expr *Arg = Args[i];
645 DefaultArgumentPromotion(Arg);
646 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000647 }
Chris Lattner4b009652007-07-25 00:24:17 +0000648 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000649
Chris Lattner2e64c072007-08-10 20:18:51 +0000650 // Do special checking on direct calls to functions.
651 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
652 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
653 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000654 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000655 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000656
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000657 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000658}
659
660Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000661ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000662 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000663 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000664 QualType literalType = QualType::getFromOpaquePtr(Ty);
665 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000666 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000667 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000668
Steve Naroffcb69fb72007-12-10 22:44:33 +0000669 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Narofff0b23542008-01-10 22:15:12 +0000670 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000671 return true;
Steve Narofff0b23542008-01-10 22:15:12 +0000672
673 if (!CurFunctionDecl && !CurMethodDecl) { // 6.5.2.5p3
674 if (CheckForConstantInitializer(literalExpr, literalType))
675 return true;
676 }
Chris Lattner386ab8a2008-01-02 21:46:24 +0000677 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000678}
679
680Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000681ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000682 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000683 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000684
Steve Naroff0acc9c92007-09-15 18:49:24 +0000685 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000686 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000687
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000688 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
689 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
690 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000691}
692
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000693bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000694 assert(VectorTy->isVectorType() && "Not a vector type!");
695
696 if (Ty->isVectorType() || Ty->isIntegerType()) {
697 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
698 Context.getTypeSize(Ty, SourceLocation()))
699 return Diag(R.getBegin(),
700 Ty->isVectorType() ?
701 diag::err_invalid_conversion_between_vectors :
702 diag::err_invalid_conversion_between_vector_and_integer,
703 VectorTy.getAsString().c_str(),
704 Ty.getAsString().c_str(), R);
705 } else
706 return Diag(R.getBegin(),
707 diag::err_invalid_conversion_between_vector_and_scalar,
708 VectorTy.getAsString().c_str(),
709 Ty.getAsString().c_str(), R);
710
711 return false;
712}
713
Chris Lattner4b009652007-07-25 00:24:17 +0000714Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000715ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000716 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000717 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000718
719 Expr *castExpr = static_cast<Expr*>(Op);
720 QualType castType = QualType::getFromOpaquePtr(Ty);
721
Steve Naroff68adb482007-08-31 00:32:44 +0000722 UsualUnaryConversions(castExpr);
723
Chris Lattner4b009652007-07-25 00:24:17 +0000724 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
725 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000726 if (!castType->isVoidType()) { // Cast to void allows any expr type.
727 if (!castType->isScalarType())
728 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
729 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000730 if (!castExpr->getType()->isScalarType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000731 return Diag(castExpr->getLocStart(),
732 diag::err_typecheck_expect_scalar_operand,
733 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000734
735 if (castExpr->getType()->isVectorType()) {
736 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
737 castExpr->getType(), castType))
738 return true;
739 } else if (castType->isVectorType()) {
740 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
741 castType, castExpr->getType()))
742 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000743 }
Chris Lattner4b009652007-07-25 00:24:17 +0000744 }
745 return new CastExpr(castType, castExpr, LParenLoc);
746}
747
Steve Naroff144667e2007-10-18 05:13:08 +0000748// promoteExprToType - a helper function to ensure we create exactly one
749// ImplicitCastExpr.
750static void promoteExprToType(Expr *&expr, QualType type) {
751 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
752 impCast->setType(type);
753 else
754 expr = new ImplicitCastExpr(type, expr);
755 return;
756}
757
Chris Lattner98a425c2007-11-26 01:40:58 +0000758/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
759/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000760inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
761 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
762 UsualUnaryConversions(cond);
763 UsualUnaryConversions(lex);
764 UsualUnaryConversions(rex);
765 QualType condT = cond->getType();
766 QualType lexT = lex->getType();
767 QualType rexT = rex->getType();
768
769 // first, check the condition.
770 if (!condT->isScalarType()) { // C99 6.5.15p2
771 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
772 condT.getAsString());
773 return QualType();
774 }
Chris Lattner992ae932008-01-06 22:42:25 +0000775
776 // Now check the two expressions.
777
778 // If both operands have arithmetic type, do the usual arithmetic conversions
779 // to find a common type: C99 6.5.15p3,5.
780 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000781 UsualArithmeticConversions(lex, rex);
782 return lex->getType();
783 }
Chris Lattner992ae932008-01-06 22:42:25 +0000784
785 // If both operands are the same structure or union type, the result is that
786 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000787 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000788 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000789 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000790 // "If both the operands have structure or union type, the result has
791 // that type." This implies that CV qualifiers are dropped.
792 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000793 }
Chris Lattner992ae932008-01-06 22:42:25 +0000794
795 // C99 6.5.15p5: "If both operands have void type, the result has void type."
796 if (lexT->isVoidType() && rexT->isVoidType())
797 return lexT.getUnqualifiedType();
Steve Naroff12ebf272008-01-08 01:11:38 +0000798
799 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
800 // the type of the other operand."
801 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
802 promoteExprToType(rex, lexT); // promote the null to a pointer.
803 return lexT;
804 }
805 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
806 promoteExprToType(lex, rexT); // promote the null to a pointer.
807 return rexT;
808 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000809 // Handle the case where both operands are pointers before we handle null
810 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000811 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
812 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
813 // get the "pointed to" types
814 QualType lhptee = LHSPT->getPointeeType();
815 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000816
Chris Lattner71225142007-07-31 21:27:01 +0000817 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
818 if (lhptee->isVoidType() &&
819 (rhptee->isObjectType() || rhptee->isIncompleteType()))
820 return lexT;
821 if (rhptee->isVoidType() &&
822 (lhptee->isObjectType() || lhptee->isIncompleteType()))
823 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000824
Steve Naroff85f0dc52007-10-15 20:41:53 +0000825 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
826 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000827 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
828 lexT.getAsString(), rexT.getAsString(),
829 lex->getSourceRange(), rex->getSourceRange());
830 return lexT; // FIXME: this is an _ext - is this return o.k?
831 }
832 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000833 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
834 // differently qualified versions of compatible types, the result type is
835 // a pointer to an appropriately qualified version of the *composite*
836 // type.
Chris Lattner0ac51632008-01-06 22:50:31 +0000837 // FIXME: Need to return the composite type.
838 return lexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000839 }
Chris Lattner4b009652007-07-25 00:24:17 +0000840 }
Chris Lattner71225142007-07-31 21:27:01 +0000841
Chris Lattner992ae932008-01-06 22:42:25 +0000842 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000843 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
844 lexT.getAsString(), rexT.getAsString(),
845 lex->getSourceRange(), rex->getSourceRange());
846 return QualType();
847}
848
Steve Naroff87d58b42007-09-16 03:34:24 +0000849/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000850/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000851Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000852 SourceLocation ColonLoc,
853 ExprTy *Cond, ExprTy *LHS,
854 ExprTy *RHS) {
855 Expr *CondExpr = (Expr *) Cond;
856 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000857
858 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
859 // was the condition.
860 bool isLHSNull = LHSExpr == 0;
861 if (isLHSNull)
862 LHSExpr = CondExpr;
863
Chris Lattner4b009652007-07-25 00:24:17 +0000864 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
865 RHSExpr, QuestionLoc);
866 if (result.isNull())
867 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000868 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
869 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000870}
871
Steve Naroffdb65e052007-08-28 23:30:39 +0000872/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
873/// do not have a prototype. Integer promotions are performed on each
874/// argument, and arguments that have type float are promoted to double.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000875void Sema::DefaultArgumentPromotion(Expr *&Expr) {
876 QualType Ty = Expr->getType();
877 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000878
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000879 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
880 promoteExprToType(Expr, Context.IntTy);
881 if (Ty == Context.FloatTy)
882 promoteExprToType(Expr, Context.DoubleTy);
Steve Naroffdb65e052007-08-28 23:30:39 +0000883}
884
Chris Lattner4b009652007-07-25 00:24:17 +0000885/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
886void Sema::DefaultFunctionArrayConversion(Expr *&e) {
887 QualType t = e->getType();
888 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
889
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000890 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000891 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
892 t = e->getType();
893 }
894 if (t->isFunctionType())
895 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000896 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000897 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
898}
899
900/// UsualUnaryConversion - Performs various conversions that are common to most
901/// operators (C99 6.3). The conversions of array and function types are
902/// sometimes surpressed. For example, the array->pointer conversion doesn't
903/// apply if the array is an argument to the sizeof or address (&) operators.
904/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000905Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
906 QualType Ty = Expr->getType();
907 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000908
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000909 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
910 promoteExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
911 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000912 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000913 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
914 promoteExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000915 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000916 DefaultFunctionArrayConversion(Expr);
917
918 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000919}
920
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000921/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000922/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
923/// routine returns the first non-arithmetic type found. The client is
924/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000925QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
926 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000927 if (!isCompAssign) {
928 UsualUnaryConversions(lhsExpr);
929 UsualUnaryConversions(rhsExpr);
930 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000931 // For conversion purposes, we ignore any qualifiers.
932 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000933 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
934 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000935
936 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000937 if (lhs == rhs)
938 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000939
940 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
941 // The caller can deal with this (e.g. pointer + int).
942 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000943 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000944
945 // At this point, we have two different arithmetic types.
946
947 // Handle complex types first (C99 6.3.1.8p1).
948 if (lhs->isComplexType() || rhs->isComplexType()) {
949 // if we have an integer operand, the result is the complex type.
950 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000951 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
952 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000953 }
954 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000955 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
956 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000957 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000958 // This handles complex/complex, complex/float, or float/complex.
959 // When both operands are complex, the shorter operand is converted to the
960 // type of the longer, and that is the type of the result. This corresponds
961 // to what is done when combining two real floating-point operands.
962 // The fun begins when size promotion occur across type domains.
963 // From H&S 6.3.4: When one operand is complex and the other is a real
964 // floating-point type, the less precise type is converted, within it's
965 // real or complex domain, to the precision of the other type. For example,
966 // when combining a "long double" with a "double _Complex", the
967 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000968 int result = Context.compareFloatingType(lhs, rhs);
969
970 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000971 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
972 if (!isCompAssign)
973 promoteExprToType(rhsExpr, rhs);
974 } else if (result < 0) { // The right side is bigger, convert lhs.
975 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
976 if (!isCompAssign)
977 promoteExprToType(lhsExpr, lhs);
978 }
979 // At this point, lhs and rhs have the same rank/size. Now, make sure the
980 // domains match. This is a requirement for our implementation, C99
981 // does not require this promotion.
982 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
983 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000984 if (!isCompAssign)
985 promoteExprToType(lhsExpr, rhs);
986 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000987 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000988 if (!isCompAssign)
989 promoteExprToType(rhsExpr, lhs);
990 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000991 }
Chris Lattner4b009652007-07-25 00:24:17 +0000992 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000993 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000994 }
995 // Now handle "real" floating types (i.e. float, double, long double).
996 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
997 // if we have an integer operand, the result is the real floating type.
998 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000999 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1000 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001001 }
1002 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001003 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1004 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001005 }
1006 // We have two real floating types, float/complex combos were handled above.
1007 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001008 int result = Context.compareFloatingType(lhs, rhs);
1009
1010 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001011 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1012 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001013 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001014 if (result < 0) { // convert the lhs
1015 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1016 return rhs;
1017 }
1018 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001019 }
1020 // Finally, we have two differing integer types.
1021 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001022 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1023 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001024 }
Steve Naroff8f708362007-08-24 19:07:16 +00001025 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1026 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001027}
1028
1029// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1030// being closely modeled after the C99 spec:-). The odd characteristic of this
1031// routine is it effectively iqnores the qualifiers on the top level pointee.
1032// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1033// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001034Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001035Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1036 QualType lhptee, rhptee;
1037
1038 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001039 lhptee = lhsType->getAsPointerType()->getPointeeType();
1040 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001041
1042 // make sure we operate on the canonical type
1043 lhptee = lhptee.getCanonicalType();
1044 rhptee = rhptee.getCanonicalType();
1045
Chris Lattner005ed752008-01-04 18:04:52 +00001046 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001047
1048 // C99 6.5.16.1p1: This following citation is common to constraints
1049 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1050 // qualifiers of the type *pointed to* by the right;
1051 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1052 rhptee.getQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001053 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001054
1055 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1056 // incomplete type and the other is a pointer to a qualified or unqualified
1057 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001058 if (lhptee->isVoidType()) {
1059 if (rhptee->isObjectType() || rhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001060 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001061
1062 // As an extension, we allow cast to/from void* to function pointer.
1063 if (rhptee->isFunctionType())
1064 return FunctionVoidPointer;
1065 }
1066
1067 if (rhptee->isVoidType()) {
1068 if (lhptee->isObjectType() || lhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001069 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001070
1071 // As an extension, we allow cast to/from void* to function pointer.
1072 if (lhptee->isFunctionType())
1073 return FunctionVoidPointer;
1074 }
1075
Chris Lattner4b009652007-07-25 00:24:17 +00001076 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1077 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001078 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1079 rhptee.getUnqualifiedType()))
1080 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001081 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001082}
1083
1084/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1085/// has code to accommodate several GCC extensions when type checking
1086/// pointers. Here are some objectionable examples that GCC considers warnings:
1087///
1088/// int a, *pint;
1089/// short *pshort;
1090/// struct foo *pfoo;
1091///
1092/// pint = pshort; // warning: assignment from incompatible pointer type
1093/// a = pint; // warning: assignment makes integer from pointer without a cast
1094/// pint = a; // warning: assignment makes pointer from integer without a cast
1095/// pint = pfoo; // warning: assignment from incompatible pointer type
1096///
1097/// As a result, the code for dealing with pointers is more complex than the
1098/// C99 spec dictates.
1099/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1100///
Chris Lattner005ed752008-01-04 18:04:52 +00001101Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001102Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001103 // Get canonical types. We're not formatting these types, just comparing
1104 // them.
1105 lhsType = lhsType.getCanonicalType();
1106 rhsType = rhsType.getCanonicalType();
1107
1108 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001109 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001110
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001111 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001112 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001113 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001114 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001115 }
Chris Lattner1853da22008-01-04 23:18:45 +00001116
Ted Kremenek42730c52008-01-07 19:49:32 +00001117 if (lhsType->isObjCQualifiedIdType()
1118 || rhsType->isObjCQualifiedIdType()) {
1119 if (Context.ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001120 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001121 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001122 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001123
1124 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1125 // For OCUVector, allow vector splats; float -> <n x float>
1126 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1127 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1128 return Compatible;
1129 }
1130
1131 // If LHS and RHS are both vectors of integer or both vectors of floating
1132 // point types, and the total vector length is the same, allow the
1133 // conversion. This is a bitcast; no bits are changed but the result type
1134 // is different.
1135 if (getLangOptions().LaxVectorConversions &&
1136 lhsType->isVectorType() && rhsType->isVectorType()) {
1137 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1138 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
1139 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1140 Context.getTypeSize(rhsType, SourceLocation()))
Nate Begemanec2d1062007-12-30 02:59:45 +00001141 return Compatible;
1142 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001143 }
1144 return Incompatible;
1145 }
1146
1147 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001148 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001149
1150 if (lhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001151 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001152 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001153
1154 if (rhsType->isPointerType())
1155 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001156 return Incompatible;
1157 }
1158
1159 if (rhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001160 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1161 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001162 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001163
1164 if (lhsType->isPointerType())
1165 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001166 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001167 }
1168
1169 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001170 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001171 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001172 }
1173 return Incompatible;
1174}
1175
Chris Lattner005ed752008-01-04 18:04:52 +00001176Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001177Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001178 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1179 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001180 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001181 && rExpr->isNullPointerConstant(Context)) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001182 promoteExprToType(rExpr, lhsType);
1183 return Compatible;
1184 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001185 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001186 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001187 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001188 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001189 //
1190 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1191 // are better understood.
1192 if (!lhsType->isReferenceType())
1193 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001194
Chris Lattner005ed752008-01-04 18:04:52 +00001195 Sema::AssignConvertType result =
1196 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001197
1198 // C99 6.5.16.1p2: The value of the right operand is converted to the
1199 // type of the assignment expression.
1200 if (rExpr->getType() != lhsType)
1201 promoteExprToType(rExpr, lhsType);
1202 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001203}
1204
Chris Lattner005ed752008-01-04 18:04:52 +00001205Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001206Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1207 return CheckAssignmentConstraints(lhsType, rhsType);
1208}
1209
Chris Lattner2c8bff72007-12-12 05:47:28 +00001210QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001211 Diag(loc, diag::err_typecheck_invalid_operands,
1212 lex->getType().getAsString(), rex->getType().getAsString(),
1213 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001214 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001215}
1216
1217inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1218 Expr *&rex) {
1219 QualType lhsType = lex->getType(), rhsType = rex->getType();
1220
1221 // make sure the vector types are identical.
1222 if (lhsType == rhsType)
1223 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001224
1225 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1226 // promote the rhs to the vector type.
1227 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1228 if (V->getElementType().getCanonicalType().getTypePtr()
1229 == rhsType.getCanonicalType().getTypePtr()) {
1230 promoteExprToType(rex, lhsType);
1231 return lhsType;
1232 }
1233 }
1234
1235 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1236 // promote the lhs to the vector type.
1237 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1238 if (V->getElementType().getCanonicalType().getTypePtr()
1239 == lhsType.getCanonicalType().getTypePtr()) {
1240 promoteExprToType(lex, rhsType);
1241 return rhsType;
1242 }
1243 }
1244
Chris Lattner4b009652007-07-25 00:24:17 +00001245 // You cannot convert between vector values of different size.
1246 Diag(loc, diag::err_typecheck_vector_not_convertable,
1247 lex->getType().getAsString(), rex->getType().getAsString(),
1248 lex->getSourceRange(), rex->getSourceRange());
1249 return QualType();
1250}
1251
1252inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001253 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001254{
1255 QualType lhsType = lex->getType(), rhsType = rex->getType();
1256
1257 if (lhsType->isVectorType() || rhsType->isVectorType())
1258 return CheckVectorOperands(loc, lex, rex);
1259
Steve Naroff8f708362007-08-24 19:07:16 +00001260 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001261
Chris Lattner4b009652007-07-25 00:24:17 +00001262 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001263 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001264 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001265}
1266
1267inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001268 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001269{
1270 QualType lhsType = lex->getType(), rhsType = rex->getType();
1271
Steve Naroff8f708362007-08-24 19:07:16 +00001272 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001273
Chris Lattner4b009652007-07-25 00:24:17 +00001274 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001275 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001276 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001277}
1278
1279inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001280 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001281{
1282 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1283 return CheckVectorOperands(loc, lex, rex);
1284
Steve Naroff8f708362007-08-24 19:07:16 +00001285 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001286
1287 // handle the common case first (both operands are arithmetic).
1288 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001289 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001290
1291 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1292 return lex->getType();
1293 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1294 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001295 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001296}
1297
1298inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001299 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001300{
1301 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1302 return CheckVectorOperands(loc, lex, rex);
1303
Steve Naroff8f708362007-08-24 19:07:16 +00001304 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001305
Chris Lattnerf6da2912007-12-09 21:53:25 +00001306 // Enforce type constraints: C99 6.5.6p3.
1307
1308 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001309 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001310 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001311
1312 // Either ptr - int or ptr - ptr.
1313 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1314 // The LHS must be an object type, not incomplete, function, etc.
1315 if (!LHSPTy->getPointeeType()->isObjectType()) {
1316 // Handle the GNU void* extension.
1317 if (LHSPTy->getPointeeType()->isVoidType()) {
1318 Diag(loc, diag::ext_gnu_void_ptr,
1319 lex->getSourceRange(), rex->getSourceRange());
1320 } else {
1321 Diag(loc, diag::err_typecheck_sub_ptr_object,
1322 lex->getType().getAsString(), lex->getSourceRange());
1323 return QualType();
1324 }
1325 }
1326
1327 // The result type of a pointer-int computation is the pointer type.
1328 if (rex->getType()->isIntegerType())
1329 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001330
Chris Lattnerf6da2912007-12-09 21:53:25 +00001331 // Handle pointer-pointer subtractions.
1332 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1333 // RHS must be an object type, unless void (GNU).
1334 if (!RHSPTy->getPointeeType()->isObjectType()) {
1335 // Handle the GNU void* extension.
1336 if (RHSPTy->getPointeeType()->isVoidType()) {
1337 if (!LHSPTy->getPointeeType()->isVoidType())
1338 Diag(loc, diag::ext_gnu_void_ptr,
1339 lex->getSourceRange(), rex->getSourceRange());
1340 } else {
1341 Diag(loc, diag::err_typecheck_sub_ptr_object,
1342 rex->getType().getAsString(), rex->getSourceRange());
1343 return QualType();
1344 }
1345 }
1346
1347 // Pointee types must be compatible.
1348 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1349 RHSPTy->getPointeeType())) {
1350 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1351 lex->getType().getAsString(), rex->getType().getAsString(),
1352 lex->getSourceRange(), rex->getSourceRange());
1353 return QualType();
1354 }
1355
1356 return Context.getPointerDiffType();
1357 }
1358 }
1359
Chris Lattner2c8bff72007-12-12 05:47:28 +00001360 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001361}
1362
1363inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattner2c8bff72007-12-12 05:47:28 +00001364 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1365 // C99 6.5.7p2: Each of the operands shall have integer type.
1366 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1367 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001368
Chris Lattner2c8bff72007-12-12 05:47:28 +00001369 // Shifts don't perform usual arithmetic conversions, they just do integer
1370 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001371 if (!isCompAssign)
1372 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001373 UsualUnaryConversions(rex);
1374
1375 // "The type of the result is that of the promoted left operand."
1376 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001377}
1378
Chris Lattner254f3bc2007-08-26 01:18:55 +00001379inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1380 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001381{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001382 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001383 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1384 UsualArithmeticConversions(lex, rex);
1385 else {
1386 UsualUnaryConversions(lex);
1387 UsualUnaryConversions(rex);
1388 }
Chris Lattner4b009652007-07-25 00:24:17 +00001389 QualType lType = lex->getType();
1390 QualType rType = rex->getType();
1391
Ted Kremenek486509e2007-10-29 17:13:39 +00001392 // For non-floating point types, check for self-comparisons of the form
1393 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1394 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001395 if (!lType->isFloatingType()) {
1396 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1397 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1398 if (DRL->getDecl() == DRR->getDecl())
1399 Diag(loc, diag::warn_selfcomparison);
1400 }
1401
Chris Lattner254f3bc2007-08-26 01:18:55 +00001402 if (isRelational) {
1403 if (lType->isRealType() && rType->isRealType())
1404 return Context.IntTy;
1405 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001406 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001407 if (lType->isFloatingType()) {
1408 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001409 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001410 }
1411
Chris Lattner254f3bc2007-08-26 01:18:55 +00001412 if (lType->isArithmeticType() && rType->isArithmeticType())
1413 return Context.IntTy;
1414 }
Chris Lattner4b009652007-07-25 00:24:17 +00001415
Chris Lattner22be8422007-08-26 01:10:14 +00001416 bool LHSIsNull = lex->isNullPointerConstant(Context);
1417 bool RHSIsNull = rex->isNullPointerConstant(Context);
1418
Chris Lattner254f3bc2007-08-26 01:18:55 +00001419 // All of the following pointer related warnings are GCC extensions, except
1420 // when handling null pointer constants. One day, we can consider making them
1421 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001422 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001423
1424 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1425 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1426 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001427 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1428 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001429 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1430 lType.getAsString(), rType.getAsString(),
1431 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001432 }
Chris Lattner22be8422007-08-26 01:10:14 +00001433 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001434 return Context.IntTy;
1435 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001436 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
1437 && Context.ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001438 promoteExprToType(rex, lType);
1439 return Context.IntTy;
1440 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001441 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001442 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001443 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1444 lType.getAsString(), rType.getAsString(),
1445 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001446 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001447 return Context.IntTy;
1448 }
1449 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001450 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001451 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1452 lType.getAsString(), rType.getAsString(),
1453 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001454 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001455 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001456 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001457 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001458}
1459
Chris Lattner4b009652007-07-25 00:24:17 +00001460inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001461 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001462{
1463 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1464 return CheckVectorOperands(loc, lex, rex);
1465
Steve Naroff8f708362007-08-24 19:07:16 +00001466 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001467
1468 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001469 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001470 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001471}
1472
1473inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1474 Expr *&lex, Expr *&rex, SourceLocation loc)
1475{
1476 UsualUnaryConversions(lex);
1477 UsualUnaryConversions(rex);
1478
1479 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1480 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001481 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001482}
1483
1484inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001485 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001486{
1487 QualType lhsType = lex->getType();
1488 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001489 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1490
1491 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001492 case Expr::MLV_Valid:
1493 break;
1494 case Expr::MLV_ConstQualified:
1495 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1496 return QualType();
1497 case Expr::MLV_ArrayType:
1498 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1499 lhsType.getAsString(), lex->getSourceRange());
1500 return QualType();
1501 case Expr::MLV_NotObjectType:
1502 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1503 lhsType.getAsString(), lex->getSourceRange());
1504 return QualType();
1505 case Expr::MLV_InvalidExpression:
1506 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1507 lex->getSourceRange());
1508 return QualType();
1509 case Expr::MLV_IncompleteType:
1510 case Expr::MLV_IncompleteVoidType:
1511 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1512 lhsType.getAsString(), lex->getSourceRange());
1513 return QualType();
1514 case Expr::MLV_DuplicateVectorComponents:
1515 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1516 lex->getSourceRange());
1517 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001518 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001519
Chris Lattner005ed752008-01-04 18:04:52 +00001520 AssignConvertType ConvTy;
1521 if (compoundType.isNull())
1522 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1523 else
1524 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1525
1526 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1527 rex, "assigning"))
1528 return QualType();
1529
Chris Lattner4b009652007-07-25 00:24:17 +00001530 // C99 6.5.16p3: The type of an assignment expression is the type of the
1531 // left operand unless the left operand has qualified type, in which case
1532 // it is the unqualified version of the type of the left operand.
1533 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1534 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001535 // C++ 5.17p1: the type of the assignment expression is that of its left
1536 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001537 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001538}
1539
1540inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1541 Expr *&lex, Expr *&rex, SourceLocation loc) {
1542 UsualUnaryConversions(rex);
1543 return rex->getType();
1544}
1545
1546/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1547/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1548QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1549 QualType resType = op->getType();
1550 assert(!resType.isNull() && "no type for increment/decrement expression");
1551
Steve Naroffd30e1932007-08-24 17:20:07 +00001552 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001553 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001554 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1555 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1556 resType.getAsString(), op->getSourceRange());
1557 return QualType();
1558 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001559 } else if (!resType->isRealType()) {
1560 if (resType->isComplexType())
1561 // C99 does not support ++/-- on complex types.
1562 Diag(OpLoc, diag::ext_integer_increment_complex,
1563 resType.getAsString(), op->getSourceRange());
1564 else {
1565 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1566 resType.getAsString(), op->getSourceRange());
1567 return QualType();
1568 }
Chris Lattner4b009652007-07-25 00:24:17 +00001569 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001570 // At this point, we know we have a real, complex or pointer type.
1571 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001572 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1573 if (mlval != Expr::MLV_Valid) {
1574 // FIXME: emit a more precise diagnostic...
1575 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1576 op->getSourceRange());
1577 return QualType();
1578 }
1579 return resType;
1580}
1581
1582/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1583/// This routine allows us to typecheck complex/recursive expressions
1584/// where the declaration is needed for type checking. Here are some
1585/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1586static Decl *getPrimaryDeclaration(Expr *e) {
1587 switch (e->getStmtClass()) {
1588 case Stmt::DeclRefExprClass:
1589 return cast<DeclRefExpr>(e)->getDecl();
1590 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001591 // Fields cannot be declared with a 'register' storage class.
1592 // &X->f is always ok, even if X is declared register.
1593 if (cast<MemberExpr>(e)->isArrow())
1594 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001595 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1596 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001597 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001598 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001599 case Stmt::UnaryOperatorClass:
1600 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1601 case Stmt::ParenExprClass:
1602 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001603 case Stmt::ImplicitCastExprClass:
1604 // &X[4] when X is an array, has an implicit cast from array to pointer.
1605 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001606 default:
1607 return 0;
1608 }
1609}
1610
1611/// CheckAddressOfOperand - The operand of & must be either a function
1612/// designator or an lvalue designating an object. If it is an lvalue, the
1613/// object cannot be declared with storage class register or be a bit field.
1614/// Note: The usual conversions are *not* applied to the operand of the &
1615/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1616QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1617 Decl *dcl = getPrimaryDeclaration(op);
1618 Expr::isLvalueResult lval = op->isLvalue();
1619
1620 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001621 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1622 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001623 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1624 op->getSourceRange());
1625 return QualType();
1626 }
1627 } else if (dcl) {
1628 // We have an lvalue with a decl. Make sure the decl is not declared
1629 // with the register storage-class specifier.
1630 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1631 if (vd->getStorageClass() == VarDecl::Register) {
1632 Diag(OpLoc, diag::err_typecheck_address_of_register,
1633 op->getSourceRange());
1634 return QualType();
1635 }
1636 } else
1637 assert(0 && "Unknown/unexpected decl type");
1638
1639 // FIXME: add check for bitfields!
1640 }
1641 // If the operand has type "type", the result has type "pointer to type".
1642 return Context.getPointerType(op->getType());
1643}
1644
1645QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1646 UsualUnaryConversions(op);
1647 QualType qType = op->getType();
1648
Chris Lattner7931f4a2007-07-31 16:53:04 +00001649 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001650 QualType ptype = PT->getPointeeType();
1651 // C99 6.5.3.2p4. "if it points to an object,...".
1652 if (ptype->isIncompleteType()) { // An incomplete type is not an object
Chris Lattnerfabcc642008-01-06 22:21:46 +00001653 // GCC compat: special case 'void *' (treat as extension, not error).
Chris Lattner4b009652007-07-25 00:24:17 +00001654 if (ptype->isVoidType()) {
Chris Lattnerfabcc642008-01-06 22:21:46 +00001655 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001656 } else {
1657 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1658 ptype.getAsString(), op->getSourceRange());
1659 return QualType();
1660 }
1661 }
1662 return ptype;
1663 }
1664 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1665 qType.getAsString(), op->getSourceRange());
1666 return QualType();
1667}
1668
1669static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1670 tok::TokenKind Kind) {
1671 BinaryOperator::Opcode Opc;
1672 switch (Kind) {
1673 default: assert(0 && "Unknown binop!");
1674 case tok::star: Opc = BinaryOperator::Mul; break;
1675 case tok::slash: Opc = BinaryOperator::Div; break;
1676 case tok::percent: Opc = BinaryOperator::Rem; break;
1677 case tok::plus: Opc = BinaryOperator::Add; break;
1678 case tok::minus: Opc = BinaryOperator::Sub; break;
1679 case tok::lessless: Opc = BinaryOperator::Shl; break;
1680 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1681 case tok::lessequal: Opc = BinaryOperator::LE; break;
1682 case tok::less: Opc = BinaryOperator::LT; break;
1683 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1684 case tok::greater: Opc = BinaryOperator::GT; break;
1685 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1686 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1687 case tok::amp: Opc = BinaryOperator::And; break;
1688 case tok::caret: Opc = BinaryOperator::Xor; break;
1689 case tok::pipe: Opc = BinaryOperator::Or; break;
1690 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1691 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1692 case tok::equal: Opc = BinaryOperator::Assign; break;
1693 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1694 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1695 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1696 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1697 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1698 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1699 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1700 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1701 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1702 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1703 case tok::comma: Opc = BinaryOperator::Comma; break;
1704 }
1705 return Opc;
1706}
1707
1708static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1709 tok::TokenKind Kind) {
1710 UnaryOperator::Opcode Opc;
1711 switch (Kind) {
1712 default: assert(0 && "Unknown unary op!");
1713 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1714 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1715 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1716 case tok::star: Opc = UnaryOperator::Deref; break;
1717 case tok::plus: Opc = UnaryOperator::Plus; break;
1718 case tok::minus: Opc = UnaryOperator::Minus; break;
1719 case tok::tilde: Opc = UnaryOperator::Not; break;
1720 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1721 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1722 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1723 case tok::kw___real: Opc = UnaryOperator::Real; break;
1724 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1725 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1726 }
1727 return Opc;
1728}
1729
1730// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001731Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001732 ExprTy *LHS, ExprTy *RHS) {
1733 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1734 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1735
Steve Naroff87d58b42007-09-16 03:34:24 +00001736 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1737 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001738
1739 QualType ResultTy; // Result type of the binary operator.
1740 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1741
1742 switch (Opc) {
1743 default:
1744 assert(0 && "Unknown binary expr!");
1745 case BinaryOperator::Assign:
1746 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1747 break;
1748 case BinaryOperator::Mul:
1749 case BinaryOperator::Div:
1750 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1751 break;
1752 case BinaryOperator::Rem:
1753 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1754 break;
1755 case BinaryOperator::Add:
1756 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1757 break;
1758 case BinaryOperator::Sub:
1759 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1760 break;
1761 case BinaryOperator::Shl:
1762 case BinaryOperator::Shr:
1763 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1764 break;
1765 case BinaryOperator::LE:
1766 case BinaryOperator::LT:
1767 case BinaryOperator::GE:
1768 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001769 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001770 break;
1771 case BinaryOperator::EQ:
1772 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001773 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001774 break;
1775 case BinaryOperator::And:
1776 case BinaryOperator::Xor:
1777 case BinaryOperator::Or:
1778 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1779 break;
1780 case BinaryOperator::LAnd:
1781 case BinaryOperator::LOr:
1782 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1783 break;
1784 case BinaryOperator::MulAssign:
1785 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001786 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001787 if (!CompTy.isNull())
1788 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1789 break;
1790 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001791 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001792 if (!CompTy.isNull())
1793 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1794 break;
1795 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001796 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001797 if (!CompTy.isNull())
1798 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1799 break;
1800 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001801 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001802 if (!CompTy.isNull())
1803 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1804 break;
1805 case BinaryOperator::ShlAssign:
1806 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001807 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001808 if (!CompTy.isNull())
1809 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1810 break;
1811 case BinaryOperator::AndAssign:
1812 case BinaryOperator::XorAssign:
1813 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001814 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001815 if (!CompTy.isNull())
1816 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1817 break;
1818 case BinaryOperator::Comma:
1819 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1820 break;
1821 }
1822 if (ResultTy.isNull())
1823 return true;
1824 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001825 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001826 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001827 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001828}
1829
1830// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001831Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001832 ExprTy *input) {
1833 Expr *Input = (Expr*)input;
1834 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1835 QualType resultType;
1836 switch (Opc) {
1837 default:
1838 assert(0 && "Unimplemented unary expr!");
1839 case UnaryOperator::PreInc:
1840 case UnaryOperator::PreDec:
1841 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1842 break;
1843 case UnaryOperator::AddrOf:
1844 resultType = CheckAddressOfOperand(Input, OpLoc);
1845 break;
1846 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001847 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001848 resultType = CheckIndirectionOperand(Input, OpLoc);
1849 break;
1850 case UnaryOperator::Plus:
1851 case UnaryOperator::Minus:
1852 UsualUnaryConversions(Input);
1853 resultType = Input->getType();
1854 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1855 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1856 resultType.getAsString());
1857 break;
1858 case UnaryOperator::Not: // bitwise complement
1859 UsualUnaryConversions(Input);
1860 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001861 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1862 if (!resultType->isIntegerType()) {
1863 if (resultType->isComplexType())
1864 // C99 does not support '~' for complex conjugation.
1865 Diag(OpLoc, diag::ext_integer_complement_complex,
1866 resultType.getAsString());
1867 else
1868 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1869 resultType.getAsString());
1870 }
Chris Lattner4b009652007-07-25 00:24:17 +00001871 break;
1872 case UnaryOperator::LNot: // logical negation
1873 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1874 DefaultFunctionArrayConversion(Input);
1875 resultType = Input->getType();
1876 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1877 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1878 resultType.getAsString());
1879 // LNot always has type int. C99 6.5.3.3p5.
1880 resultType = Context.IntTy;
1881 break;
1882 case UnaryOperator::SizeOf:
1883 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1884 break;
1885 case UnaryOperator::AlignOf:
1886 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1887 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001888 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001889 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001890 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001891 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001892 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001893 resultType = Input->getType();
1894 break;
1895 }
1896 if (resultType.isNull())
1897 return true;
1898 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1899}
1900
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001901/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1902Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001903 SourceLocation LabLoc,
1904 IdentifierInfo *LabelII) {
1905 // Look up the record for this label identifier.
1906 LabelStmt *&LabelDecl = LabelMap[LabelII];
1907
1908 // If we haven't seen this label yet, create a forward reference.
1909 if (LabelDecl == 0)
1910 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1911
1912 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001913 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1914 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001915}
1916
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001917Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001918 SourceLocation RPLoc) { // "({..})"
1919 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1920 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1921 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1922
1923 // FIXME: there are a variety of strange constraints to enforce here, for
1924 // example, it is not possible to goto into a stmt expression apparently.
1925 // More semantic analysis is needed.
1926
1927 // FIXME: the last statement in the compount stmt has its value used. We
1928 // should not warn about it being unused.
1929
1930 // If there are sub stmts in the compound stmt, take the type of the last one
1931 // as the type of the stmtexpr.
1932 QualType Ty = Context.VoidTy;
1933
1934 if (!Compound->body_empty())
1935 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1936 Ty = LastExpr->getType();
1937
1938 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1939}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001940
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001941Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001942 SourceLocation TypeLoc,
1943 TypeTy *argty,
1944 OffsetOfComponent *CompPtr,
1945 unsigned NumComponents,
1946 SourceLocation RPLoc) {
1947 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1948 assert(!ArgTy.isNull() && "Missing type argument!");
1949
1950 // We must have at least one component that refers to the type, and the first
1951 // one is known to be a field designator. Verify that the ArgTy represents
1952 // a struct/union/class.
1953 if (!ArgTy->isRecordType())
1954 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1955
1956 // Otherwise, create a compound literal expression as the base, and
1957 // iteratively process the offsetof designators.
Chris Lattner386ab8a2008-01-02 21:46:24 +00001958 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001959
Chris Lattnerb37522e2007-08-31 21:49:13 +00001960 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1961 // GCC extension, diagnose them.
1962 if (NumComponents != 1)
1963 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1964 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1965
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001966 for (unsigned i = 0; i != NumComponents; ++i) {
1967 const OffsetOfComponent &OC = CompPtr[i];
1968 if (OC.isBrackets) {
1969 // Offset of an array sub-field. TODO: Should we allow vector elements?
1970 const ArrayType *AT = Res->getType()->getAsArrayType();
1971 if (!AT) {
1972 delete Res;
1973 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1974 Res->getType().getAsString());
1975 }
1976
Chris Lattner2af6a802007-08-30 17:59:59 +00001977 // FIXME: C++: Verify that operator[] isn't overloaded.
1978
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001979 // C99 6.5.2.1p1
1980 Expr *Idx = static_cast<Expr*>(OC.U.E);
1981 if (!Idx->getType()->isIntegerType())
1982 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1983 Idx->getSourceRange());
1984
1985 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1986 continue;
1987 }
1988
1989 const RecordType *RC = Res->getType()->getAsRecordType();
1990 if (!RC) {
1991 delete Res;
1992 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1993 Res->getType().getAsString());
1994 }
1995
1996 // Get the decl corresponding to this.
1997 RecordDecl *RD = RC->getDecl();
1998 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1999 if (!MemberDecl)
2000 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2001 OC.U.IdentInfo->getName(),
2002 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002003
2004 // FIXME: C++: Verify that MemberDecl isn't a static field.
2005 // FIXME: Verify that MemberDecl isn't a bitfield.
2006
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002007 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
2008 }
2009
2010 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2011 BuiltinLoc);
2012}
2013
2014
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002015Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002016 TypeTy *arg1, TypeTy *arg2,
2017 SourceLocation RPLoc) {
2018 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2019 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2020
2021 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2022
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002023 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002024}
2025
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002026Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002027 ExprTy *expr1, ExprTy *expr2,
2028 SourceLocation RPLoc) {
2029 Expr *CondExpr = static_cast<Expr*>(cond);
2030 Expr *LHSExpr = static_cast<Expr*>(expr1);
2031 Expr *RHSExpr = static_cast<Expr*>(expr2);
2032
2033 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2034
2035 // The conditional expression is required to be a constant expression.
2036 llvm::APSInt condEval(32);
2037 SourceLocation ExpLoc;
2038 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2039 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2040 CondExpr->getSourceRange());
2041
2042 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2043 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2044 RHSExpr->getType();
2045 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2046}
2047
Anders Carlsson36760332007-10-15 20:28:48 +00002048Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2049 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002050 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002051 Expr *E = static_cast<Expr*>(expr);
2052 QualType T = QualType::getFromOpaquePtr(type);
2053
2054 InitBuiltinVaListType();
2055
Chris Lattner005ed752008-01-04 18:04:52 +00002056 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2057 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002058 return Diag(E->getLocStart(),
2059 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2060 E->getType().getAsString(),
2061 E->getSourceRange());
2062
2063 // FIXME: Warn if a non-POD type is passed in.
2064
2065 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2066}
2067
Chris Lattner005ed752008-01-04 18:04:52 +00002068bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2069 SourceLocation Loc,
2070 QualType DstType, QualType SrcType,
2071 Expr *SrcExpr, const char *Flavor) {
2072 // Decode the result (notice that AST's are still created for extensions).
2073 bool isInvalid = false;
2074 unsigned DiagKind;
2075 switch (ConvTy) {
2076 default: assert(0 && "Unknown conversion type");
2077 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002078 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002079 DiagKind = diag::ext_typecheck_convert_pointer_int;
2080 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002081 case IntToPointer:
2082 DiagKind = diag::ext_typecheck_convert_int_pointer;
2083 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002084 case IncompatiblePointer:
2085 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2086 break;
2087 case FunctionVoidPointer:
2088 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2089 break;
2090 case CompatiblePointerDiscardsQualifiers:
2091 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2092 break;
2093 case Incompatible:
2094 DiagKind = diag::err_typecheck_convert_incompatible;
2095 isInvalid = true;
2096 break;
2097 }
2098
2099 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2100 SrcExpr->getSourceRange());
2101 return isInvalid;
2102}
2103