blob: 3c5a467edcf199dd2e83d251fb1b93cfcfe880ca [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"
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000017#include "clang/AST/DeclCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/Expr.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000021#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Lex/LiteralSupport.h"
24#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000026#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Steve Naroff87d58b42007-09-16 03:34:24 +000031/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000032/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
33/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
34/// multiple tokens. However, the common case is that StringToks points to one
35/// string.
36///
37Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000038Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000039 assert(NumStringToks && "Must have at least one string!");
40
41 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
42 if (Literal.hadError)
43 return ExprResult(true);
44
45 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
46 for (unsigned i = 0; i != NumStringToks; ++i)
47 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +000048
49 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000050 if (Literal.Pascal && Literal.GetStringLength() > 256)
51 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
52 SourceRange(StringToks[0].getLocation(),
53 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000054
Chris Lattnera6dcce32008-02-11 00:02:17 +000055 QualType StrTy = Context.CharTy;
Eli Friedman256b7d72008-05-27 07:57:14 +000056 if (Literal.AnyWide) StrTy = Context.getWcharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +000057 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
58
59 // Get an array type for the string, according to C99 6.4.5. This includes
60 // the nul terminator character as well as the string length for pascal
61 // strings.
62 StrTy = Context.getConstantArrayType(StrTy,
63 llvm::APInt(32, Literal.GetStringLength()+1),
64 ArrayType::Normal, 0);
65
Chris Lattner4b009652007-07-25 00:24:17 +000066 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
67 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +000068 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000069 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000070 StringToks[NumStringToks-1].getLocation());
71}
72
73
Steve Naroff0acc9c92007-09-15 18:49:24 +000074/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000075/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +000076/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000077Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000078 IdentifierInfo &II,
79 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000080 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +000081 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000082
83 // If this reference is in an Objective-C method, then ivar lookup happens as
84 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +000085 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +000086 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000087 // There are two cases to handle here. 1) scoped lookup could have failed,
88 // in which case we should look for an ivar. 2) scoped lookup could have
89 // found a decl, but that decl is outside the current method (i.e. a global
90 // variable). In these two cases, we do a lookup for an ivar with this
91 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +000092 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +000093 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +000094 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000095 // FIXME: This should use a new expr for a direct reference, don't turn
96 // this into Self->ivar, just return a BareIVarExpr or something.
97 IdentifierInfo &II = Context.Idents.get("self");
98 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
99 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
100 static_cast<Expr*>(SelfExpr.Val), true, true);
101 }
102 }
Steve Naroffe90d4cc2008-06-05 18:14:25 +0000103 if (SD == 0 && !strcmp(II.getName(), "super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000104 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000105 getCurMethodDecl()->getClassInterface()));
Steve Naroff6f786252008-06-02 23:03:37 +0000106 return new ObjCSuperRefExpr(T, Loc);
107 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000108 }
109
Chris Lattner4b009652007-07-25 00:24:17 +0000110 if (D == 0) {
111 // Otherwise, this could be an implicitly declared function reference (legal
112 // in C90, extension in C99).
113 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000114 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000115 D = ImplicitlyDefineFunction(Loc, II, S);
116 else {
117 // If this name wasn't predeclared and if this is not a function call,
118 // diagnose the problem.
119 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
120 }
121 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000122
Steve Naroff91b03f72007-08-28 03:03:08 +0000123 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000124 // check if referencing an identifier with __attribute__((deprecated)).
125 if (VD->getAttr<DeprecatedAttr>())
126 Diag(Loc, diag::warn_deprecated, VD->getName());
127
Steve Naroffcae537d2007-08-28 18:45:29 +0000128 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000129 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000130 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000131 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000132 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000133
134 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
135 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
136 if (MD->isStatic())
137 // "invalid use of member 'x' in static member function"
138 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
139 FD->getName());
140 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
141 // "invalid use of nonstatic data member 'x'"
142 return Diag(Loc, diag::err_invalid_non_static_member_use,
143 FD->getName());
144
145 if (FD->isInvalidDecl())
146 return true;
147
148 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
149 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
150 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
151 true, FD, Loc, FD->getType());
152 }
153
154 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
155 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000156
Chris Lattner4b009652007-07-25 00:24:17 +0000157 if (isa<TypedefDecl>(D))
158 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000159 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000160 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000161 if (isa<NamespaceDecl>(D))
162 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000163
164 assert(0 && "Invalid decl");
165 abort();
166}
167
Steve Naroff87d58b42007-09-16 03:34:24 +0000168Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000169 tok::TokenKind Kind) {
170 PreDefinedExpr::IdentType IT;
171
172 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000173 default: assert(0 && "Unknown simple primary expr!");
174 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
175 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
176 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000177 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000178
179 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000180 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000181 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000182
Chris Lattner7e637512008-01-12 08:14:25 +0000183 // Pre-defined identifiers are of type char[x], where x is the length of the
184 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000185 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000186 if (getCurFunctionDecl())
187 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000188 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000189 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000190
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000191 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000192 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000193 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000194 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000195}
196
Steve Naroff87d58b42007-09-16 03:34:24 +0000197Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000198 llvm::SmallString<16> CharBuffer;
199 CharBuffer.resize(Tok.getLength());
200 const char *ThisTokBegin = &CharBuffer[0];
201 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
202
203 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
204 Tok.getLocation(), PP);
205 if (Literal.hadError())
206 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000207
208 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
209
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000210 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
211 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000212}
213
Steve Naroff87d58b42007-09-16 03:34:24 +0000214Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000215 // fast path for a single digit (which is quite common). A single digit
216 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
217 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000218 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000219
Chris Lattner8cd0e932008-03-05 18:54:05 +0000220 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000221 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000222 Context.IntTy,
223 Tok.getLocation()));
224 }
225 llvm::SmallString<512> IntegerBuffer;
226 IntegerBuffer.resize(Tok.getLength());
227 const char *ThisTokBegin = &IntegerBuffer[0];
228
229 // Get the spelling of the token, which eliminates trigraphs, etc.
230 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
231 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
232 Tok.getLocation(), PP);
233 if (Literal.hadError)
234 return ExprResult(true);
235
Chris Lattner1de66eb2007-08-26 03:42:43 +0000236 Expr *Res;
237
238 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000239 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000240 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000241 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000242 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000243 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000244 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000245 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000246
247 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
248
Ted Kremenekddedbe22007-11-29 00:56:49 +0000249 // isExact will be set by GetFloatValue().
250 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000251 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000252 Ty, Tok.getLocation());
253
Chris Lattner1de66eb2007-08-26 03:42:43 +0000254 } else if (!Literal.isIntegerLiteral()) {
255 return ExprResult(true);
256 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000257 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000258
Neil Booth7421e9c2007-08-29 22:00:19 +0000259 // long long is a C99 feature.
260 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000261 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000262 Diag(Tok.getLocation(), diag::ext_longlong);
263
Chris Lattner4b009652007-07-25 00:24:17 +0000264 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000265 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000266
267 if (Literal.GetIntegerValue(ResultVal)) {
268 // If this value didn't fit into uintmax_t, warn and force to ull.
269 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000270 Ty = Context.UnsignedLongLongTy;
271 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000272 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000273 } else {
274 // If this value fits into a ULL, try to figure out what else it fits into
275 // according to the rules of C99 6.4.4.1p5.
276
277 // Octal, Hexadecimal, and integers with a U suffix are allowed to
278 // be an unsigned int.
279 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
280
281 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000282 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000283 if (!Literal.isLong && !Literal.isLongLong) {
284 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000285 unsigned IntSize = Context.Target.getIntWidth();
286
Chris Lattner4b009652007-07-25 00:24:17 +0000287 // Does it fit in a unsigned int?
288 if (ResultVal.isIntN(IntSize)) {
289 // Does it fit in a signed int?
290 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000291 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000292 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000293 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000294 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000295 }
Chris Lattner4b009652007-07-25 00:24:17 +0000296 }
297
298 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000299 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000300 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000301
302 // Does it fit in a unsigned long?
303 if (ResultVal.isIntN(LongSize)) {
304 // Does it fit in a signed long?
305 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000306 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000307 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000308 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000309 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000310 }
Chris Lattner4b009652007-07-25 00:24:17 +0000311 }
312
313 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000314 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000315 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000316
317 // Does it fit in a unsigned long long?
318 if (ResultVal.isIntN(LongLongSize)) {
319 // Does it fit in a signed long long?
320 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000321 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000322 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000323 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000324 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000325 }
326 }
327
328 // If we still couldn't decide a type, we probably have something that
329 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000330 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000331 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000332 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000333 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000334 }
Chris Lattnere4068872008-05-09 05:59:00 +0000335
336 if (ResultVal.getBitWidth() != Width)
337 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000338 }
339
Chris Lattner48d7f382008-04-02 04:24:33 +0000340 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000341 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000342
343 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
344 if (Literal.isImaginary)
345 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
346
347 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000348}
349
Steve Naroff87d58b42007-09-16 03:34:24 +0000350Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000351 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000352 Expr *E = (Expr *)Val;
353 assert((E != 0) && "ActOnParenExpr() missing expr");
354 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000355}
356
357/// The UsualUnaryConversions() function is *not* called by this routine.
358/// See C99 6.3.2.1p[2-4] for more details.
359QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
360 SourceLocation OpLoc, bool isSizeof) {
361 // C99 6.5.3.4p1:
362 if (isa<FunctionType>(exprType) && isSizeof)
363 // alignof(function) is allowed.
364 Diag(OpLoc, diag::ext_sizeof_function_type);
365 else if (exprType->isVoidType())
366 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
367 else if (exprType->isIncompleteType()) {
368 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
369 diag::err_alignof_incomplete_type,
370 exprType.getAsString());
371 return QualType(); // error
372 }
373 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
374 return Context.getSizeType();
375}
376
377Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000378ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000379 SourceLocation LPLoc, TypeTy *Ty,
380 SourceLocation RPLoc) {
381 // If error parsing type, ignore.
382 if (Ty == 0) return true;
383
384 // Verify that this is a valid expression.
385 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
386
387 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
388
389 if (resultType.isNull())
390 return true;
391 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
392}
393
Chris Lattner5110ad52007-08-24 21:41:10 +0000394QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000395 DefaultFunctionArrayConversion(V);
396
Chris Lattnera16e42d2007-08-26 05:39:26 +0000397 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000398 if (const ComplexType *CT = V->getType()->getAsComplexType())
399 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000400
401 // Otherwise they pass through real integer and floating point types here.
402 if (V->getType()->isArithmeticType())
403 return V->getType();
404
405 // Reject anything else.
406 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
407 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000408}
409
410
Chris Lattner4b009652007-07-25 00:24:17 +0000411
Steve Naroff87d58b42007-09-16 03:34:24 +0000412Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000413 tok::TokenKind Kind,
414 ExprTy *Input) {
415 UnaryOperator::Opcode Opc;
416 switch (Kind) {
417 default: assert(0 && "Unknown unary op!");
418 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
419 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
420 }
421 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
422 if (result.isNull())
423 return true;
424 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
425}
426
427Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000428ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000429 ExprTy *Idx, SourceLocation RLoc) {
430 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
431
432 // Perform default conversions.
433 DefaultFunctionArrayConversion(LHSExp);
434 DefaultFunctionArrayConversion(RHSExp);
435
436 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
437
438 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000439 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000440 // in the subscript position. As a result, we need to derive the array base
441 // and index from the expression types.
442 Expr *BaseExpr, *IndexExpr;
443 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000444 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000445 BaseExpr = LHSExp;
446 IndexExpr = RHSExp;
447 // FIXME: need to deal with const...
448 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000449 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000450 // Handle the uncommon case of "123[Ptr]".
451 BaseExpr = RHSExp;
452 IndexExpr = LHSExp;
453 // FIXME: need to deal with const...
454 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000455 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
456 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000457 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000458
459 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000460 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
461 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000462 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000463 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000464 // FIXME: need to deal with const...
465 ResultType = VTy->getElementType();
466 } else {
467 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
468 RHSExp->getSourceRange());
469 }
470 // C99 6.5.2.1p1
471 if (!IndexExpr->getType()->isIntegerType())
472 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
473 IndexExpr->getSourceRange());
474
475 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
476 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000477 // void (*)(int)) and pointers to incomplete types. Functions are not
478 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000479 if (!ResultType->isObjectType())
480 return Diag(BaseExpr->getLocStart(),
481 diag::err_typecheck_subscript_not_object,
482 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
483
484 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
485}
486
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000487QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000488CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000489 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000490 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000491
492 // This flag determines whether or not the component is to be treated as a
493 // special name, or a regular GLSL-style component access.
494 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000495
496 // The vector accessor can't exceed the number of elements.
497 const char *compStr = CompName.getName();
498 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000499 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000500 baseType.getAsString(), SourceRange(CompLoc));
501 return QualType();
502 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000503
504 // Check that we've found one of the special components, or that the component
505 // names must come from the same set.
506 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
507 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
508 SpecialComponent = true;
509 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000510 do
511 compStr++;
512 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
513 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
514 do
515 compStr++;
516 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
517 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
518 do
519 compStr++;
520 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
521 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000522
Nate Begemanc8e51f82008-05-09 06:41:27 +0000523 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000524 // We didn't get to the end of the string. This means the component names
525 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000526 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000527 std::string(compStr,compStr+1), SourceRange(CompLoc));
528 return QualType();
529 }
530 // Each component accessor can't exceed the vector type.
531 compStr = CompName.getName();
532 while (*compStr) {
533 if (vecType->isAccessorWithinNumElements(*compStr))
534 compStr++;
535 else
536 break;
537 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000538 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000539 // We didn't get to the end of the string. This means a component accessor
540 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000541 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000542 baseType.getAsString(), SourceRange(CompLoc));
543 return QualType();
544 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000545
546 // If we have a special component name, verify that the current vector length
547 // is an even number, since all special component names return exactly half
548 // the elements.
549 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
550 return QualType();
551 }
552
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000553 // The component accessor looks fine - now we need to compute the actual type.
554 // The vector type is implied by the component accessor. For example,
555 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000556 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
557 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
558 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000559 if (CompSize == 1)
560 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000561
Nate Begemanaf6ed502008-04-18 23:10:10 +0000562 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000563 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000564 // diagostics look bad. We want extended vector types to appear built-in.
565 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
566 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
567 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000568 }
569 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000570}
571
Chris Lattner4b009652007-07-25 00:24:17 +0000572Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000573ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000574 tok::TokenKind OpKind, SourceLocation MemberLoc,
575 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000576 Expr *BaseExpr = static_cast<Expr *>(Base);
577 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000578
579 // Perform default conversions.
580 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000581
Steve Naroff2cb66382007-07-26 03:11:44 +0000582 QualType BaseType = BaseExpr->getType();
583 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000584
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000585 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
586 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000587 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000588 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000589 BaseType = PT->getPointeeType();
590 else
591 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
592 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000593 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000594
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000595 // Handle field access to simple records. This also handles access to fields
596 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000597 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000598 RecordDecl *RDecl = RTy->getDecl();
599 if (RTy->isIncompleteType())
600 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
601 BaseExpr->getSourceRange());
602 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000603 FieldDecl *MemberDecl = RDecl->getMember(&Member);
604 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000605 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
606 SourceRange(MemberLoc));
Eli Friedman76b49832008-02-06 22:48:16 +0000607
608 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000609 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000610 QualType MemberType = MemberDecl->getType();
611 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000612 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000613 MemberType = MemberType.getQualifiedType(combinedQualifiers);
614
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000615 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000616 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000617 }
618
619 // Handle access to Objective C instance variables, such as "Obj->ivar".
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000620 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
621 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000622 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000623 OpKind == tok::arrow);
Chris Lattner52292be2008-07-21 04:42:08 +0000624 return Diag(OpLoc, diag::err_typecheck_member_reference_ivar,
625 IFTy->getDecl()->getName(), Member.getName(),
626 BaseExpr->getSourceRange(), SourceRange(MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +0000627 }
628
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000629 // Handle property access.
Chris Lattnera57cf472008-07-21 04:28:12 +0000630 if (isObjCObjectPointerType(BaseType)) {
631 const PointerType *pointerType = BaseType->getAsPointerType();
Steve Naroff05391d22008-05-30 00:40:33 +0000632 BaseType = pointerType->getPointeeType();
633 ObjCInterfaceDecl *IFace;
Steve Naroffd1f0eb42008-06-05 13:55:23 +0000634 QualType CanonType = BaseType.getCanonicalType();
635 if (isa<ObjCInterfaceType>(CanonType))
636 IFace = dyn_cast<ObjCInterfaceType>(CanonType)->getDecl();
Steve Naroff05391d22008-05-30 00:40:33 +0000637 else
Steve Naroffd1f0eb42008-06-05 13:55:23 +0000638 IFace = dyn_cast<ObjCQualifiedInterfaceType>(CanonType)->getDecl();
Chris Lattnered94f762008-07-21 04:44:44 +0000639 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member))
Steve Naroff05391d22008-05-30 00:40:33 +0000640 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
641 OpKind==tok::arrow);
642 // Check for properties.
643 if (OpKind==tok::period) {
644 // Before we look for explicit property declarations, we check for
645 // nullary methods (which allow '.' notation).
646 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
647 ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel);
648 if (MD)
649 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
650 MemberLoc, BaseExpr);
651 // FIXME: Need to deal with setter methods that take 1 argument. E.g.:
652 // @interface NSBundle : NSObject {}
653 // - (NSString *)bundlePath;
654 // - (void)setBundlePath:(NSString *)x;
655 // @end
656 // void someMethod() { frameworkBundle.bundlePath = 0; }
657 //
Steve Naroff858813d2008-06-03 21:56:14 +0000658 ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member);
Steve Naroffd1f0eb42008-06-05 13:55:23 +0000659
660 if (!PD) { // Lastly, check protocols on qualified interfaces.
661 if (ObjCQualifiedInterfaceType *QIT =
662 dyn_cast<ObjCQualifiedInterfaceType>(CanonType)) {
663 for (unsigned i = 0; i < QIT->getNumProtocols(); i++)
664 if ((PD = QIT->getProtocols(i)->FindPropertyDeclaration(&Member)))
665 break;
666 }
667 }
Steve Naroff858813d2008-06-03 21:56:14 +0000668 if (PD)
669 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Steve Naroff05391d22008-05-30 00:40:33 +0000670 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000671 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000672
673 // Handle 'field access' to vectors, such as 'V.xx'.
674 if (BaseType->isExtVectorType() && OpKind == tok::period) {
675 // Component access limited to variables (reject vec4.rg.g).
676 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
677 !isa<ExtVectorElementExpr>(BaseExpr))
678 return Diag(OpLoc, diag::err_ext_vector_component_access,
679 SourceRange(MemberLoc));
680 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
681 if (ret.isNull())
682 return true;
683 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
684 }
685
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000686 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
687 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000688}
689
Steve Naroff87d58b42007-09-16 03:34:24 +0000690/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000691/// This provides the location of the left/right parens and a list of comma
692/// locations.
693Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000694ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000695 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000696 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
697 Expr *Fn = static_cast<Expr *>(fn);
698 Expr **Args = reinterpret_cast<Expr**>(args);
699 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000700 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000701
702 // Promote the function operand.
703 UsualUnaryConversions(Fn);
704
705 // If we're directly calling a function, get the declaration for
706 // that function.
707 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
708 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
709 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
710
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000711 // Make the call expr early, before semantic checks. This guarantees cleanup
712 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000713 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000714 Context.BoolTy, RParenLoc));
715
Chris Lattner4b009652007-07-25 00:24:17 +0000716 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
717 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000718 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000719 if (PT == 0)
720 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
721 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000722 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
723 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000724 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
725 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000726
727 // We know the result type of the call, set it.
728 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000729
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000730 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000731 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
732 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000733 unsigned NumArgsInProto = Proto->getNumArgs();
734 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000735
Chris Lattner3e254fb2008-04-08 04:40:51 +0000736 // If too few arguments are available (and we don't have default
737 // arguments for the remaining parameters), don't make the call.
738 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +0000739 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000740 // Use default arguments for missing arguments
741 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +0000742 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000743 } else
744 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
745 Fn->getSourceRange());
746 }
747
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000748 // If too many are passed and not variadic, error on the extras and drop
749 // them.
750 if (NumArgs > NumArgsInProto) {
751 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000752 Diag(Args[NumArgsInProto]->getLocStart(),
753 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
754 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000755 Args[NumArgs-1]->getLocEnd()));
756 // This deletes the extra arguments.
757 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000758 }
759 NumArgsToCheck = NumArgsInProto;
760 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000761
Chris Lattner4b009652007-07-25 00:24:17 +0000762 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000763 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +0000764 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000765
766 Expr *Arg;
767 if (i < NumArgs)
768 Arg = Args[i];
769 else
770 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +0000771 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000772
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000773 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000774 AssignConvertType ConvTy =
775 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000776 TheCall->setArg(i, Arg);
777
Chris Lattner005ed752008-01-04 18:04:52 +0000778 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
779 ArgType, Arg, "passing"))
780 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000781 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000782
783 // If this is a variadic call, handle args passed through "...".
784 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000785 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000786 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
787 Expr *Arg = Args[i];
788 DefaultArgumentPromotion(Arg);
789 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000790 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000791 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000792 } else {
793 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
794
Steve Naroffdb65e052007-08-28 23:30:39 +0000795 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000796 for (unsigned i = 0; i != NumArgs; i++) {
797 Expr *Arg = Args[i];
798 DefaultArgumentPromotion(Arg);
799 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000800 }
Chris Lattner4b009652007-07-25 00:24:17 +0000801 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000802
Chris Lattner2e64c072007-08-10 20:18:51 +0000803 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +0000804 if (FDecl)
805 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +0000806
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000807 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000808}
809
810Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000811ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000812 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000813 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000814 QualType literalType = QualType::getFromOpaquePtr(Ty);
815 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000816 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000817 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000818
Eli Friedman8c2173d2008-05-20 05:22:08 +0000819 if (literalType->isArrayType()) {
820 if (literalType->getAsVariableArrayType())
821 return Diag(LParenLoc,
822 diag::err_variable_object_no_init,
823 SourceRange(LParenLoc,
824 literalExpr->getSourceRange().getEnd()));
825 } else if (literalType->isIncompleteType()) {
826 return Diag(LParenLoc,
827 diag::err_typecheck_decl_incomplete_type,
828 literalType.getAsString(),
829 SourceRange(LParenLoc,
830 literalExpr->getSourceRange().getEnd()));
831 }
832
Steve Narofff0b23542008-01-10 22:15:12 +0000833 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000834 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000835
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000836 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +0000837 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000838 if (CheckForConstantInitializer(literalExpr, literalType))
839 return true;
840 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000841 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000842}
843
844Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000845ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000846 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000847 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000848
Steve Naroff0acc9c92007-09-15 18:49:24 +0000849 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000850 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000851
Chris Lattner48d7f382008-04-02 04:24:33 +0000852 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
853 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
854 return E;
Chris Lattner4b009652007-07-25 00:24:17 +0000855}
856
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000857bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000858 assert(VectorTy->isVectorType() && "Not a vector type!");
859
860 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000861 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000862 return Diag(R.getBegin(),
863 Ty->isVectorType() ?
864 diag::err_invalid_conversion_between_vectors :
865 diag::err_invalid_conversion_between_vector_and_integer,
866 VectorTy.getAsString().c_str(),
867 Ty.getAsString().c_str(), R);
868 } else
869 return Diag(R.getBegin(),
870 diag::err_invalid_conversion_between_vector_and_scalar,
871 VectorTy.getAsString().c_str(),
872 Ty.getAsString().c_str(), R);
873
874 return false;
875}
876
Chris Lattner4b009652007-07-25 00:24:17 +0000877Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000878ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000879 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000880 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000881
882 Expr *castExpr = static_cast<Expr*>(Op);
883 QualType castType = QualType::getFromOpaquePtr(Ty);
884
Steve Naroff68adb482007-08-31 00:32:44 +0000885 UsualUnaryConversions(castExpr);
886
Chris Lattner4b009652007-07-25 00:24:17 +0000887 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
888 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000889 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Naroff5ad85292008-06-03 12:56:35 +0000890 if (!castType->isScalarType() && !castType->isVectorType()) {
891 // GCC struct/union extension.
892 if (castType == castExpr->getType() &&
Steve Naroff7f1c5b52008-06-03 13:21:30 +0000893 castType->isStructureType() || castType->isUnionType()) {
894 Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar,
895 SourceRange(LParenLoc, RParenLoc));
896 return new CastExpr(castType, castExpr, LParenLoc);
897 } else
Steve Naroff5ad85292008-06-03 12:56:35 +0000898 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
899 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
900 }
Steve Narofff459ee52008-01-24 22:55:05 +0000901 if (!castExpr->getType()->isScalarType() &&
902 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000903 return Diag(castExpr->getLocStart(),
904 diag::err_typecheck_expect_scalar_operand,
905 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000906
907 if (castExpr->getType()->isVectorType()) {
908 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
909 castExpr->getType(), castType))
910 return true;
911 } else if (castType->isVectorType()) {
912 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
913 castType, castExpr->getType()))
914 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000915 }
Chris Lattner4b009652007-07-25 00:24:17 +0000916 }
917 return new CastExpr(castType, castExpr, LParenLoc);
918}
919
Chris Lattner98a425c2007-11-26 01:40:58 +0000920/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
921/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000922inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
923 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
924 UsualUnaryConversions(cond);
925 UsualUnaryConversions(lex);
926 UsualUnaryConversions(rex);
927 QualType condT = cond->getType();
928 QualType lexT = lex->getType();
929 QualType rexT = rex->getType();
930
931 // first, check the condition.
932 if (!condT->isScalarType()) { // C99 6.5.15p2
933 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
934 condT.getAsString());
935 return QualType();
936 }
Chris Lattner992ae932008-01-06 22:42:25 +0000937
938 // Now check the two expressions.
939
940 // If both operands have arithmetic type, do the usual arithmetic conversions
941 // to find a common type: C99 6.5.15p3,5.
942 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000943 UsualArithmeticConversions(lex, rex);
944 return lex->getType();
945 }
Chris Lattner992ae932008-01-06 22:42:25 +0000946
947 // If both operands are the same structure or union type, the result is that
948 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000949 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000950 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000951 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000952 // "If both the operands have structure or union type, the result has
953 // that type." This implies that CV qualifiers are dropped.
954 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000955 }
Chris Lattner992ae932008-01-06 22:42:25 +0000956
957 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +0000958 // The following || allows only one side to be void (a GCC-ism).
959 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +0000960 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +0000961 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
962 rex->getSourceRange());
963 if (!rexT->isVoidType())
964 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +0000965 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +0000966 ImpCastExprToType(lex, Context.VoidTy);
967 ImpCastExprToType(rex, Context.VoidTy);
968 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +0000969 }
Steve Naroff12ebf272008-01-08 01:11:38 +0000970 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
971 // the type of the other operand."
972 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000973 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000974 return lexT;
975 }
976 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000977 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000978 return rexT;
979 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000980 // Handle the case where both operands are pointers before we handle null
981 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000982 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
983 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
984 // get the "pointed to" types
985 QualType lhptee = LHSPT->getPointeeType();
986 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000987
Chris Lattner71225142007-07-31 21:27:01 +0000988 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
989 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +0000990 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000991 // Figure out necessary qualifiers (C99 6.5.15p6)
992 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000993 QualType destType = Context.getPointerType(destPointee);
994 ImpCastExprToType(lex, destType); // add qualifiers if necessary
995 ImpCastExprToType(rex, destType); // promote to void*
996 return destType;
997 }
Chris Lattner9db553e2008-04-02 06:59:01 +0000998 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000999 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001000 QualType destType = Context.getPointerType(destPointee);
1001 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1002 ImpCastExprToType(rex, destType); // promote to void*
1003 return destType;
1004 }
Chris Lattner4b009652007-07-25 00:24:17 +00001005
Steve Naroff85f0dc52007-10-15 20:41:53 +00001006 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1007 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001008 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001009 lexT.getAsString(), rexT.getAsString(),
1010 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +00001011 // In this situation, we assume void* type. No especially good
1012 // reason, but this is what gcc does, and we do have to pick
1013 // to get a consistent AST.
1014 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
1015 ImpCastExprToType(lex, voidPtrTy);
1016 ImpCastExprToType(rex, voidPtrTy);
1017 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +00001018 }
1019 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001020 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1021 // differently qualified versions of compatible types, the result type is
1022 // a pointer to an appropriately qualified version of the *composite*
1023 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001024 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001025 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001026 QualType compositeType = lexT;
1027 ImpCastExprToType(lex, compositeType);
1028 ImpCastExprToType(rex, compositeType);
1029 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001030 }
Chris Lattner4b009652007-07-25 00:24:17 +00001031 }
Steve Naroff605896f2008-05-31 22:33:45 +00001032 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1033 // evaluates to "struct objc_object *" (and is handled above when comparing
1034 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType?
1035 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1036 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true))
1037 return Context.getObjCIdType();
1038 }
Chris Lattner992ae932008-01-06 22:42:25 +00001039 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001040 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1041 lexT.getAsString(), rexT.getAsString(),
1042 lex->getSourceRange(), rex->getSourceRange());
1043 return QualType();
1044}
1045
Steve Naroff87d58b42007-09-16 03:34:24 +00001046/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001047/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001048Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001049 SourceLocation ColonLoc,
1050 ExprTy *Cond, ExprTy *LHS,
1051 ExprTy *RHS) {
1052 Expr *CondExpr = (Expr *) Cond;
1053 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001054
1055 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1056 // was the condition.
1057 bool isLHSNull = LHSExpr == 0;
1058 if (isLHSNull)
1059 LHSExpr = CondExpr;
1060
Chris Lattner4b009652007-07-25 00:24:17 +00001061 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1062 RHSExpr, QuestionLoc);
1063 if (result.isNull())
1064 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001065 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1066 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001067}
1068
Steve Naroffdb65e052007-08-28 23:30:39 +00001069/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +00001070/// do not have a prototype. Arguments that have type float are promoted to
1071/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001072void Sema::DefaultArgumentPromotion(Expr *&Expr) {
1073 QualType Ty = Expr->getType();
1074 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +00001075
Chris Lattner11216032008-06-27 22:48:56 +00001076 // If this is a 'float' (CVR qualified or typedef) promote to double.
1077 if (const BuiltinType *BT = Ty->getAsBuiltinType())
1078 if (BT->getKind() == BuiltinType::Float)
1079 return ImpCastExprToType(Expr, Context.DoubleTy);
1080
1081 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +00001082}
1083
Chris Lattner4b009652007-07-25 00:24:17 +00001084/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Chris Lattner48d7f382008-04-02 04:24:33 +00001085void Sema::DefaultFunctionArrayConversion(Expr *&E) {
1086 QualType Ty = E->getType();
1087 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001088
Chris Lattner48d7f382008-04-02 04:24:33 +00001089 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +00001090 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
Chris Lattner48d7f382008-04-02 04:24:33 +00001091 Ty = E->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001092 }
Chris Lattner48d7f382008-04-02 04:24:33 +00001093 if (Ty->isFunctionType())
1094 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner19eb97e2008-04-02 05:18:44 +00001095 else if (Ty->isArrayType())
1096 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
Chris Lattner4b009652007-07-25 00:24:17 +00001097}
1098
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001099/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +00001100/// operators (C99 6.3). The conversions of array and function types are
1101/// sometimes surpressed. For example, the array->pointer conversion doesn't
1102/// apply if the array is an argument to the sizeof or address (&) operators.
1103/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001104Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
1105 QualType Ty = Expr->getType();
1106 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001107
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001108 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +00001109 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001110 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001111 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001112 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +00001113 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +00001114 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001115 DefaultFunctionArrayConversion(Expr);
1116
1117 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +00001118}
1119
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001120/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +00001121/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1122/// routine returns the first non-arithmetic type found. The client is
1123/// responsible for emitting appropriate error diagnostics.
Chris Lattner48d7f382008-04-02 04:24:33 +00001124/// FIXME: verify the conversion rules for "complex int" are consistent with
1125/// GCC.
Steve Naroff8f708362007-08-24 19:07:16 +00001126QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
1127 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +00001128 if (!isCompAssign) {
1129 UsualUnaryConversions(lhsExpr);
1130 UsualUnaryConversions(rhsExpr);
1131 }
Steve Naroff7438fdf2007-10-18 18:55:53 +00001132 // For conversion purposes, we ignore any qualifiers.
1133 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +00001134 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
1135 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001136
1137 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +00001138 if (lhs == rhs)
1139 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001140
1141 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1142 // The caller can deal with this (e.g. pointer + int).
1143 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001144 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001145
1146 // At this point, we have two different arithmetic types.
1147
1148 // Handle complex types first (C99 6.3.1.8p1).
1149 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +00001150 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001151 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001152 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001153 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001154 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +00001155 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001157 // convert the lhs to the rhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001158 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001159 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001160 }
Steve Naroff3cf497f2007-08-27 01:27:54 +00001161 // This handles complex/complex, complex/float, or float/complex.
1162 // When both operands are complex, the shorter operand is converted to the
1163 // type of the longer, and that is the type of the result. This corresponds
1164 // to what is done when combining two real floating-point operands.
1165 // The fun begins when size promotion occur across type domains.
1166 // From H&S 6.3.4: When one operand is complex and the other is a real
1167 // floating-point type, the less precise type is converted, within it's
1168 // real or complex domain, to the precision of the other type. For example,
1169 // when combining a "long double" with a "double _Complex", the
1170 // "double _Complex" is promoted to "long double _Complex".
Chris Lattnerd7135b42008-04-06 23:38:49 +00001171 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001172
1173 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001174 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1175 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001176 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001177 } else if (result < 0) { // The right side is bigger, convert lhs.
1178 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1179 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001180 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001181 }
1182 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1183 // domains match. This is a requirement for our implementation, C99
1184 // does not require this promotion.
1185 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1186 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001187 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001188 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001189 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001190 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001191 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001192 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001193 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001194 }
Chris Lattner4b009652007-07-25 00:24:17 +00001195 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001196 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001197 }
1198 // Now handle "real" floating types (i.e. float, double, long double).
1199 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1200 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001201 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001202 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001203 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001204 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001205 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001206 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001207 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001208 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001209 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001210 }
1211 // We have two real floating types, float/complex combos were handled above.
1212 // Convert the smaller operand to the bigger result.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001213 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001214
1215 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001216 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001217 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001218 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001219 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001220 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001221 return rhs;
1222 }
1223 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001224 }
Steve Naroff43001212008-01-15 19:36:10 +00001225 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1226 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001227 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001228 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001229
Eli Friedman50727042008-02-08 01:19:44 +00001230 if (lhsComplexInt && rhsComplexInt) {
Chris Lattner51285d82008-04-06 23:55:33 +00001231 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
1232 rhsComplexInt->getElementType()) >= 0) {
Eli Friedman94075c02008-02-08 01:24:30 +00001233 // convert the rhs
1234 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1235 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001236 }
1237 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001238 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001239 return rhs;
1240 } else if (lhsComplexInt && rhs->isIntegerType()) {
1241 // convert the rhs to the lhs complex type.
1242 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1243 return lhs;
1244 } else if (rhsComplexInt && lhs->isIntegerType()) {
1245 // convert the lhs to the rhs complex type.
1246 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1247 return rhs;
1248 }
Steve Naroff43001212008-01-15 19:36:10 +00001249 }
Chris Lattner4b009652007-07-25 00:24:17 +00001250 // Finally, we have two differing integer types.
Eli Friedman0832dbc2008-06-28 06:23:08 +00001251 // The rules for this case are in C99 6.3.1.8
1252 int compare = Context.getIntegerTypeOrder(lhs, rhs);
1253 bool lhsSigned = lhs->isSignedIntegerType(),
1254 rhsSigned = rhs->isSignedIntegerType();
1255 QualType destType;
1256 if (lhsSigned == rhsSigned) {
1257 // Same signedness; use the higher-ranked type
1258 destType = compare >= 0 ? lhs : rhs;
1259 } else if (compare != (lhsSigned ? 1 : -1)) {
1260 // The unsigned type has greater than or equal rank to the
1261 // signed type, so use the unsigned type
1262 destType = lhsSigned ? rhs : lhs;
1263 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
1264 // The two types are different widths; if we are here, that
1265 // means the signed type is larger than the unsigned type, so
1266 // use the signed type.
1267 destType = lhsSigned ? lhs : rhs;
1268 } else {
1269 // The signed type is higher-ranked than the unsigned type,
1270 // but isn't actually any bigger (like unsigned int and long
1271 // on most 32-bit systems). Use the unsigned type corresponding
1272 // to the signed type.
1273 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00001274 }
Eli Friedman0832dbc2008-06-28 06:23:08 +00001275 if (!isCompAssign) {
1276 ImpCastExprToType(lhsExpr, destType);
1277 ImpCastExprToType(rhsExpr, destType);
1278 }
1279 return destType;
Chris Lattner4b009652007-07-25 00:24:17 +00001280}
1281
1282// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1283// being closely modeled after the C99 spec:-). The odd characteristic of this
1284// routine is it effectively iqnores the qualifiers on the top level pointee.
1285// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1286// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001287Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001288Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1289 QualType lhptee, rhptee;
1290
1291 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001292 lhptee = lhsType->getAsPointerType()->getPointeeType();
1293 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001294
1295 // make sure we operate on the canonical type
1296 lhptee = lhptee.getCanonicalType();
1297 rhptee = rhptee.getCanonicalType();
1298
Chris Lattner005ed752008-01-04 18:04:52 +00001299 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001300
1301 // C99 6.5.16.1p1: This following citation is common to constraints
1302 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1303 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001304 // FIXME: Handle ASQualType
1305 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1306 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001307 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001308
1309 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1310 // incomplete type and the other is a pointer to a qualified or unqualified
1311 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001312 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001313 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001314 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001315
1316 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001317 assert(rhptee->isFunctionType());
1318 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001319 }
1320
1321 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001322 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001323 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001324
1325 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001326 assert(lhptee->isFunctionType());
1327 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001328 }
1329
Chris Lattner4b009652007-07-25 00:24:17 +00001330 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1331 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001332 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1333 rhptee.getUnqualifiedType()))
1334 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001335 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001336}
1337
1338/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1339/// has code to accommodate several GCC extensions when type checking
1340/// pointers. Here are some objectionable examples that GCC considers warnings:
1341///
1342/// int a, *pint;
1343/// short *pshort;
1344/// struct foo *pfoo;
1345///
1346/// pint = pshort; // warning: assignment from incompatible pointer type
1347/// a = pint; // warning: assignment makes integer from pointer without a cast
1348/// pint = a; // warning: assignment makes pointer from integer without a cast
1349/// pint = pfoo; // warning: assignment from incompatible pointer type
1350///
1351/// As a result, the code for dealing with pointers is more complex than the
1352/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001353///
Chris Lattner005ed752008-01-04 18:04:52 +00001354Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001355Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001356 // Get canonical types. We're not formatting these types, just comparing
1357 // them.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001358 lhsType = lhsType.getCanonicalType().getUnqualifiedType();
1359 rhsType = rhsType.getCanonicalType().getUnqualifiedType();
1360
1361 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001362 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001363
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001364 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001365 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001366 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001367 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001368 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001369
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001370 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1371 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001372 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001373 // Relax integer conversions like we do for pointers below.
1374 if (rhsType->isIntegerType())
1375 return IntToPointer;
1376 if (lhsType->isIntegerType())
1377 return PointerToInt;
Chris Lattner1853da22008-01-04 23:18:45 +00001378 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001379 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001380
Nate Begemanc5f0f652008-07-14 18:02:46 +00001381 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001382 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001383 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1384 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001385 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001386
Nate Begemanc5f0f652008-07-14 18:02:46 +00001387 // If we are allowing lax vector conversions, and LHS and RHS are both
1388 // vectors, the total size only needs to be the same. This is a bitcast;
1389 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001390 if (getLangOptions().LaxVectorConversions &&
1391 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001392 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1393 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001394 }
1395 return Incompatible;
1396 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001397
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001398 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001399 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001400
Chris Lattner390564e2008-04-07 06:49:41 +00001401 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001402 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001403 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001404
Chris Lattner390564e2008-04-07 06:49:41 +00001405 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001406 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001407 return Incompatible;
1408 }
1409
Chris Lattner390564e2008-04-07 06:49:41 +00001410 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001411 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001412 if (lhsType == Context.BoolTy)
1413 return Compatible;
1414
1415 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001416 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001417
Chris Lattner390564e2008-04-07 06:49:41 +00001418 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001419 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001420 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001421 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001422
Chris Lattner1853da22008-01-04 23:18:45 +00001423 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001424 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001425 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001426 }
1427 return Incompatible;
1428}
1429
Chris Lattner005ed752008-01-04 18:04:52 +00001430Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001431Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001432 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1433 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001434 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001435 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001436 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001437 return Compatible;
1438 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001439 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001440 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001441 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001442 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001443 //
1444 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1445 // are better understood.
1446 if (!lhsType->isReferenceType())
1447 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001448
Chris Lattner005ed752008-01-04 18:04:52 +00001449 Sema::AssignConvertType result =
1450 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001451
1452 // C99 6.5.16.1p2: The value of the right operand is converted to the
1453 // type of the assignment expression.
1454 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001455 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001456 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001457}
1458
Chris Lattner005ed752008-01-04 18:04:52 +00001459Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001460Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1461 return CheckAssignmentConstraints(lhsType, rhsType);
1462}
1463
Chris Lattner2c8bff72007-12-12 05:47:28 +00001464QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001465 Diag(loc, diag::err_typecheck_invalid_operands,
1466 lex->getType().getAsString(), rex->getType().getAsString(),
1467 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001468 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001469}
1470
1471inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1472 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001473 // For conversion purposes, we ignore any qualifiers.
1474 // For example, "const float" and "float" are equivalent.
1475 QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType();
1476 QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001477
Nate Begemanc5f0f652008-07-14 18:02:46 +00001478 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001479 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001480 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001481
Nate Begemanc5f0f652008-07-14 18:02:46 +00001482 // Handle the case of a vector & extvector type of the same size and element
1483 // type. It would be nice if we only had one vector type someday.
1484 if (getLangOptions().LaxVectorConversions)
1485 if (const VectorType *LV = lhsType->getAsVectorType())
1486 if (const VectorType *RV = rhsType->getAsVectorType())
1487 if (LV->getElementType() == RV->getElementType() &&
1488 LV->getNumElements() == RV->getNumElements())
1489 return lhsType->isExtVectorType() ? lhsType : rhsType;
1490
1491 // If the lhs is an extended vector and the rhs is a scalar of the same type
1492 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001493 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001494 QualType eltType = V->getElementType();
1495
1496 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1497 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1498 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001499 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001500 return lhsType;
1501 }
1502 }
1503
Nate Begemanc5f0f652008-07-14 18:02:46 +00001504 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001505 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001506 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001507 QualType eltType = V->getElementType();
1508
1509 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1510 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1511 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001512 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001513 return rhsType;
1514 }
1515 }
1516
Chris Lattner4b009652007-07-25 00:24:17 +00001517 // You cannot convert between vector values of different size.
1518 Diag(loc, diag::err_typecheck_vector_not_convertable,
1519 lex->getType().getAsString(), rex->getType().getAsString(),
1520 lex->getSourceRange(), rex->getSourceRange());
1521 return QualType();
1522}
1523
1524inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001525 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001526{
1527 QualType lhsType = lex->getType(), rhsType = rex->getType();
1528
1529 if (lhsType->isVectorType() || rhsType->isVectorType())
1530 return CheckVectorOperands(loc, lex, rex);
1531
Steve Naroff8f708362007-08-24 19:07:16 +00001532 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001533
Chris Lattner4b009652007-07-25 00:24:17 +00001534 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001535 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001536 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001537}
1538
1539inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001540 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001541{
1542 QualType lhsType = lex->getType(), rhsType = rex->getType();
1543
Steve Naroff8f708362007-08-24 19:07:16 +00001544 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001545
Chris Lattner4b009652007-07-25 00:24:17 +00001546 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001547 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001548 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001549}
1550
1551inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001552 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001553{
1554 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1555 return CheckVectorOperands(loc, lex, rex);
1556
Steve Naroff8f708362007-08-24 19:07:16 +00001557 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001558
Chris Lattner4b009652007-07-25 00:24:17 +00001559 // handle the common case first (both operands are arithmetic).
1560 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001561 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001562
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001563 // Put any potential pointer into PExp
1564 Expr* PExp = lex, *IExp = rex;
1565 if (IExp->getType()->isPointerType())
1566 std::swap(PExp, IExp);
1567
1568 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1569 if (IExp->getType()->isIntegerType()) {
1570 // Check for arithmetic on pointers to incomplete types
1571 if (!PTy->getPointeeType()->isObjectType()) {
1572 if (PTy->getPointeeType()->isVoidType()) {
1573 Diag(loc, diag::ext_gnu_void_ptr,
1574 lex->getSourceRange(), rex->getSourceRange());
1575 } else {
1576 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1577 lex->getType().getAsString(), lex->getSourceRange());
1578 return QualType();
1579 }
1580 }
1581 return PExp->getType();
1582 }
1583 }
1584
Chris Lattner2c8bff72007-12-12 05:47:28 +00001585 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001586}
1587
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001588// C99 6.5.6
1589QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1590 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001591 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1592 return CheckVectorOperands(loc, lex, rex);
1593
Steve Naroff8f708362007-08-24 19:07:16 +00001594 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001595
Chris Lattnerf6da2912007-12-09 21:53:25 +00001596 // Enforce type constraints: C99 6.5.6p3.
1597
1598 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001599 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001600 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001601
1602 // Either ptr - int or ptr - ptr.
1603 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001604 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001605
Chris Lattnerf6da2912007-12-09 21:53:25 +00001606 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001607 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001608 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001609 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001610 Diag(loc, diag::ext_gnu_void_ptr,
1611 lex->getSourceRange(), rex->getSourceRange());
1612 } else {
1613 Diag(loc, diag::err_typecheck_sub_ptr_object,
1614 lex->getType().getAsString(), lex->getSourceRange());
1615 return QualType();
1616 }
1617 }
1618
1619 // The result type of a pointer-int computation is the pointer type.
1620 if (rex->getType()->isIntegerType())
1621 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001622
Chris Lattnerf6da2912007-12-09 21:53:25 +00001623 // Handle pointer-pointer subtractions.
1624 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001625 QualType rpointee = RHSPTy->getPointeeType();
1626
Chris Lattnerf6da2912007-12-09 21:53:25 +00001627 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001628 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001629 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001630 if (rpointee->isVoidType()) {
1631 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001632 Diag(loc, diag::ext_gnu_void_ptr,
1633 lex->getSourceRange(), rex->getSourceRange());
1634 } else {
1635 Diag(loc, diag::err_typecheck_sub_ptr_object,
1636 rex->getType().getAsString(), rex->getSourceRange());
1637 return QualType();
1638 }
1639 }
1640
1641 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001642 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1643 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001644 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1645 lex->getType().getAsString(), rex->getType().getAsString(),
1646 lex->getSourceRange(), rex->getSourceRange());
1647 return QualType();
1648 }
1649
1650 return Context.getPointerDiffType();
1651 }
1652 }
1653
Chris Lattner2c8bff72007-12-12 05:47:28 +00001654 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001655}
1656
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001657// C99 6.5.7
1658QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1659 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001660 // C99 6.5.7p2: Each of the operands shall have integer type.
1661 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1662 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001663
Chris Lattner2c8bff72007-12-12 05:47:28 +00001664 // Shifts don't perform usual arithmetic conversions, they just do integer
1665 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001666 if (!isCompAssign)
1667 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001668 UsualUnaryConversions(rex);
1669
1670 // "The type of the result is that of the promoted left operand."
1671 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001672}
1673
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001674// C99 6.5.8
1675QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1676 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001677 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1678 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1679
Chris Lattner254f3bc2007-08-26 01:18:55 +00001680 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001681 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1682 UsualArithmeticConversions(lex, rex);
1683 else {
1684 UsualUnaryConversions(lex);
1685 UsualUnaryConversions(rex);
1686 }
Chris Lattner4b009652007-07-25 00:24:17 +00001687 QualType lType = lex->getType();
1688 QualType rType = rex->getType();
1689
Ted Kremenek486509e2007-10-29 17:13:39 +00001690 // For non-floating point types, check for self-comparisons of the form
1691 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1692 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001693 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001694 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1695 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001696 if (DRL->getDecl() == DRR->getDecl())
1697 Diag(loc, diag::warn_selfcomparison);
1698 }
1699
Chris Lattner254f3bc2007-08-26 01:18:55 +00001700 if (isRelational) {
1701 if (lType->isRealType() && rType->isRealType())
1702 return Context.IntTy;
1703 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001704 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001705 if (lType->isFloatingType()) {
1706 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001707 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001708 }
1709
Chris Lattner254f3bc2007-08-26 01:18:55 +00001710 if (lType->isArithmeticType() && rType->isArithmeticType())
1711 return Context.IntTy;
1712 }
Chris Lattner4b009652007-07-25 00:24:17 +00001713
Chris Lattner22be8422007-08-26 01:10:14 +00001714 bool LHSIsNull = lex->isNullPointerConstant(Context);
1715 bool RHSIsNull = rex->isNullPointerConstant(Context);
1716
Chris Lattner254f3bc2007-08-26 01:18:55 +00001717 // All of the following pointer related warnings are GCC extensions, except
1718 // when handling null pointer constants. One day, we can consider making them
1719 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001720 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001721 QualType LCanPointeeTy =
1722 lType->getAsPointerType()->getPointeeType().getCanonicalType();
1723 QualType RCanPointeeTy =
1724 rType->getAsPointerType()->getPointeeType().getCanonicalType();
Eli Friedman50727042008-02-08 01:19:44 +00001725
Steve Naroff3b435622007-11-13 14:57:38 +00001726 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001727 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1728 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1729 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001730 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1731 lType.getAsString(), rType.getAsString(),
1732 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001733 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001734 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001735 return Context.IntTy;
1736 }
Steve Naroff936c4362008-06-03 14:04:54 +00001737 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1738 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1739 ImpCastExprToType(rex, lType);
1740 return Context.IntTy;
1741 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001742 }
Steve Naroff936c4362008-06-03 14:04:54 +00001743 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1744 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001745 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001746 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1747 lType.getAsString(), rType.getAsString(),
1748 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001749 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001750 return Context.IntTy;
1751 }
Steve Naroff936c4362008-06-03 14:04:54 +00001752 if (lType->isIntegerType() &&
1753 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00001754 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001755 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1756 lType.getAsString(), rType.getAsString(),
1757 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001758 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001759 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001760 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001761 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001762}
1763
Nate Begemanc5f0f652008-07-14 18:02:46 +00001764/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1765/// operates on extended vector types. Instead of producing an IntTy result,
1766/// like a scalar comparison, a vector comparison produces a vector of integer
1767/// types.
1768QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1769 SourceLocation loc,
1770 bool isRelational) {
1771 // Check to make sure we're operating on vectors of the same type and width,
1772 // Allowing one side to be a scalar of element type.
1773 QualType vType = CheckVectorOperands(loc, lex, rex);
1774 if (vType.isNull())
1775 return vType;
1776
1777 QualType lType = lex->getType();
1778 QualType rType = rex->getType();
1779
1780 // For non-floating point types, check for self-comparisons of the form
1781 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1782 // often indicate logic errors in the program.
1783 if (!lType->isFloatingType()) {
1784 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1785 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1786 if (DRL->getDecl() == DRR->getDecl())
1787 Diag(loc, diag::warn_selfcomparison);
1788 }
1789
1790 // Check for comparisons of floating point operands using != and ==.
1791 if (!isRelational && lType->isFloatingType()) {
1792 assert (rType->isFloatingType());
1793 CheckFloatComparison(loc,lex,rex);
1794 }
1795
1796 // Return the type for the comparison, which is the same as vector type for
1797 // integer vectors, or an integer type of identical size and number of
1798 // elements for floating point vectors.
1799 if (lType->isIntegerType())
1800 return lType;
1801
1802 const VectorType *VTy = lType->getAsVectorType();
1803
1804 // FIXME: need to deal with non-32b int / non-64b long long
1805 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
1806 if (TypeSize == 32) {
1807 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
1808 }
1809 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
1810 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
1811}
1812
Chris Lattner4b009652007-07-25 00:24:17 +00001813inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001814 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001815{
1816 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1817 return CheckVectorOperands(loc, lex, rex);
1818
Steve Naroff8f708362007-08-24 19:07:16 +00001819 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001820
1821 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001822 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001823 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001824}
1825
1826inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1827 Expr *&lex, Expr *&rex, SourceLocation loc)
1828{
1829 UsualUnaryConversions(lex);
1830 UsualUnaryConversions(rex);
1831
Eli Friedmanbea3f842008-05-13 20:16:47 +00001832 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00001833 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001834 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001835}
1836
1837inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001838 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001839{
1840 QualType lhsType = lex->getType();
1841 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001842 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1843
1844 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001845 case Expr::MLV_Valid:
1846 break;
1847 case Expr::MLV_ConstQualified:
1848 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1849 return QualType();
1850 case Expr::MLV_ArrayType:
1851 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1852 lhsType.getAsString(), lex->getSourceRange());
1853 return QualType();
1854 case Expr::MLV_NotObjectType:
1855 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1856 lhsType.getAsString(), lex->getSourceRange());
1857 return QualType();
1858 case Expr::MLV_InvalidExpression:
1859 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1860 lex->getSourceRange());
1861 return QualType();
1862 case Expr::MLV_IncompleteType:
1863 case Expr::MLV_IncompleteVoidType:
1864 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1865 lhsType.getAsString(), lex->getSourceRange());
1866 return QualType();
1867 case Expr::MLV_DuplicateVectorComponents:
1868 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1869 lex->getSourceRange());
1870 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001871 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001872
Chris Lattner005ed752008-01-04 18:04:52 +00001873 AssignConvertType ConvTy;
1874 if (compoundType.isNull())
1875 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1876 else
1877 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1878
1879 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1880 rex, "assigning"))
1881 return QualType();
1882
Chris Lattner4b009652007-07-25 00:24:17 +00001883 // C99 6.5.16p3: The type of an assignment expression is the type of the
1884 // left operand unless the left operand has qualified type, in which case
1885 // it is the unqualified version of the type of the left operand.
1886 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1887 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001888 // C++ 5.17p1: the type of the assignment expression is that of its left
1889 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001890 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001891}
1892
1893inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1894 Expr *&lex, Expr *&rex, SourceLocation loc) {
1895 UsualUnaryConversions(rex);
1896 return rex->getType();
1897}
1898
1899/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1900/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1901QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1902 QualType resType = op->getType();
1903 assert(!resType.isNull() && "no type for increment/decrement expression");
1904
Steve Naroffd30e1932007-08-24 17:20:07 +00001905 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001906 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001907 if (pt->getPointeeType()->isVoidType()) {
1908 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
1909 } else if (!pt->getPointeeType()->isObjectType()) {
1910 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00001911 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1912 resType.getAsString(), op->getSourceRange());
1913 return QualType();
1914 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001915 } else if (!resType->isRealType()) {
1916 if (resType->isComplexType())
1917 // C99 does not support ++/-- on complex types.
1918 Diag(OpLoc, diag::ext_integer_increment_complex,
1919 resType.getAsString(), op->getSourceRange());
1920 else {
1921 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1922 resType.getAsString(), op->getSourceRange());
1923 return QualType();
1924 }
Chris Lattner4b009652007-07-25 00:24:17 +00001925 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001926 // At this point, we know we have a real, complex or pointer type.
1927 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001928 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1929 if (mlval != Expr::MLV_Valid) {
1930 // FIXME: emit a more precise diagnostic...
1931 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1932 op->getSourceRange());
1933 return QualType();
1934 }
1935 return resType;
1936}
1937
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001938/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001939/// This routine allows us to typecheck complex/recursive expressions
1940/// where the declaration is needed for type checking. Here are some
1941/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Chris Lattner48d7f382008-04-02 04:24:33 +00001942static ValueDecl *getPrimaryDecl(Expr *E) {
1943 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001944 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001945 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001946 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001947 // Fields cannot be declared with a 'register' storage class.
1948 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00001949 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00001950 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00001951 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001952 case Stmt::ArraySubscriptExprClass: {
1953 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1954
Chris Lattner48d7f382008-04-02 04:24:33 +00001955 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001956 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001957 return 0;
1958 else
1959 return VD;
1960 }
Chris Lattner4b009652007-07-25 00:24:17 +00001961 case Stmt::UnaryOperatorClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001962 return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001963 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001964 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001965 case Stmt::ImplicitCastExprClass:
1966 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00001967 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001968 default:
1969 return 0;
1970 }
1971}
1972
1973/// CheckAddressOfOperand - The operand of & must be either a function
1974/// designator or an lvalue designating an object. If it is an lvalue, the
1975/// object cannot be declared with storage class register or be a bit field.
1976/// Note: The usual conversions are *not* applied to the operand of the &
1977/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1978QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001979 if (getLangOptions().C99) {
1980 // Implement C99-only parts of addressof rules.
1981 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1982 if (uOp->getOpcode() == UnaryOperator::Deref)
1983 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1984 // (assuming the deref expression is valid).
1985 return uOp->getSubExpr()->getType();
1986 }
1987 // Technically, there should be a check for array subscript
1988 // expressions here, but the result of one is always an lvalue anyway.
1989 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001990 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001991 Expr::isLvalueResult lval = op->isLvalue();
1992
1993 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001994 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1995 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001996 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1997 op->getSourceRange());
1998 return QualType();
1999 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002000 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2001 if (MemExpr->getMemberDecl()->isBitField()) {
2002 Diag(OpLoc, diag::err_typecheck_address_of,
2003 std::string("bit-field"), op->getSourceRange());
2004 return QualType();
2005 }
2006 // Check for Apple extension for accessing vector components.
2007 } else if (isa<ArraySubscriptExpr>(op) &&
2008 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2009 Diag(OpLoc, diag::err_typecheck_address_of,
2010 std::string("vector"), op->getSourceRange());
2011 return QualType();
2012 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002013 // We have an lvalue with a decl. Make sure the decl is not declared
2014 // with the register storage-class specifier.
2015 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2016 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002017 Diag(OpLoc, diag::err_typecheck_address_of,
2018 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002019 return QualType();
2020 }
2021 } else
2022 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002023 }
2024 // If the operand has type "type", the result has type "pointer to type".
2025 return Context.getPointerType(op->getType());
2026}
2027
2028QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2029 UsualUnaryConversions(op);
2030 QualType qType = op->getType();
2031
Chris Lattner7931f4a2007-07-31 16:53:04 +00002032 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002033 // Note that per both C89 and C99, this is always legal, even
2034 // if ptype is an incomplete type or void.
2035 // It would be possible to warn about dereferencing a
2036 // void pointer, but it's completely well-defined,
2037 // and such a warning is unlikely to catch any mistakes.
2038 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002039 }
2040 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2041 qType.getAsString(), op->getSourceRange());
2042 return QualType();
2043}
2044
2045static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2046 tok::TokenKind Kind) {
2047 BinaryOperator::Opcode Opc;
2048 switch (Kind) {
2049 default: assert(0 && "Unknown binop!");
2050 case tok::star: Opc = BinaryOperator::Mul; break;
2051 case tok::slash: Opc = BinaryOperator::Div; break;
2052 case tok::percent: Opc = BinaryOperator::Rem; break;
2053 case tok::plus: Opc = BinaryOperator::Add; break;
2054 case tok::minus: Opc = BinaryOperator::Sub; break;
2055 case tok::lessless: Opc = BinaryOperator::Shl; break;
2056 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2057 case tok::lessequal: Opc = BinaryOperator::LE; break;
2058 case tok::less: Opc = BinaryOperator::LT; break;
2059 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2060 case tok::greater: Opc = BinaryOperator::GT; break;
2061 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2062 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2063 case tok::amp: Opc = BinaryOperator::And; break;
2064 case tok::caret: Opc = BinaryOperator::Xor; break;
2065 case tok::pipe: Opc = BinaryOperator::Or; break;
2066 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2067 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2068 case tok::equal: Opc = BinaryOperator::Assign; break;
2069 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2070 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2071 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2072 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2073 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2074 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2075 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2076 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2077 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2078 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2079 case tok::comma: Opc = BinaryOperator::Comma; break;
2080 }
2081 return Opc;
2082}
2083
2084static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2085 tok::TokenKind Kind) {
2086 UnaryOperator::Opcode Opc;
2087 switch (Kind) {
2088 default: assert(0 && "Unknown unary op!");
2089 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2090 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2091 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2092 case tok::star: Opc = UnaryOperator::Deref; break;
2093 case tok::plus: Opc = UnaryOperator::Plus; break;
2094 case tok::minus: Opc = UnaryOperator::Minus; break;
2095 case tok::tilde: Opc = UnaryOperator::Not; break;
2096 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2097 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2098 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2099 case tok::kw___real: Opc = UnaryOperator::Real; break;
2100 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2101 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2102 }
2103 return Opc;
2104}
2105
2106// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002107Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002108 ExprTy *LHS, ExprTy *RHS) {
2109 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2110 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2111
Steve Naroff87d58b42007-09-16 03:34:24 +00002112 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2113 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002114
2115 QualType ResultTy; // Result type of the binary operator.
2116 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2117
2118 switch (Opc) {
2119 default:
2120 assert(0 && "Unknown binary expr!");
2121 case BinaryOperator::Assign:
2122 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2123 break;
2124 case BinaryOperator::Mul:
2125 case BinaryOperator::Div:
2126 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2127 break;
2128 case BinaryOperator::Rem:
2129 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2130 break;
2131 case BinaryOperator::Add:
2132 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2133 break;
2134 case BinaryOperator::Sub:
2135 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2136 break;
2137 case BinaryOperator::Shl:
2138 case BinaryOperator::Shr:
2139 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2140 break;
2141 case BinaryOperator::LE:
2142 case BinaryOperator::LT:
2143 case BinaryOperator::GE:
2144 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002145 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002146 break;
2147 case BinaryOperator::EQ:
2148 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002149 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002150 break;
2151 case BinaryOperator::And:
2152 case BinaryOperator::Xor:
2153 case BinaryOperator::Or:
2154 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2155 break;
2156 case BinaryOperator::LAnd:
2157 case BinaryOperator::LOr:
2158 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2159 break;
2160 case BinaryOperator::MulAssign:
2161 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002162 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002163 if (!CompTy.isNull())
2164 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2165 break;
2166 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002167 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002168 if (!CompTy.isNull())
2169 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2170 break;
2171 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002172 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002173 if (!CompTy.isNull())
2174 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2175 break;
2176 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002177 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002178 if (!CompTy.isNull())
2179 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2180 break;
2181 case BinaryOperator::ShlAssign:
2182 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002183 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002184 if (!CompTy.isNull())
2185 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2186 break;
2187 case BinaryOperator::AndAssign:
2188 case BinaryOperator::XorAssign:
2189 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002190 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002191 if (!CompTy.isNull())
2192 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2193 break;
2194 case BinaryOperator::Comma:
2195 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2196 break;
2197 }
2198 if (ResultTy.isNull())
2199 return true;
2200 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002201 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002202 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002203 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002204}
2205
2206// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002207Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002208 ExprTy *input) {
2209 Expr *Input = (Expr*)input;
2210 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2211 QualType resultType;
2212 switch (Opc) {
2213 default:
2214 assert(0 && "Unimplemented unary expr!");
2215 case UnaryOperator::PreInc:
2216 case UnaryOperator::PreDec:
2217 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2218 break;
2219 case UnaryOperator::AddrOf:
2220 resultType = CheckAddressOfOperand(Input, OpLoc);
2221 break;
2222 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002223 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002224 resultType = CheckIndirectionOperand(Input, OpLoc);
2225 break;
2226 case UnaryOperator::Plus:
2227 case UnaryOperator::Minus:
2228 UsualUnaryConversions(Input);
2229 resultType = Input->getType();
2230 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2231 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2232 resultType.getAsString());
2233 break;
2234 case UnaryOperator::Not: // bitwise complement
2235 UsualUnaryConversions(Input);
2236 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00002237 // C99 6.5.3.3p1. We allow complex as a GCC extension.
2238 if (!resultType->isIntegerType()) {
2239 if (resultType->isComplexType())
2240 // C99 does not support '~' for complex conjugation.
2241 Diag(OpLoc, diag::ext_integer_complement_complex,
2242 resultType.getAsString());
2243 else
2244 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2245 resultType.getAsString());
2246 }
Chris Lattner4b009652007-07-25 00:24:17 +00002247 break;
2248 case UnaryOperator::LNot: // logical negation
2249 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2250 DefaultFunctionArrayConversion(Input);
2251 resultType = Input->getType();
2252 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2253 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2254 resultType.getAsString());
2255 // LNot always has type int. C99 6.5.3.3p5.
2256 resultType = Context.IntTy;
2257 break;
2258 case UnaryOperator::SizeOf:
2259 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
2260 break;
2261 case UnaryOperator::AlignOf:
2262 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
2263 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002264 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002265 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002266 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002267 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002268 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002269 resultType = Input->getType();
2270 break;
2271 }
2272 if (resultType.isNull())
2273 return true;
2274 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2275}
2276
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002277/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2278Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002279 SourceLocation LabLoc,
2280 IdentifierInfo *LabelII) {
2281 // Look up the record for this label identifier.
2282 LabelStmt *&LabelDecl = LabelMap[LabelII];
2283
2284 // If we haven't seen this label yet, create a forward reference.
2285 if (LabelDecl == 0)
2286 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2287
2288 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002289 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2290 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002291}
2292
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002293Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002294 SourceLocation RPLoc) { // "({..})"
2295 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2296 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2297 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2298
2299 // FIXME: there are a variety of strange constraints to enforce here, for
2300 // example, it is not possible to goto into a stmt expression apparently.
2301 // More semantic analysis is needed.
2302
2303 // FIXME: the last statement in the compount stmt has its value used. We
2304 // should not warn about it being unused.
2305
2306 // If there are sub stmts in the compound stmt, take the type of the last one
2307 // as the type of the stmtexpr.
2308 QualType Ty = Context.VoidTy;
2309
2310 if (!Compound->body_empty())
2311 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2312 Ty = LastExpr->getType();
2313
2314 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2315}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002316
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002317Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002318 SourceLocation TypeLoc,
2319 TypeTy *argty,
2320 OffsetOfComponent *CompPtr,
2321 unsigned NumComponents,
2322 SourceLocation RPLoc) {
2323 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2324 assert(!ArgTy.isNull() && "Missing type argument!");
2325
2326 // We must have at least one component that refers to the type, and the first
2327 // one is known to be a field designator. Verify that the ArgTy represents
2328 // a struct/union/class.
2329 if (!ArgTy->isRecordType())
2330 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2331
2332 // Otherwise, create a compound literal expression as the base, and
2333 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002334 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002335
Chris Lattnerb37522e2007-08-31 21:49:13 +00002336 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2337 // GCC extension, diagnose them.
2338 if (NumComponents != 1)
2339 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2340 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2341
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002342 for (unsigned i = 0; i != NumComponents; ++i) {
2343 const OffsetOfComponent &OC = CompPtr[i];
2344 if (OC.isBrackets) {
2345 // Offset of an array sub-field. TODO: Should we allow vector elements?
2346 const ArrayType *AT = Res->getType()->getAsArrayType();
2347 if (!AT) {
2348 delete Res;
2349 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2350 Res->getType().getAsString());
2351 }
2352
Chris Lattner2af6a802007-08-30 17:59:59 +00002353 // FIXME: C++: Verify that operator[] isn't overloaded.
2354
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002355 // C99 6.5.2.1p1
2356 Expr *Idx = static_cast<Expr*>(OC.U.E);
2357 if (!Idx->getType()->isIntegerType())
2358 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2359 Idx->getSourceRange());
2360
2361 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2362 continue;
2363 }
2364
2365 const RecordType *RC = Res->getType()->getAsRecordType();
2366 if (!RC) {
2367 delete Res;
2368 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2369 Res->getType().getAsString());
2370 }
2371
2372 // Get the decl corresponding to this.
2373 RecordDecl *RD = RC->getDecl();
2374 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2375 if (!MemberDecl)
2376 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2377 OC.U.IdentInfo->getName(),
2378 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002379
2380 // FIXME: C++: Verify that MemberDecl isn't a static field.
2381 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002382 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2383 // matter here.
2384 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002385 }
2386
2387 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2388 BuiltinLoc);
2389}
2390
2391
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002392Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002393 TypeTy *arg1, TypeTy *arg2,
2394 SourceLocation RPLoc) {
2395 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2396 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2397
2398 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2399
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002400 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002401}
2402
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002403Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002404 ExprTy *expr1, ExprTy *expr2,
2405 SourceLocation RPLoc) {
2406 Expr *CondExpr = static_cast<Expr*>(cond);
2407 Expr *LHSExpr = static_cast<Expr*>(expr1);
2408 Expr *RHSExpr = static_cast<Expr*>(expr2);
2409
2410 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2411
2412 // The conditional expression is required to be a constant expression.
2413 llvm::APSInt condEval(32);
2414 SourceLocation ExpLoc;
2415 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2416 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2417 CondExpr->getSourceRange());
2418
2419 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2420 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2421 RHSExpr->getType();
2422 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2423}
2424
Nate Begemanbd881ef2008-01-30 20:50:20 +00002425/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002426/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002427/// The number of arguments has already been validated to match the number of
2428/// arguments in FnType.
2429static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002430 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002431 for (unsigned i = 0; i != NumParams; ++i) {
2432 QualType ExprTy = Args[i]->getType().getCanonicalType();
2433 QualType ParmTy = FnType->getArgType(i).getCanonicalType();
2434
2435 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002436 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002437 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002438 return true;
2439}
2440
2441Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2442 SourceLocation *CommaLocs,
2443 SourceLocation BuiltinLoc,
2444 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002445 // __builtin_overload requires at least 2 arguments
2446 if (NumArgs < 2)
2447 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2448 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002449
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002450 // The first argument is required to be a constant expression. It tells us
2451 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002452 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002453 Expr *NParamsExpr = Args[0];
2454 llvm::APSInt constEval(32);
2455 SourceLocation ExpLoc;
2456 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2457 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2458 NParamsExpr->getSourceRange());
2459
2460 // Verify that the number of parameters is > 0
2461 unsigned NumParams = constEval.getZExtValue();
2462 if (NumParams == 0)
2463 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2464 NParamsExpr->getSourceRange());
2465 // Verify that we have at least 1 + NumParams arguments to the builtin.
2466 if ((NumParams + 1) > NumArgs)
2467 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2468 SourceRange(BuiltinLoc, RParenLoc));
2469
2470 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002471 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002472 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002473 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2474 // UsualUnaryConversions will convert the function DeclRefExpr into a
2475 // pointer to function.
2476 Expr *Fn = UsualUnaryConversions(Args[i]);
2477 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002478 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2479 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2480 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2481 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002482
2483 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2484 // parameters, and the number of parameters must match the value passed to
2485 // the builtin.
2486 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002487 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2488 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002489
2490 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002491 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002492 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002493 if (ExprsMatchFnType(Args+1, FnType)) {
2494 if (OE)
2495 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2496 OE->getFn()->getSourceRange());
2497 // Remember our match, and continue processing the remaining arguments
2498 // to catch any errors.
2499 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2500 BuiltinLoc, RParenLoc);
2501 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002502 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002503 // Return the newly created OverloadExpr node, if we succeded in matching
2504 // exactly one of the candidate functions.
2505 if (OE)
2506 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002507
2508 // If we didn't find a matching function Expr in the __builtin_overload list
2509 // the return an error.
2510 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002511 for (unsigned i = 0; i != NumParams; ++i) {
2512 if (i != 0) typeNames += ", ";
2513 typeNames += Args[i+1]->getType().getAsString();
2514 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002515
2516 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2517 SourceRange(BuiltinLoc, RParenLoc));
2518}
2519
Anders Carlsson36760332007-10-15 20:28:48 +00002520Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2521 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002522 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002523 Expr *E = static_cast<Expr*>(expr);
2524 QualType T = QualType::getFromOpaquePtr(type);
2525
2526 InitBuiltinVaListType();
2527
Chris Lattner005ed752008-01-04 18:04:52 +00002528 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2529 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002530 return Diag(E->getLocStart(),
2531 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2532 E->getType().getAsString(),
2533 E->getSourceRange());
2534
2535 // FIXME: Warn if a non-POD type is passed in.
2536
2537 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2538}
2539
Chris Lattner005ed752008-01-04 18:04:52 +00002540bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2541 SourceLocation Loc,
2542 QualType DstType, QualType SrcType,
2543 Expr *SrcExpr, const char *Flavor) {
2544 // Decode the result (notice that AST's are still created for extensions).
2545 bool isInvalid = false;
2546 unsigned DiagKind;
2547 switch (ConvTy) {
2548 default: assert(0 && "Unknown conversion type");
2549 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002550 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002551 DiagKind = diag::ext_typecheck_convert_pointer_int;
2552 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002553 case IntToPointer:
2554 DiagKind = diag::ext_typecheck_convert_int_pointer;
2555 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002556 case IncompatiblePointer:
2557 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2558 break;
2559 case FunctionVoidPointer:
2560 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2561 break;
2562 case CompatiblePointerDiscardsQualifiers:
2563 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2564 break;
2565 case Incompatible:
2566 DiagKind = diag::err_typecheck_convert_incompatible;
2567 isInvalid = true;
2568 break;
2569 }
2570
2571 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2572 SrcExpr->getSourceRange());
2573 return isInvalid;
2574}