blob: 930457c249c295a44002f91ac87e6f4ae7c57861 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr class and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000014#include "clang/AST/Expr.h"
Douglas Gregor0979c802009-08-31 21:41:48 +000015#include "clang/AST/ExprCXX.h"
Chris Lattnera4d55d82008-10-06 06:40:35 +000016#include "clang/AST/APValue.h"
Chris Lattner2eadfb62007-07-15 23:32:58 +000017#include "clang/AST/ASTContext.h"
Chris Lattnera4d55d82008-10-06 06:40:35 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregor98cd5992008-10-21 23:43:52 +000019#include "clang/AST/DeclCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000020#include "clang/AST/DeclTemplate.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/AST/StmtVisitor.h"
Chris Lattner08f92e32010-11-17 07:37:15 +000023#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Lexer.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Chris Lattner08f92e32010-11-17 07:37:15 +000026#include "clang/Basic/SourceManager.h"
Chris Lattnerda5a6b62007-11-27 18:22:04 +000027#include "clang/Basic/TargetInfo.h"
Douglas Gregorcf3293e2009-11-01 20:32:48 +000028#include "llvm/Support/ErrorHandling.h"
Anders Carlsson3a082d82009-09-08 18:24:21 +000029#include "llvm/Support/raw_ostream.h"
Douglas Gregorffb4b6e2009-04-15 06:41:24 +000030#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
Chris Lattner2b334bb2010-04-16 23:34:13 +000033/// isKnownToHaveBooleanValue - Return true if this is an integer expression
34/// that is known to return 0 or 1. This happens for _Bool/bool expressions
35/// but also int expressions which are produced by things like comparisons in
36/// C.
37bool Expr::isKnownToHaveBooleanValue() const {
38 // If this value has _Bool type, it is obvious 0/1.
39 if (getType()->isBooleanType()) return true;
Sean Huntc3021132010-05-05 15:23:54 +000040 // If this is a non-scalar-integer type, we don't care enough to try.
Douglas Gregor2ade35e2010-06-16 00:17:44 +000041 if (!getType()->isIntegralOrEnumerationType()) return false;
Sean Huntc3021132010-05-05 15:23:54 +000042
Chris Lattner2b334bb2010-04-16 23:34:13 +000043 if (const ParenExpr *PE = dyn_cast<ParenExpr>(this))
44 return PE->getSubExpr()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +000045
Chris Lattner2b334bb2010-04-16 23:34:13 +000046 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(this)) {
47 switch (UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +000048 case UO_Plus:
49 case UO_Extension:
Chris Lattner2b334bb2010-04-16 23:34:13 +000050 return UO->getSubExpr()->isKnownToHaveBooleanValue();
51 default:
52 return false;
53 }
54 }
Sean Huntc3021132010-05-05 15:23:54 +000055
John McCall6907fbe2010-06-12 01:56:02 +000056 // Only look through implicit casts. If the user writes
57 // '(int) (a && b)' treat it as an arbitrary int.
58 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(this))
Chris Lattner2b334bb2010-04-16 23:34:13 +000059 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +000060
Chris Lattner2b334bb2010-04-16 23:34:13 +000061 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(this)) {
62 switch (BO->getOpcode()) {
63 default: return false;
John McCall2de56d12010-08-25 11:45:40 +000064 case BO_LT: // Relational operators.
65 case BO_GT:
66 case BO_LE:
67 case BO_GE:
68 case BO_EQ: // Equality operators.
69 case BO_NE:
70 case BO_LAnd: // AND operator.
71 case BO_LOr: // Logical OR operator.
Chris Lattner2b334bb2010-04-16 23:34:13 +000072 return true;
Sean Huntc3021132010-05-05 15:23:54 +000073
John McCall2de56d12010-08-25 11:45:40 +000074 case BO_And: // Bitwise AND operator.
75 case BO_Xor: // Bitwise XOR operator.
76 case BO_Or: // Bitwise OR operator.
Chris Lattner2b334bb2010-04-16 23:34:13 +000077 // Handle things like (x==2)|(y==12).
78 return BO->getLHS()->isKnownToHaveBooleanValue() &&
79 BO->getRHS()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +000080
John McCall2de56d12010-08-25 11:45:40 +000081 case BO_Comma:
82 case BO_Assign:
Chris Lattner2b334bb2010-04-16 23:34:13 +000083 return BO->getRHS()->isKnownToHaveBooleanValue();
84 }
85 }
Sean Huntc3021132010-05-05 15:23:54 +000086
Chris Lattner2b334bb2010-04-16 23:34:13 +000087 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(this))
88 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
89 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +000090
Chris Lattner2b334bb2010-04-16 23:34:13 +000091 return false;
92}
93
John McCall63c00d72011-02-09 08:16:59 +000094// Amusing macro metaprogramming hack: check whether a class provides
95// a more specific implementation of getExprLoc().
96namespace {
97 /// This implementation is used when a class provides a custom
98 /// implementation of getExprLoc.
99 template <class E, class T>
100 SourceLocation getExprLocImpl(const Expr *expr,
101 SourceLocation (T::*v)() const) {
102 return static_cast<const E*>(expr)->getExprLoc();
103 }
104
105 /// This implementation is used when a class doesn't provide
106 /// a custom implementation of getExprLoc. Overload resolution
107 /// should pick it over the implementation above because it's
108 /// more specialized according to function template partial ordering.
109 template <class E>
110 SourceLocation getExprLocImpl(const Expr *expr,
111 SourceLocation (Expr::*v)() const) {
112 return static_cast<const E*>(expr)->getSourceRange().getBegin();
113 }
114}
115
116SourceLocation Expr::getExprLoc() const {
117 switch (getStmtClass()) {
118 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
119#define ABSTRACT_STMT(type)
120#define STMT(type, base) \
121 case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break;
122#define EXPR(type, base) \
123 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
124#include "clang/AST/StmtNodes.inc"
125 }
126 llvm_unreachable("unknown statement kind");
127 return SourceLocation();
128}
129
Reid Spencer5f016e22007-07-11 17:01:13 +0000130//===----------------------------------------------------------------------===//
131// Primary Expressions.
132//===----------------------------------------------------------------------===//
133
John McCalld5532b62009-11-23 01:53:49 +0000134void ExplicitTemplateArgumentList::initializeFrom(
135 const TemplateArgumentListInfo &Info) {
136 LAngleLoc = Info.getLAngleLoc();
137 RAngleLoc = Info.getRAngleLoc();
138 NumTemplateArgs = Info.size();
139
140 TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
141 for (unsigned i = 0; i != NumTemplateArgs; ++i)
142 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
143}
144
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000145void ExplicitTemplateArgumentList::initializeFrom(
146 const TemplateArgumentListInfo &Info,
147 bool &Dependent,
148 bool &ContainsUnexpandedParameterPack) {
149 LAngleLoc = Info.getLAngleLoc();
150 RAngleLoc = Info.getRAngleLoc();
151 NumTemplateArgs = Info.size();
152
153 TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
154 for (unsigned i = 0; i != NumTemplateArgs; ++i) {
155 Dependent = Dependent || Info[i].getArgument().isDependent();
156 ContainsUnexpandedParameterPack
157 = ContainsUnexpandedParameterPack ||
158 Info[i].getArgument().containsUnexpandedParameterPack();
159
160 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
161 }
162}
163
John McCalld5532b62009-11-23 01:53:49 +0000164void ExplicitTemplateArgumentList::copyInto(
165 TemplateArgumentListInfo &Info) const {
166 Info.setLAngleLoc(LAngleLoc);
167 Info.setRAngleLoc(RAngleLoc);
168 for (unsigned I = 0; I != NumTemplateArgs; ++I)
169 Info.addArgument(getTemplateArgs()[I]);
170}
171
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +0000172std::size_t ExplicitTemplateArgumentList::sizeFor(unsigned NumTemplateArgs) {
173 return sizeof(ExplicitTemplateArgumentList) +
174 sizeof(TemplateArgumentLoc) * NumTemplateArgs;
175}
176
John McCalld5532b62009-11-23 01:53:49 +0000177std::size_t ExplicitTemplateArgumentList::sizeFor(
178 const TemplateArgumentListInfo &Info) {
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +0000179 return sizeFor(Info.size());
John McCalld5532b62009-11-23 01:53:49 +0000180}
181
Douglas Gregord967e312011-01-19 21:52:31 +0000182/// \brief Compute the type- and value-dependence of a declaration reference
183/// based on the declaration being referenced.
184static void computeDeclRefDependence(NamedDecl *D, QualType T,
185 bool &TypeDependent,
186 bool &ValueDependent) {
187 TypeDependent = false;
188 ValueDependent = false;
Sean Huntc3021132010-05-05 15:23:54 +0000189
Douglas Gregor0da76df2009-11-23 11:41:28 +0000190
191 // (TD) C++ [temp.dep.expr]p3:
192 // An id-expression is type-dependent if it contains:
193 //
Sean Huntc3021132010-05-05 15:23:54 +0000194 // and
Douglas Gregor0da76df2009-11-23 11:41:28 +0000195 //
196 // (VD) C++ [temp.dep.constexpr]p2:
197 // An identifier is value-dependent if it is:
Douglas Gregord967e312011-01-19 21:52:31 +0000198
Douglas Gregor0da76df2009-11-23 11:41:28 +0000199 // (TD) - an identifier that was declared with dependent type
200 // (VD) - a name declared with a dependent type,
Douglas Gregord967e312011-01-19 21:52:31 +0000201 if (T->isDependentType()) {
202 TypeDependent = true;
203 ValueDependent = true;
204 return;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000205 }
Douglas Gregord967e312011-01-19 21:52:31 +0000206
Douglas Gregor0da76df2009-11-23 11:41:28 +0000207 // (TD) - a conversion-function-id that specifies a dependent type
Douglas Gregord967e312011-01-19 21:52:31 +0000208 if (D->getDeclName().getNameKind()
209 == DeclarationName::CXXConversionFunctionName &&
Douglas Gregor0da76df2009-11-23 11:41:28 +0000210 D->getDeclName().getCXXNameType()->isDependentType()) {
Douglas Gregord967e312011-01-19 21:52:31 +0000211 TypeDependent = true;
212 ValueDependent = true;
213 return;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000214 }
215 // (VD) - the name of a non-type template parameter,
Douglas Gregord967e312011-01-19 21:52:31 +0000216 if (isa<NonTypeTemplateParmDecl>(D)) {
217 ValueDependent = true;
218 return;
219 }
220
Douglas Gregor0da76df2009-11-23 11:41:28 +0000221 // (VD) - a constant with integral or enumeration type and is
222 // initialized with an expression that is value-dependent.
Douglas Gregord967e312011-01-19 21:52:31 +0000223 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000224 if (Var->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor501edb62010-01-15 16:21:02 +0000225 Var->getType().getCVRQualifiers() == Qualifiers::Const) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000226 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor501edb62010-01-15 16:21:02 +0000227 if (Init->isValueDependent())
Douglas Gregord967e312011-01-19 21:52:31 +0000228 ValueDependent = true;
Douglas Gregorbb6e73f2010-05-11 08:41:30 +0000229 }
Douglas Gregord967e312011-01-19 21:52:31 +0000230
Douglas Gregorbb6e73f2010-05-11 08:41:30 +0000231 // (VD) - FIXME: Missing from the standard:
232 // - a member function or a static data member of the current
233 // instantiation
234 else if (Var->isStaticDataMember() &&
Douglas Gregor7ed5bd32010-05-11 08:44:04 +0000235 Var->getDeclContext()->isDependentContext())
Douglas Gregord967e312011-01-19 21:52:31 +0000236 ValueDependent = true;
237
238 return;
239 }
240
Douglas Gregorbb6e73f2010-05-11 08:41:30 +0000241 // (VD) - FIXME: Missing from the standard:
242 // - a member function or a static data member of the current
243 // instantiation
Douglas Gregord967e312011-01-19 21:52:31 +0000244 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
245 ValueDependent = true;
246 return;
247 }
248}
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000249
Douglas Gregord967e312011-01-19 21:52:31 +0000250void DeclRefExpr::computeDependence() {
251 bool TypeDependent = false;
252 bool ValueDependent = false;
253 computeDeclRefDependence(getDecl(), getType(), TypeDependent, ValueDependent);
254
255 // (TD) C++ [temp.dep.expr]p3:
256 // An id-expression is type-dependent if it contains:
257 //
258 // and
259 //
260 // (VD) C++ [temp.dep.constexpr]p2:
261 // An identifier is value-dependent if it is:
262 if (!TypeDependent && !ValueDependent &&
263 hasExplicitTemplateArgs() &&
264 TemplateSpecializationType::anyDependentTemplateArguments(
265 getTemplateArgs(),
266 getNumTemplateArgs())) {
267 TypeDependent = true;
268 ValueDependent = true;
269 }
270
271 ExprBits.TypeDependent = TypeDependent;
272 ExprBits.ValueDependent = ValueDependent;
273
Douglas Gregor10738d32010-12-23 23:51:58 +0000274 // Is the declaration a parameter pack?
Douglas Gregord967e312011-01-19 21:52:31 +0000275 if (getDecl()->isParameterPack())
Douglas Gregor1fe85ea2011-01-05 21:11:38 +0000276 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000277}
278
Douglas Gregor40d96a62011-02-28 21:54:11 +0000279DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
John McCalldbd872f2009-12-08 09:08:17 +0000280 ValueDecl *D, SourceLocation NameLoc,
John McCalld5532b62009-11-23 01:53:49 +0000281 const TemplateArgumentListInfo *TemplateArgs,
John McCallf89e55a2010-11-18 06:31:45 +0000282 QualType T, ExprValueKind VK)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000283 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false),
Douglas Gregora2813ce2009-10-23 18:54:35 +0000284 DecoratedD(D,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000285 (QualifierLoc? HasQualifierFlag : 0) |
John McCalld5532b62009-11-23 01:53:49 +0000286 (TemplateArgs ? HasExplicitTemplateArgumentListFlag : 0)),
Douglas Gregora2813ce2009-10-23 18:54:35 +0000287 Loc(NameLoc) {
Douglas Gregor40d96a62011-02-28 21:54:11 +0000288 if (QualifierLoc) {
Douglas Gregora2813ce2009-10-23 18:54:35 +0000289 NameQualifier *NQ = getNameQualifier();
Douglas Gregor40d96a62011-02-28 21:54:11 +0000290 NQ->QualifierLoc = QualifierLoc;
Douglas Gregora2813ce2009-10-23 18:54:35 +0000291 }
Sean Huntc3021132010-05-05 15:23:54 +0000292
John McCalld5532b62009-11-23 01:53:49 +0000293 if (TemplateArgs)
John McCall096832c2010-08-19 23:49:38 +0000294 getExplicitTemplateArgs().initializeFrom(*TemplateArgs);
Douglas Gregor0da76df2009-11-23 11:41:28 +0000295
296 computeDependence();
Douglas Gregora2813ce2009-10-23 18:54:35 +0000297}
298
Douglas Gregor40d96a62011-02-28 21:54:11 +0000299DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000300 ValueDecl *D, const DeclarationNameInfo &NameInfo,
301 const TemplateArgumentListInfo *TemplateArgs,
John McCallf89e55a2010-11-18 06:31:45 +0000302 QualType T, ExprValueKind VK)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000303 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false),
Abramo Bagnara25777432010-08-11 22:01:17 +0000304 DecoratedD(D,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000305 (QualifierLoc? HasQualifierFlag : 0) |
Abramo Bagnara25777432010-08-11 22:01:17 +0000306 (TemplateArgs ? HasExplicitTemplateArgumentListFlag : 0)),
307 Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
Douglas Gregor40d96a62011-02-28 21:54:11 +0000308 if (QualifierLoc) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000309 NameQualifier *NQ = getNameQualifier();
Douglas Gregor40d96a62011-02-28 21:54:11 +0000310 NQ->QualifierLoc = QualifierLoc;
Abramo Bagnara25777432010-08-11 22:01:17 +0000311 }
312
313 if (TemplateArgs)
John McCall096832c2010-08-19 23:49:38 +0000314 getExplicitTemplateArgs().initializeFrom(*TemplateArgs);
Abramo Bagnara25777432010-08-11 22:01:17 +0000315
316 computeDependence();
317}
318
Douglas Gregora2813ce2009-10-23 18:54:35 +0000319DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000320 NestedNameSpecifierLoc QualifierLoc,
John McCalldbd872f2009-12-08 09:08:17 +0000321 ValueDecl *D,
Douglas Gregora2813ce2009-10-23 18:54:35 +0000322 SourceLocation NameLoc,
Douglas Gregor0da76df2009-11-23 11:41:28 +0000323 QualType T,
John McCallf89e55a2010-11-18 06:31:45 +0000324 ExprValueKind VK,
Douglas Gregor0da76df2009-11-23 11:41:28 +0000325 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregor40d96a62011-02-28 21:54:11 +0000326 return Create(Context, QualifierLoc, D,
Abramo Bagnara25777432010-08-11 22:01:17 +0000327 DeclarationNameInfo(D->getDeclName(), NameLoc),
John McCallf89e55a2010-11-18 06:31:45 +0000328 T, VK, TemplateArgs);
Abramo Bagnara25777432010-08-11 22:01:17 +0000329}
330
331DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000332 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000333 ValueDecl *D,
334 const DeclarationNameInfo &NameInfo,
335 QualType T,
John McCallf89e55a2010-11-18 06:31:45 +0000336 ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +0000337 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora2813ce2009-10-23 18:54:35 +0000338 std::size_t Size = sizeof(DeclRefExpr);
Douglas Gregor40d96a62011-02-28 21:54:11 +0000339 if (QualifierLoc != 0)
Douglas Gregora2813ce2009-10-23 18:54:35 +0000340 Size += sizeof(NameQualifier);
Sean Huntc3021132010-05-05 15:23:54 +0000341
John McCalld5532b62009-11-23 01:53:49 +0000342 if (TemplateArgs)
343 Size += ExplicitTemplateArgumentList::sizeFor(*TemplateArgs);
Sean Huntc3021132010-05-05 15:23:54 +0000344
Chris Lattner32488542010-10-30 05:14:06 +0000345 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Douglas Gregor40d96a62011-02-28 21:54:11 +0000346 return new (Mem) DeclRefExpr(QualifierLoc, D, NameInfo, TemplateArgs, T, VK);
Douglas Gregora2813ce2009-10-23 18:54:35 +0000347}
348
Douglas Gregordef03542011-02-04 12:01:24 +0000349DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
350 bool HasQualifier,
351 bool HasExplicitTemplateArgs,
Argyrios Kyrtzidis663e3802010-07-08 13:09:47 +0000352 unsigned NumTemplateArgs) {
353 std::size_t Size = sizeof(DeclRefExpr);
354 if (HasQualifier)
355 Size += sizeof(NameQualifier);
356
Douglas Gregordef03542011-02-04 12:01:24 +0000357 if (HasExplicitTemplateArgs)
Argyrios Kyrtzidis663e3802010-07-08 13:09:47 +0000358 Size += ExplicitTemplateArgumentList::sizeFor(NumTemplateArgs);
359
Chris Lattner32488542010-10-30 05:14:06 +0000360 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Argyrios Kyrtzidis663e3802010-07-08 13:09:47 +0000361 return new (Mem) DeclRefExpr(EmptyShell());
362}
363
Douglas Gregora2813ce2009-10-23 18:54:35 +0000364SourceRange DeclRefExpr::getSourceRange() const {
Abramo Bagnara25777432010-08-11 22:01:17 +0000365 SourceRange R = getNameInfo().getSourceRange();
Douglas Gregora2813ce2009-10-23 18:54:35 +0000366 if (hasQualifier())
Douglas Gregor40d96a62011-02-28 21:54:11 +0000367 R.setBegin(getQualifierLoc().getBeginLoc());
John McCall096832c2010-08-19 23:49:38 +0000368 if (hasExplicitTemplateArgs())
Douglas Gregora2813ce2009-10-23 18:54:35 +0000369 R.setEnd(getRAngleLoc());
370 return R;
371}
372
Anders Carlsson3a082d82009-09-08 18:24:21 +0000373// FIXME: Maybe this should use DeclPrinter with a special "print predefined
374// expr" policy instead.
Anders Carlsson848fa642010-02-11 18:20:28 +0000375std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
376 ASTContext &Context = CurrentDecl->getASTContext();
377
Anders Carlsson3a082d82009-09-08 18:24:21 +0000378 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Anders Carlsson848fa642010-02-11 18:20:28 +0000379 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
Anders Carlsson3a082d82009-09-08 18:24:21 +0000380 return FD->getNameAsString();
381
382 llvm::SmallString<256> Name;
383 llvm::raw_svector_ostream Out(Name);
384
385 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Anders Carlsson848fa642010-02-11 18:20:28 +0000386 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
Anders Carlsson3a082d82009-09-08 18:24:21 +0000387 Out << "virtual ";
Sam Weinig4eadcc52009-12-27 01:38:20 +0000388 if (MD->isStatic())
389 Out << "static ";
Anders Carlsson3a082d82009-09-08 18:24:21 +0000390 }
391
392 PrintingPolicy Policy(Context.getLangOptions());
Anders Carlsson3a082d82009-09-08 18:24:21 +0000393
394 std::string Proto = FD->getQualifiedNameAsString(Policy);
395
John McCall183700f2009-09-21 23:43:11 +0000396 const FunctionType *AFT = FD->getType()->getAs<FunctionType>();
Anders Carlsson3a082d82009-09-08 18:24:21 +0000397 const FunctionProtoType *FT = 0;
398 if (FD->hasWrittenPrototype())
399 FT = dyn_cast<FunctionProtoType>(AFT);
400
401 Proto += "(";
402 if (FT) {
403 llvm::raw_string_ostream POut(Proto);
404 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
405 if (i) POut << ", ";
406 std::string Param;
407 FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
408 POut << Param;
409 }
410
411 if (FT->isVariadic()) {
412 if (FD->getNumParams()) POut << ", ";
413 POut << "...";
414 }
415 }
416 Proto += ")";
417
Sam Weinig4eadcc52009-12-27 01:38:20 +0000418 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
419 Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
420 if (ThisQuals.hasConst())
421 Proto += " const";
422 if (ThisQuals.hasVolatile())
423 Proto += " volatile";
424 }
425
Sam Weinig3a1ce1e2009-12-06 23:55:13 +0000426 if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
427 AFT->getResultType().getAsStringInternal(Proto, Policy);
Anders Carlsson3a082d82009-09-08 18:24:21 +0000428
429 Out << Proto;
430
431 Out.flush();
432 return Name.str().str();
433 }
434 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
435 llvm::SmallString<256> Name;
436 llvm::raw_svector_ostream Out(Name);
437 Out << (MD->isInstanceMethod() ? '-' : '+');
438 Out << '[';
Ted Kremenekb03d33e2010-03-18 21:23:08 +0000439
440 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
441 // a null check to avoid a crash.
442 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramer900fc632010-04-17 09:33:03 +0000443 Out << ID;
Ted Kremenekb03d33e2010-03-18 21:23:08 +0000444
Anders Carlsson3a082d82009-09-08 18:24:21 +0000445 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramer900fc632010-04-17 09:33:03 +0000446 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
447 Out << '(' << CID << ')';
448
Anders Carlsson3a082d82009-09-08 18:24:21 +0000449 Out << ' ';
450 Out << MD->getSelector().getAsString();
451 Out << ']';
452
453 Out.flush();
454 return Name.str().str();
455 }
456 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
457 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
458 return "top level";
459 }
460 return "";
461}
462
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000463void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
464 if (hasAllocation())
465 C.Deallocate(pVal);
466
467 BitWidth = Val.getBitWidth();
468 unsigned NumWords = Val.getNumWords();
469 const uint64_t* Words = Val.getRawData();
470 if (NumWords > 1) {
471 pVal = new (C) uint64_t[NumWords];
472 std::copy(Words, Words + NumWords, pVal);
473 } else if (NumWords == 1)
474 VAL = Words[0];
475 else
476 VAL = 0;
477}
478
479IntegerLiteral *
480IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
481 QualType type, SourceLocation l) {
482 return new (C) IntegerLiteral(C, V, type, l);
483}
484
485IntegerLiteral *
486IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
487 return new (C) IntegerLiteral(Empty);
488}
489
490FloatingLiteral *
491FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
492 bool isexact, QualType Type, SourceLocation L) {
493 return new (C) FloatingLiteral(C, V, isexact, Type, L);
494}
495
496FloatingLiteral *
497FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
498 return new (C) FloatingLiteral(Empty);
499}
500
Chris Lattnerda8249e2008-06-07 22:13:43 +0000501/// getValueAsApproximateDouble - This returns the value as an inaccurate
502/// double. Note that this may cause loss of precision, but is useful for
503/// debugging dumps, etc.
504double FloatingLiteral::getValueAsApproximateDouble() const {
505 llvm::APFloat V = getValue();
Dale Johannesenee5a7002008-10-09 23:02:32 +0000506 bool ignored;
507 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
508 &ignored);
Chris Lattnerda8249e2008-06-07 22:13:43 +0000509 return V.convertToDouble();
510}
511
Chris Lattner2085fd62009-02-18 06:40:38 +0000512StringLiteral *StringLiteral::Create(ASTContext &C, const char *StrData,
513 unsigned ByteLength, bool Wide,
514 QualType Ty,
Mike Stump1eb44332009-09-09 15:08:12 +0000515 const SourceLocation *Loc,
Anders Carlssona135fb42009-03-15 18:34:13 +0000516 unsigned NumStrs) {
Chris Lattner2085fd62009-02-18 06:40:38 +0000517 // Allocate enough space for the StringLiteral plus an array of locations for
518 // any concatenated string tokens.
519 void *Mem = C.Allocate(sizeof(StringLiteral)+
520 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner32488542010-10-30 05:14:06 +0000521 llvm::alignOf<StringLiteral>());
Chris Lattner2085fd62009-02-18 06:40:38 +0000522 StringLiteral *SL = new (Mem) StringLiteral(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Reid Spencer5f016e22007-07-11 17:01:13 +0000524 // OPTIMIZE: could allocate this appended to the StringLiteral.
Chris Lattner2085fd62009-02-18 06:40:38 +0000525 char *AStrData = new (C, 1) char[ByteLength];
526 memcpy(AStrData, StrData, ByteLength);
527 SL->StrData = AStrData;
528 SL->ByteLength = ByteLength;
529 SL->IsWide = Wide;
530 SL->TokLocs[0] = Loc[0];
531 SL->NumConcatenated = NumStrs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000532
Chris Lattner726e1682009-02-18 05:49:11 +0000533 if (NumStrs != 1)
Chris Lattner2085fd62009-02-18 06:40:38 +0000534 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
535 return SL;
Chris Lattner726e1682009-02-18 05:49:11 +0000536}
537
Douglas Gregor673ecd62009-04-15 16:35:07 +0000538StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
539 void *Mem = C.Allocate(sizeof(StringLiteral)+
540 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner32488542010-10-30 05:14:06 +0000541 llvm::alignOf<StringLiteral>());
Douglas Gregor673ecd62009-04-15 16:35:07 +0000542 StringLiteral *SL = new (Mem) StringLiteral(QualType());
543 SL->StrData = 0;
544 SL->ByteLength = 0;
545 SL->NumConcatenated = NumStrs;
546 return SL;
547}
548
Daniel Dunbarb6480232009-09-22 03:27:33 +0000549void StringLiteral::setString(ASTContext &C, llvm::StringRef Str) {
Daniel Dunbarb6480232009-09-22 03:27:33 +0000550 char *AStrData = new (C, 1) char[Str.size()];
551 memcpy(AStrData, Str.data(), Str.size());
Douglas Gregor673ecd62009-04-15 16:35:07 +0000552 StrData = AStrData;
Daniel Dunbarb6480232009-09-22 03:27:33 +0000553 ByteLength = Str.size();
Douglas Gregor673ecd62009-04-15 16:35:07 +0000554}
555
Chris Lattner08f92e32010-11-17 07:37:15 +0000556/// getLocationOfByte - Return a source location that points to the specified
557/// byte of this string literal.
558///
559/// Strings are amazingly complex. They can be formed from multiple tokens and
560/// can have escape sequences in them in addition to the usual trigraph and
561/// escaped newline business. This routine handles this complexity.
562///
563SourceLocation StringLiteral::
564getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
565 const LangOptions &Features, const TargetInfo &Target) const {
566 assert(!isWide() && "This doesn't work for wide strings yet");
567
568 // Loop over all of the tokens in this string until we find the one that
569 // contains the byte we're looking for.
570 unsigned TokNo = 0;
571 while (1) {
572 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
573 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
574
575 // Get the spelling of the string so that we can get the data that makes up
576 // the string literal, not the identifier for the macro it is potentially
577 // expanded through.
578 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
579
580 // Re-lex the token to get its length and original spelling.
581 std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
582 bool Invalid = false;
583 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
584 if (Invalid)
585 return StrTokSpellingLoc;
586
587 const char *StrData = Buffer.data()+LocInfo.second;
588
589 // Create a langops struct and enable trigraphs. This is sufficient for
590 // relexing tokens.
591 LangOptions LangOpts;
592 LangOpts.Trigraphs = true;
593
594 // Create a lexer starting at the beginning of this token.
595 Lexer TheLexer(StrTokSpellingLoc, Features, Buffer.begin(), StrData,
596 Buffer.end());
597 Token TheTok;
598 TheLexer.LexFromRawLexer(TheTok);
599
600 // Use the StringLiteralParser to compute the length of the string in bytes.
601 StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
602 unsigned TokNumBytes = SLP.GetStringLength();
603
604 // If the byte is in this token, return the location of the byte.
605 if (ByteNo < TokNumBytes ||
606 (ByteNo == TokNumBytes && TokNo == getNumConcatenated())) {
607 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
608
609 // Now that we know the offset of the token in the spelling, use the
610 // preprocessor to get the offset in the original source.
611 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
612 }
613
614 // Move to the next string token.
615 ++TokNo;
616 ByteNo -= TokNumBytes;
617 }
618}
619
620
621
Reid Spencer5f016e22007-07-11 17:01:13 +0000622/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
623/// corresponds to, e.g. "sizeof" or "[pre]++".
624const char *UnaryOperator::getOpcodeStr(Opcode Op) {
625 switch (Op) {
626 default: assert(0 && "Unknown unary operator");
John McCall2de56d12010-08-25 11:45:40 +0000627 case UO_PostInc: return "++";
628 case UO_PostDec: return "--";
629 case UO_PreInc: return "++";
630 case UO_PreDec: return "--";
631 case UO_AddrOf: return "&";
632 case UO_Deref: return "*";
633 case UO_Plus: return "+";
634 case UO_Minus: return "-";
635 case UO_Not: return "~";
636 case UO_LNot: return "!";
637 case UO_Real: return "__real";
638 case UO_Imag: return "__imag";
639 case UO_Extension: return "__extension__";
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 }
641}
642
John McCall2de56d12010-08-25 11:45:40 +0000643UnaryOperatorKind
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000644UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
645 switch (OO) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000646 default: assert(false && "No unary operator for overloaded function");
John McCall2de56d12010-08-25 11:45:40 +0000647 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
648 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
649 case OO_Amp: return UO_AddrOf;
650 case OO_Star: return UO_Deref;
651 case OO_Plus: return UO_Plus;
652 case OO_Minus: return UO_Minus;
653 case OO_Tilde: return UO_Not;
654 case OO_Exclaim: return UO_LNot;
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000655 }
656}
657
658OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
659 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +0000660 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
661 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
662 case UO_AddrOf: return OO_Amp;
663 case UO_Deref: return OO_Star;
664 case UO_Plus: return OO_Plus;
665 case UO_Minus: return OO_Minus;
666 case UO_Not: return OO_Tilde;
667 case UO_LNot: return OO_Exclaim;
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000668 default: return OO_None;
669 }
670}
671
672
Reid Spencer5f016e22007-07-11 17:01:13 +0000673//===----------------------------------------------------------------------===//
674// Postfix Operators.
675//===----------------------------------------------------------------------===//
676
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000677CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
678 Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
John McCallf89e55a2010-11-18 06:31:45 +0000679 SourceLocation rparenloc)
680 : Expr(SC, t, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000681 fn->isTypeDependent(),
682 fn->isValueDependent(),
683 fn->containsUnexpandedParameterPack()),
Douglas Gregor898574e2008-12-05 23:32:09 +0000684 NumArgs(numargs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000686 SubExprs = new (C) Stmt*[numargs+PREARGS_START+NumPreArgs];
Douglas Gregorb4609802008-11-14 16:09:21 +0000687 SubExprs[FN] = fn;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000688 for (unsigned i = 0; i != numargs; ++i) {
689 if (args[i]->isTypeDependent())
690 ExprBits.TypeDependent = true;
691 if (args[i]->isValueDependent())
692 ExprBits.ValueDependent = true;
693 if (args[i]->containsUnexpandedParameterPack())
694 ExprBits.ContainsUnexpandedParameterPack = true;
695
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000696 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000697 }
Ted Kremenek668bf912009-02-09 20:51:47 +0000698
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000699 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregorb4609802008-11-14 16:09:21 +0000700 RParenLoc = rparenloc;
701}
Nate Begemane2ce1d92008-01-17 17:46:27 +0000702
Ted Kremenek668bf912009-02-09 20:51:47 +0000703CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
John McCallf89e55a2010-11-18 06:31:45 +0000704 QualType t, ExprValueKind VK, SourceLocation rparenloc)
705 : Expr(CallExprClass, t, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000706 fn->isTypeDependent(),
707 fn->isValueDependent(),
708 fn->containsUnexpandedParameterPack()),
Douglas Gregor898574e2008-12-05 23:32:09 +0000709 NumArgs(numargs) {
Ted Kremenek668bf912009-02-09 20:51:47 +0000710
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000711 SubExprs = new (C) Stmt*[numargs+PREARGS_START];
Ted Kremenek77ed8e42007-08-24 18:13:47 +0000712 SubExprs[FN] = fn;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000713 for (unsigned i = 0; i != numargs; ++i) {
714 if (args[i]->isTypeDependent())
715 ExprBits.TypeDependent = true;
716 if (args[i]->isValueDependent())
717 ExprBits.ValueDependent = true;
718 if (args[i]->containsUnexpandedParameterPack())
719 ExprBits.ContainsUnexpandedParameterPack = true;
720
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000721 SubExprs[i+PREARGS_START] = args[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000722 }
Ted Kremenek668bf912009-02-09 20:51:47 +0000723
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000724 CallExprBits.NumPreArgs = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 RParenLoc = rparenloc;
726}
727
Mike Stump1eb44332009-09-09 15:08:12 +0000728CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
729 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000730 // FIXME: Why do we allocate this?
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000731 SubExprs = new (C) Stmt*[PREARGS_START];
732 CallExprBits.NumPreArgs = 0;
733}
734
735CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs,
736 EmptyShell Empty)
737 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
738 // FIXME: Why do we allocate this?
739 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
740 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregor1f0d0132009-04-15 17:43:59 +0000741}
742
Nuno Lopesd20254f2009-12-20 23:11:08 +0000743Decl *CallExpr::getCalleeDecl() {
Zhongxing Xua0042542009-07-17 07:29:51 +0000744 Expr *CEE = getCallee()->IgnoreParenCasts();
Sebastian Redl20012152010-09-10 20:55:30 +0000745 // If we're calling a dereference, look at the pointer instead.
746 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
747 if (BO->isPtrMemOp())
748 CEE = BO->getRHS()->IgnoreParenCasts();
749 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
750 if (UO->getOpcode() == UO_Deref)
751 CEE = UO->getSubExpr()->IgnoreParenCasts();
752 }
Chris Lattner6346f962009-07-17 15:46:27 +0000753 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopesd20254f2009-12-20 23:11:08 +0000754 return DRE->getDecl();
Nuno Lopescb1c77f2009-12-24 00:28:18 +0000755 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
756 return ME->getMemberDecl();
Zhongxing Xua0042542009-07-17 07:29:51 +0000757
758 return 0;
759}
760
Nuno Lopesd20254f2009-12-20 23:11:08 +0000761FunctionDecl *CallExpr::getDirectCallee() {
Chris Lattnercaabf9b2009-12-21 01:10:56 +0000762 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
Nuno Lopesd20254f2009-12-20 23:11:08 +0000763}
764
Chris Lattnerd18b3292007-12-28 05:25:02 +0000765/// setNumArgs - This changes the number of arguments present in this call.
766/// Any orphaned expressions are deleted by this, and any new operands are set
767/// to null.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000768void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
Chris Lattnerd18b3292007-12-28 05:25:02 +0000769 // No change, just return.
770 if (NumArgs == getNumArgs()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Chris Lattnerd18b3292007-12-28 05:25:02 +0000772 // If shrinking # arguments, just delete the extras and forgot them.
773 if (NumArgs < getNumArgs()) {
Chris Lattnerd18b3292007-12-28 05:25:02 +0000774 this->NumArgs = NumArgs;
775 return;
776 }
777
778 // Otherwise, we are growing the # arguments. New an bigger argument array.
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000779 unsigned NumPreArgs = getNumPreArgs();
780 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
Chris Lattnerd18b3292007-12-28 05:25:02 +0000781 // Copy over args.
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000782 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
Chris Lattnerd18b3292007-12-28 05:25:02 +0000783 NewSubExprs[i] = SubExprs[i];
784 // Null out new args.
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000785 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
786 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
Chris Lattnerd18b3292007-12-28 05:25:02 +0000787 NewSubExprs[i] = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Douglas Gregor88c9a462009-04-17 21:46:47 +0000789 if (SubExprs) C.Deallocate(SubExprs);
Chris Lattnerd18b3292007-12-28 05:25:02 +0000790 SubExprs = NewSubExprs;
791 this->NumArgs = NumArgs;
792}
793
Chris Lattnercb888962008-10-06 05:00:53 +0000794/// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If
795/// not, return 0.
Jay Foad4ba2a172011-01-12 09:06:06 +0000796unsigned CallExpr::isBuiltinCall(const ASTContext &Context) const {
Steve Naroffc4f8e8b2008-01-31 01:07:12 +0000797 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump1eb44332009-09-09 15:08:12 +0000798 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Naroffc4f8e8b2008-01-31 01:07:12 +0000799 // ImplicitCastExpr.
800 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
801 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattnercb888962008-10-06 05:00:53 +0000802 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Steve Naroffc4f8e8b2008-01-31 01:07:12 +0000804 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
805 if (!DRE)
Chris Lattnercb888962008-10-06 05:00:53 +0000806 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Anders Carlssonbcba2012008-01-31 02:13:57 +0000808 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
809 if (!FDecl)
Chris Lattnercb888962008-10-06 05:00:53 +0000810 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Douglas Gregor4fcd3992008-11-21 15:30:19 +0000812 if (!FDecl->getIdentifier())
813 return 0;
814
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000815 return FDecl->getBuiltinID();
Chris Lattnercb888962008-10-06 05:00:53 +0000816}
Anders Carlssonbcba2012008-01-31 02:13:57 +0000817
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000818QualType CallExpr::getCallReturnType() const {
819 QualType CalleeType = getCallee()->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000820 if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000821 CalleeType = FnTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000822 else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000823 CalleeType = BPT->getPointeeType();
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000824 else if (const MemberPointerType *MPT
825 = CalleeType->getAs<MemberPointerType>())
826 CalleeType = MPT->getPointeeType();
827
John McCall183700f2009-09-21 23:43:11 +0000828 const FunctionType *FnType = CalleeType->getAs<FunctionType>();
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000829 return FnType->getResultType();
830}
Chris Lattnercb888962008-10-06 05:00:53 +0000831
John McCall2882eca2011-02-21 06:23:05 +0000832SourceRange CallExpr::getSourceRange() const {
833 if (isa<CXXOperatorCallExpr>(this))
834 return cast<CXXOperatorCallExpr>(this)->getSourceRange();
835
836 SourceLocation begin = getCallee()->getLocStart();
837 if (begin.isInvalid() && getNumArgs() > 0)
838 begin = getArg(0)->getLocStart();
839 SourceLocation end = getRParenLoc();
840 if (end.isInvalid() && getNumArgs() > 0)
841 end = getArg(getNumArgs() - 1)->getLocEnd();
842 return SourceRange(begin, end);
843}
844
Sean Huntc3021132010-05-05 15:23:54 +0000845OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000846 SourceLocation OperatorLoc,
Sean Huntc3021132010-05-05 15:23:54 +0000847 TypeSourceInfo *tsi,
848 OffsetOfNode* compsPtr, unsigned numComps,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000849 Expr** exprsPtr, unsigned numExprs,
850 SourceLocation RParenLoc) {
851 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
Sean Huntc3021132010-05-05 15:23:54 +0000852 sizeof(OffsetOfNode) * numComps +
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000853 sizeof(Expr*) * numExprs);
854
855 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps,
856 exprsPtr, numExprs, RParenLoc);
857}
858
859OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
860 unsigned numComps, unsigned numExprs) {
861 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
862 sizeof(OffsetOfNode) * numComps +
863 sizeof(Expr*) * numExprs);
864 return new (Mem) OffsetOfExpr(numComps, numExprs);
865}
866
Sean Huntc3021132010-05-05 15:23:54 +0000867OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000868 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Sean Huntc3021132010-05-05 15:23:54 +0000869 OffsetOfNode* compsPtr, unsigned numComps,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000870 Expr** exprsPtr, unsigned numExprs,
871 SourceLocation RParenLoc)
John McCallf89e55a2010-11-18 06:31:45 +0000872 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
873 /*TypeDependent=*/false,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000874 /*ValueDependent=*/tsi->getType()->isDependentType(),
875 tsi->getType()->containsUnexpandedParameterPack()),
Sean Huntc3021132010-05-05 15:23:54 +0000876 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
877 NumComps(numComps), NumExprs(numExprs)
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000878{
879 for(unsigned i = 0; i < numComps; ++i) {
880 setComponent(i, compsPtr[i]);
881 }
Sean Huntc3021132010-05-05 15:23:54 +0000882
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000883 for(unsigned i = 0; i < numExprs; ++i) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000884 if (exprsPtr[i]->isTypeDependent() || exprsPtr[i]->isValueDependent())
885 ExprBits.ValueDependent = true;
886 if (exprsPtr[i]->containsUnexpandedParameterPack())
887 ExprBits.ContainsUnexpandedParameterPack = true;
888
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000889 setIndexExpr(i, exprsPtr[i]);
890 }
891}
892
893IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
894 assert(getKind() == Field || getKind() == Identifier);
895 if (getKind() == Field)
896 return getField()->getIdentifier();
Sean Huntc3021132010-05-05 15:23:54 +0000897
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000898 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
899}
900
Mike Stump1eb44332009-09-09 15:08:12 +0000901MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000902 NestedNameSpecifierLoc QualifierLoc,
Eli Friedmanf595cc42009-12-04 06:40:45 +0000903 ValueDecl *memberdecl,
John McCall161755a2010-04-06 21:38:20 +0000904 DeclAccessPair founddecl,
Abramo Bagnara25777432010-08-11 22:01:17 +0000905 DeclarationNameInfo nameinfo,
John McCalld5532b62009-11-23 01:53:49 +0000906 const TemplateArgumentListInfo *targs,
John McCallf89e55a2010-11-18 06:31:45 +0000907 QualType ty,
908 ExprValueKind vk,
909 ExprObjectKind ok) {
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000910 std::size_t Size = sizeof(MemberExpr);
John McCall6bb80172010-03-30 21:47:33 +0000911
Douglas Gregor40d96a62011-02-28 21:54:11 +0000912 bool hasQualOrFound = (QualifierLoc ||
John McCall161755a2010-04-06 21:38:20 +0000913 founddecl.getDecl() != memberdecl ||
914 founddecl.getAccess() != memberdecl->getAccess());
John McCall6bb80172010-03-30 21:47:33 +0000915 if (hasQualOrFound)
916 Size += sizeof(MemberNameQualifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000917
John McCalld5532b62009-11-23 01:53:49 +0000918 if (targs)
919 Size += ExplicitTemplateArgumentList::sizeFor(*targs);
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Chris Lattner32488542010-10-30 05:14:06 +0000921 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
John McCallf89e55a2010-11-18 06:31:45 +0000922 MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
923 ty, vk, ok);
John McCall6bb80172010-03-30 21:47:33 +0000924
925 if (hasQualOrFound) {
Douglas Gregor40d96a62011-02-28 21:54:11 +0000926 // FIXME: Wrong. We should be looking at the member declaration we found.
927 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall6bb80172010-03-30 21:47:33 +0000928 E->setValueDependent(true);
929 E->setTypeDependent(true);
930 }
931 E->HasQualifierOrFoundDecl = true;
932
933 MemberNameQualifier *NQ = E->getMemberQualifier();
Douglas Gregor40d96a62011-02-28 21:54:11 +0000934 NQ->QualifierLoc = QualifierLoc;
John McCall6bb80172010-03-30 21:47:33 +0000935 NQ->FoundDecl = founddecl;
936 }
937
938 if (targs) {
939 E->HasExplicitTemplateArgumentList = true;
John McCall096832c2010-08-19 23:49:38 +0000940 E->getExplicitTemplateArgs().initializeFrom(*targs);
John McCall6bb80172010-03-30 21:47:33 +0000941 }
942
943 return E;
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000944}
945
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000946const char *CastExpr::getCastKindName() const {
947 switch (getCastKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000948 case CK_Dependent:
949 return "Dependent";
John McCall2de56d12010-08-25 11:45:40 +0000950 case CK_BitCast:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000951 return "BitCast";
John McCall2de56d12010-08-25 11:45:40 +0000952 case CK_LValueBitCast:
Douglas Gregore39a3892010-07-13 23:17:26 +0000953 return "LValueBitCast";
John McCall0ae287a2010-12-01 04:43:34 +0000954 case CK_LValueToRValue:
955 return "LValueToRValue";
John McCallf6a16482010-12-04 03:47:34 +0000956 case CK_GetObjCProperty:
957 return "GetObjCProperty";
John McCall2de56d12010-08-25 11:45:40 +0000958 case CK_NoOp:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000959 return "NoOp";
John McCall2de56d12010-08-25 11:45:40 +0000960 case CK_BaseToDerived:
Anders Carlsson11de6de2009-11-12 16:43:42 +0000961 return "BaseToDerived";
John McCall2de56d12010-08-25 11:45:40 +0000962 case CK_DerivedToBase:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000963 return "DerivedToBase";
John McCall2de56d12010-08-25 11:45:40 +0000964 case CK_UncheckedDerivedToBase:
John McCall23cba802010-03-30 23:58:03 +0000965 return "UncheckedDerivedToBase";
John McCall2de56d12010-08-25 11:45:40 +0000966 case CK_Dynamic:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000967 return "Dynamic";
John McCall2de56d12010-08-25 11:45:40 +0000968 case CK_ToUnion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000969 return "ToUnion";
John McCall2de56d12010-08-25 11:45:40 +0000970 case CK_ArrayToPointerDecay:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000971 return "ArrayToPointerDecay";
John McCall2de56d12010-08-25 11:45:40 +0000972 case CK_FunctionToPointerDecay:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000973 return "FunctionToPointerDecay";
John McCall2de56d12010-08-25 11:45:40 +0000974 case CK_NullToMemberPointer:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000975 return "NullToMemberPointer";
John McCall404cd162010-11-13 01:35:44 +0000976 case CK_NullToPointer:
977 return "NullToPointer";
John McCall2de56d12010-08-25 11:45:40 +0000978 case CK_BaseToDerivedMemberPointer:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000979 return "BaseToDerivedMemberPointer";
John McCall2de56d12010-08-25 11:45:40 +0000980 case CK_DerivedToBaseMemberPointer:
Anders Carlsson1a31a182009-10-30 00:46:35 +0000981 return "DerivedToBaseMemberPointer";
John McCall2de56d12010-08-25 11:45:40 +0000982 case CK_UserDefinedConversion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000983 return "UserDefinedConversion";
John McCall2de56d12010-08-25 11:45:40 +0000984 case CK_ConstructorConversion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000985 return "ConstructorConversion";
John McCall2de56d12010-08-25 11:45:40 +0000986 case CK_IntegralToPointer:
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000987 return "IntegralToPointer";
John McCall2de56d12010-08-25 11:45:40 +0000988 case CK_PointerToIntegral:
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000989 return "PointerToIntegral";
John McCalldaa8e4e2010-11-15 09:13:47 +0000990 case CK_PointerToBoolean:
991 return "PointerToBoolean";
John McCall2de56d12010-08-25 11:45:40 +0000992 case CK_ToVoid:
Anders Carlssonebeaf202009-10-16 02:35:04 +0000993 return "ToVoid";
John McCall2de56d12010-08-25 11:45:40 +0000994 case CK_VectorSplat:
Anders Carlsson16a89042009-10-16 05:23:41 +0000995 return "VectorSplat";
John McCall2de56d12010-08-25 11:45:40 +0000996 case CK_IntegralCast:
Anders Carlsson82debc72009-10-18 18:12:03 +0000997 return "IntegralCast";
John McCalldaa8e4e2010-11-15 09:13:47 +0000998 case CK_IntegralToBoolean:
999 return "IntegralToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001000 case CK_IntegralToFloating:
Anders Carlsson82debc72009-10-18 18:12:03 +00001001 return "IntegralToFloating";
John McCall2de56d12010-08-25 11:45:40 +00001002 case CK_FloatingToIntegral:
Anders Carlsson82debc72009-10-18 18:12:03 +00001003 return "FloatingToIntegral";
John McCall2de56d12010-08-25 11:45:40 +00001004 case CK_FloatingCast:
Benjamin Kramerc6b29162009-10-18 19:02:15 +00001005 return "FloatingCast";
John McCalldaa8e4e2010-11-15 09:13:47 +00001006 case CK_FloatingToBoolean:
1007 return "FloatingToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001008 case CK_MemberPointerToBoolean:
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001009 return "MemberPointerToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001010 case CK_AnyPointerToObjCPointerCast:
Fariborz Jahanian4cbf9d42009-12-08 23:46:15 +00001011 return "AnyPointerToObjCPointerCast";
John McCall2de56d12010-08-25 11:45:40 +00001012 case CK_AnyPointerToBlockPointerCast:
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001013 return "AnyPointerToBlockPointerCast";
John McCall2de56d12010-08-25 11:45:40 +00001014 case CK_ObjCObjectLValueCast:
Douglas Gregor569c3162010-08-07 11:51:51 +00001015 return "ObjCObjectLValueCast";
John McCall2bb5d002010-11-13 09:02:35 +00001016 case CK_FloatingRealToComplex:
1017 return "FloatingRealToComplex";
John McCallf3ea8cf2010-11-14 08:17:51 +00001018 case CK_FloatingComplexToReal:
1019 return "FloatingComplexToReal";
1020 case CK_FloatingComplexToBoolean:
1021 return "FloatingComplexToBoolean";
John McCall2bb5d002010-11-13 09:02:35 +00001022 case CK_FloatingComplexCast:
1023 return "FloatingComplexCast";
John McCallf3ea8cf2010-11-14 08:17:51 +00001024 case CK_FloatingComplexToIntegralComplex:
1025 return "FloatingComplexToIntegralComplex";
John McCall2bb5d002010-11-13 09:02:35 +00001026 case CK_IntegralRealToComplex:
1027 return "IntegralRealToComplex";
John McCallf3ea8cf2010-11-14 08:17:51 +00001028 case CK_IntegralComplexToReal:
1029 return "IntegralComplexToReal";
1030 case CK_IntegralComplexToBoolean:
1031 return "IntegralComplexToBoolean";
John McCall2bb5d002010-11-13 09:02:35 +00001032 case CK_IntegralComplexCast:
1033 return "IntegralComplexCast";
John McCallf3ea8cf2010-11-14 08:17:51 +00001034 case CK_IntegralComplexToFloatingComplex:
1035 return "IntegralComplexToFloatingComplex";
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001036 }
Mike Stump1eb44332009-09-09 15:08:12 +00001037
John McCall2bb5d002010-11-13 09:02:35 +00001038 llvm_unreachable("Unhandled cast kind!");
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001039 return 0;
1040}
1041
Douglas Gregor6eef5192009-12-14 19:27:10 +00001042Expr *CastExpr::getSubExprAsWritten() {
1043 Expr *SubExpr = 0;
1044 CastExpr *E = this;
1045 do {
1046 SubExpr = E->getSubExpr();
Sean Huntc3021132010-05-05 15:23:54 +00001047
Douglas Gregor6eef5192009-12-14 19:27:10 +00001048 // Skip any temporary bindings; they're implicit.
1049 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1050 SubExpr = Binder->getSubExpr();
Sean Huntc3021132010-05-05 15:23:54 +00001051
Douglas Gregor6eef5192009-12-14 19:27:10 +00001052 // Conversions by constructor and conversion functions have a
1053 // subexpression describing the call; strip it off.
John McCall2de56d12010-08-25 11:45:40 +00001054 if (E->getCastKind() == CK_ConstructorConversion)
Douglas Gregor6eef5192009-12-14 19:27:10 +00001055 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
John McCall2de56d12010-08-25 11:45:40 +00001056 else if (E->getCastKind() == CK_UserDefinedConversion)
Douglas Gregor6eef5192009-12-14 19:27:10 +00001057 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
Sean Huntc3021132010-05-05 15:23:54 +00001058
Douglas Gregor6eef5192009-12-14 19:27:10 +00001059 // If the subexpression we're left with is an implicit cast, look
1060 // through that, too.
Sean Huntc3021132010-05-05 15:23:54 +00001061 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1062
Douglas Gregor6eef5192009-12-14 19:27:10 +00001063 return SubExpr;
1064}
1065
John McCallf871d0c2010-08-07 06:22:56 +00001066CXXBaseSpecifier **CastExpr::path_buffer() {
1067 switch (getStmtClass()) {
1068#define ABSTRACT_STMT(x)
1069#define CASTEXPR(Type, Base) \
1070 case Stmt::Type##Class: \
1071 return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1072#define STMT(Type, Base)
1073#include "clang/AST/StmtNodes.inc"
1074 default:
1075 llvm_unreachable("non-cast expressions not possible here");
1076 return 0;
1077 }
1078}
1079
1080void CastExpr::setCastPath(const CXXCastPath &Path) {
1081 assert(Path.size() == path_size());
1082 memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1083}
1084
1085ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
1086 CastKind Kind, Expr *Operand,
1087 const CXXCastPath *BasePath,
John McCall5baba9d2010-08-25 10:28:54 +00001088 ExprValueKind VK) {
John McCallf871d0c2010-08-07 06:22:56 +00001089 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1090 void *Buffer =
1091 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1092 ImplicitCastExpr *E =
John McCall5baba9d2010-08-25 10:28:54 +00001093 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
John McCallf871d0c2010-08-07 06:22:56 +00001094 if (PathSize) E->setCastPath(*BasePath);
1095 return E;
1096}
1097
1098ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
1099 unsigned PathSize) {
1100 void *Buffer =
1101 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1102 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1103}
1104
1105
1106CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00001107 ExprValueKind VK, CastKind K, Expr *Op,
John McCallf871d0c2010-08-07 06:22:56 +00001108 const CXXCastPath *BasePath,
1109 TypeSourceInfo *WrittenTy,
1110 SourceLocation L, SourceLocation R) {
1111 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1112 void *Buffer =
1113 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1114 CStyleCastExpr *E =
John McCallf89e55a2010-11-18 06:31:45 +00001115 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
John McCallf871d0c2010-08-07 06:22:56 +00001116 if (PathSize) E->setCastPath(*BasePath);
1117 return E;
1118}
1119
1120CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
1121 void *Buffer =
1122 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1123 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1124}
1125
Reid Spencer5f016e22007-07-11 17:01:13 +00001126/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1127/// corresponds to, e.g. "<<=".
1128const char *BinaryOperator::getOpcodeStr(Opcode Op) {
1129 switch (Op) {
John McCall2de56d12010-08-25 11:45:40 +00001130 case BO_PtrMemD: return ".*";
1131 case BO_PtrMemI: return "->*";
1132 case BO_Mul: return "*";
1133 case BO_Div: return "/";
1134 case BO_Rem: return "%";
1135 case BO_Add: return "+";
1136 case BO_Sub: return "-";
1137 case BO_Shl: return "<<";
1138 case BO_Shr: return ">>";
1139 case BO_LT: return "<";
1140 case BO_GT: return ">";
1141 case BO_LE: return "<=";
1142 case BO_GE: return ">=";
1143 case BO_EQ: return "==";
1144 case BO_NE: return "!=";
1145 case BO_And: return "&";
1146 case BO_Xor: return "^";
1147 case BO_Or: return "|";
1148 case BO_LAnd: return "&&";
1149 case BO_LOr: return "||";
1150 case BO_Assign: return "=";
1151 case BO_MulAssign: return "*=";
1152 case BO_DivAssign: return "/=";
1153 case BO_RemAssign: return "%=";
1154 case BO_AddAssign: return "+=";
1155 case BO_SubAssign: return "-=";
1156 case BO_ShlAssign: return "<<=";
1157 case BO_ShrAssign: return ">>=";
1158 case BO_AndAssign: return "&=";
1159 case BO_XorAssign: return "^=";
1160 case BO_OrAssign: return "|=";
1161 case BO_Comma: return ",";
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 }
Douglas Gregorbaf53482009-03-12 22:51:37 +00001163
1164 return "";
Reid Spencer5f016e22007-07-11 17:01:13 +00001165}
1166
John McCall2de56d12010-08-25 11:45:40 +00001167BinaryOperatorKind
Douglas Gregor063daf62009-03-13 18:40:31 +00001168BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1169 switch (OO) {
Chris Lattnerb7beee92009-03-22 00:10:22 +00001170 default: assert(false && "Not an overloadable binary operator");
John McCall2de56d12010-08-25 11:45:40 +00001171 case OO_Plus: return BO_Add;
1172 case OO_Minus: return BO_Sub;
1173 case OO_Star: return BO_Mul;
1174 case OO_Slash: return BO_Div;
1175 case OO_Percent: return BO_Rem;
1176 case OO_Caret: return BO_Xor;
1177 case OO_Amp: return BO_And;
1178 case OO_Pipe: return BO_Or;
1179 case OO_Equal: return BO_Assign;
1180 case OO_Less: return BO_LT;
1181 case OO_Greater: return BO_GT;
1182 case OO_PlusEqual: return BO_AddAssign;
1183 case OO_MinusEqual: return BO_SubAssign;
1184 case OO_StarEqual: return BO_MulAssign;
1185 case OO_SlashEqual: return BO_DivAssign;
1186 case OO_PercentEqual: return BO_RemAssign;
1187 case OO_CaretEqual: return BO_XorAssign;
1188 case OO_AmpEqual: return BO_AndAssign;
1189 case OO_PipeEqual: return BO_OrAssign;
1190 case OO_LessLess: return BO_Shl;
1191 case OO_GreaterGreater: return BO_Shr;
1192 case OO_LessLessEqual: return BO_ShlAssign;
1193 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1194 case OO_EqualEqual: return BO_EQ;
1195 case OO_ExclaimEqual: return BO_NE;
1196 case OO_LessEqual: return BO_LE;
1197 case OO_GreaterEqual: return BO_GE;
1198 case OO_AmpAmp: return BO_LAnd;
1199 case OO_PipePipe: return BO_LOr;
1200 case OO_Comma: return BO_Comma;
1201 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor063daf62009-03-13 18:40:31 +00001202 }
1203}
1204
1205OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1206 static const OverloadedOperatorKind OverOps[] = {
1207 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1208 OO_Star, OO_Slash, OO_Percent,
1209 OO_Plus, OO_Minus,
1210 OO_LessLess, OO_GreaterGreater,
1211 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1212 OO_EqualEqual, OO_ExclaimEqual,
1213 OO_Amp,
1214 OO_Caret,
1215 OO_Pipe,
1216 OO_AmpAmp,
1217 OO_PipePipe,
1218 OO_Equal, OO_StarEqual,
1219 OO_SlashEqual, OO_PercentEqual,
1220 OO_PlusEqual, OO_MinusEqual,
1221 OO_LessLessEqual, OO_GreaterGreaterEqual,
1222 OO_AmpEqual, OO_CaretEqual,
1223 OO_PipeEqual,
1224 OO_Comma
1225 };
1226 return OverOps[Opc];
1227}
1228
Ted Kremenek709210f2010-04-13 23:39:13 +00001229InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
Chris Lattner418f6c72008-10-26 23:43:26 +00001230 Expr **initExprs, unsigned numInits,
Douglas Gregor4c678342009-01-28 21:54:33 +00001231 SourceLocation rbraceloc)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001232 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1233 false),
Ted Kremenek709210f2010-04-13 23:39:13 +00001234 InitExprs(C, numInits),
Mike Stump1eb44332009-09-09 15:08:12 +00001235 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0),
Sean Huntc3021132010-05-05 15:23:54 +00001236 UnionFieldInit(0), HadArrayRangeDesignator(false)
1237{
Ted Kremenekba7bc552010-02-19 01:50:18 +00001238 for (unsigned I = 0; I != numInits; ++I) {
1239 if (initExprs[I]->isTypeDependent())
John McCall8e6285a2010-10-26 08:39:16 +00001240 ExprBits.TypeDependent = true;
Ted Kremenekba7bc552010-02-19 01:50:18 +00001241 if (initExprs[I]->isValueDependent())
John McCall8e6285a2010-10-26 08:39:16 +00001242 ExprBits.ValueDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001243 if (initExprs[I]->containsUnexpandedParameterPack())
1244 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor73460a32009-11-19 23:25:22 +00001245 }
Sean Huntc3021132010-05-05 15:23:54 +00001246
Ted Kremenek709210f2010-04-13 23:39:13 +00001247 InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001248}
Reid Spencer5f016e22007-07-11 17:01:13 +00001249
Ted Kremenek709210f2010-04-13 23:39:13 +00001250void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
Ted Kremenekba7bc552010-02-19 01:50:18 +00001251 if (NumInits > InitExprs.size())
Ted Kremenek709210f2010-04-13 23:39:13 +00001252 InitExprs.reserve(C, NumInits);
Douglas Gregorfa219202009-03-20 23:58:33 +00001253}
1254
Ted Kremenek709210f2010-04-13 23:39:13 +00001255void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
Ted Kremenek709210f2010-04-13 23:39:13 +00001256 InitExprs.resize(C, NumInits, 0);
Douglas Gregor4c678342009-01-28 21:54:33 +00001257}
1258
Ted Kremenek709210f2010-04-13 23:39:13 +00001259Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenekba7bc552010-02-19 01:50:18 +00001260 if (Init >= InitExprs.size()) {
Ted Kremenek709210f2010-04-13 23:39:13 +00001261 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
Ted Kremenekba7bc552010-02-19 01:50:18 +00001262 InitExprs.back() = expr;
1263 return 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001264 }
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Douglas Gregor4c678342009-01-28 21:54:33 +00001266 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1267 InitExprs[Init] = expr;
1268 return Result;
1269}
1270
Ted Kremenekc4ba51f2010-11-09 02:11:40 +00001271SourceRange InitListExpr::getSourceRange() const {
1272 if (SyntacticForm)
1273 return SyntacticForm->getSourceRange();
1274 SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1275 if (Beg.isInvalid()) {
1276 // Find the first non-null initializer.
1277 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1278 E = InitExprs.end();
1279 I != E; ++I) {
1280 if (Stmt *S = *I) {
1281 Beg = S->getLocStart();
1282 break;
1283 }
1284 }
1285 }
1286 if (End.isInvalid()) {
1287 // Find the first non-null initializer from the end.
1288 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1289 E = InitExprs.rend();
1290 I != E; ++I) {
1291 if (Stmt *S = *I) {
1292 End = S->getSourceRange().getEnd();
1293 break;
1294 }
1295 }
1296 }
1297 return SourceRange(Beg, End);
1298}
1299
Steve Naroffbfdcae62008-09-04 15:31:07 +00001300/// getFunctionType - Return the underlying function type for this block.
Steve Naroff4eb206b2008-09-03 18:15:37 +00001301///
1302const FunctionType *BlockExpr::getFunctionType() const {
Ted Kremenek6217b802009-07-29 21:53:49 +00001303 return getType()->getAs<BlockPointerType>()->
John McCall183700f2009-09-21 23:43:11 +00001304 getPointeeType()->getAs<FunctionType>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00001305}
1306
Mike Stump1eb44332009-09-09 15:08:12 +00001307SourceLocation BlockExpr::getCaretLocation() const {
1308 return TheBlock->getCaretLocation();
Steve Naroff56ee6892008-10-08 17:01:13 +00001309}
Mike Stump1eb44332009-09-09 15:08:12 +00001310const Stmt *BlockExpr::getBody() const {
Douglas Gregor72971342009-04-18 00:02:19 +00001311 return TheBlock->getBody();
1312}
Mike Stump1eb44332009-09-09 15:08:12 +00001313Stmt *BlockExpr::getBody() {
1314 return TheBlock->getBody();
Douglas Gregor72971342009-04-18 00:02:19 +00001315}
Steve Naroff56ee6892008-10-08 17:01:13 +00001316
1317
Reid Spencer5f016e22007-07-11 17:01:13 +00001318//===----------------------------------------------------------------------===//
1319// Generic Expression Routines
1320//===----------------------------------------------------------------------===//
1321
Chris Lattner026dc962009-02-14 07:37:35 +00001322/// isUnusedResultAWarning - Return true if this immediate expression should
1323/// be warned about if the result is unused. If so, fill in Loc and Ranges
1324/// with location to warn on and the source range[s] to report with the
1325/// warning.
1326bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
Mike Stumpdf317bf2009-11-03 23:25:48 +00001327 SourceRange &R2, ASTContext &Ctx) const {
Anders Carlssonffce2df2009-05-15 23:10:19 +00001328 // Don't warn if the expr is type dependent. The type could end up
1329 // instantiating to void.
1330 if (isTypeDependent())
1331 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Reid Spencer5f016e22007-07-11 17:01:13 +00001333 switch (getStmtClass()) {
1334 default:
John McCall0faede62010-03-12 07:11:26 +00001335 if (getType()->isVoidType())
1336 return false;
Chris Lattner026dc962009-02-14 07:37:35 +00001337 Loc = getExprLoc();
1338 R1 = getSourceRange();
1339 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 case ParenExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001341 return cast<ParenExpr>(this)->getSubExpr()->
Mike Stumpdf317bf2009-11-03 23:25:48 +00001342 isUnusedResultAWarning(Loc, R1, R2, Ctx);
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 case UnaryOperatorClass: {
1344 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 switch (UO->getOpcode()) {
Chris Lattner026dc962009-02-14 07:37:35 +00001347 default: break;
John McCall2de56d12010-08-25 11:45:40 +00001348 case UO_PostInc:
1349 case UO_PostDec:
1350 case UO_PreInc:
1351 case UO_PreDec: // ++/--
Chris Lattner026dc962009-02-14 07:37:35 +00001352 return false; // Not a warning.
John McCall2de56d12010-08-25 11:45:40 +00001353 case UO_Deref:
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 // Dereferencing a volatile pointer is a side-effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001355 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001356 return false;
1357 break;
John McCall2de56d12010-08-25 11:45:40 +00001358 case UO_Real:
1359 case UO_Imag:
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 // accessing a piece of a volatile complex is a side-effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001361 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1362 .isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001363 return false;
1364 break;
John McCall2de56d12010-08-25 11:45:40 +00001365 case UO_Extension:
Mike Stumpdf317bf2009-11-03 23:25:48 +00001366 return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 }
Chris Lattner026dc962009-02-14 07:37:35 +00001368 Loc = UO->getOperatorLoc();
1369 R1 = UO->getSubExpr()->getSourceRange();
1370 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 }
Chris Lattnere7716e62007-12-01 06:07:34 +00001372 case BinaryOperatorClass: {
Chris Lattner026dc962009-02-14 07:37:35 +00001373 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenekc46a2462010-04-07 18:49:21 +00001374 switch (BO->getOpcode()) {
1375 default:
1376 break;
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001377 // Consider the RHS of comma for side effects. LHS was checked by
1378 // Sema::CheckCommaOperands.
John McCall2de56d12010-08-25 11:45:40 +00001379 case BO_Comma:
Ted Kremenekc46a2462010-04-07 18:49:21 +00001380 // ((foo = <blah>), 0) is an idiom for hiding the result (and
1381 // lvalue-ness) of an assignment written in a macro.
1382 if (IntegerLiteral *IE =
1383 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1384 if (IE->getValue() == 0)
1385 return false;
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001386 return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1387 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCall2de56d12010-08-25 11:45:40 +00001388 case BO_LAnd:
1389 case BO_LOr:
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001390 if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) ||
1391 !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1392 return false;
1393 break;
John McCallbf0ee352010-02-16 04:10:53 +00001394 }
Chris Lattner026dc962009-02-14 07:37:35 +00001395 if (BO->isAssignmentOp())
1396 return false;
1397 Loc = BO->getOperatorLoc();
1398 R1 = BO->getLHS()->getSourceRange();
1399 R2 = BO->getRHS()->getSourceRange();
1400 return true;
Chris Lattnere7716e62007-12-01 06:07:34 +00001401 }
Chris Lattnereb14fe82007-08-25 02:00:02 +00001402 case CompoundAssignOperatorClass:
Douglas Gregorc6dfe192010-05-08 22:41:50 +00001403 case VAArgExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001404 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001405
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001406 case ConditionalOperatorClass: {
Ted Kremenekfb7cb352011-03-01 20:34:48 +00001407 // If only one of the LHS or RHS is a warning, the operator might
1408 // be being used for control flow. Only warn if both the LHS and
1409 // RHS are warnings.
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001410 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Ted Kremenekfb7cb352011-03-01 20:34:48 +00001411 if (!Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1412 return false;
1413 if (!Exp->getLHS())
Chris Lattner026dc962009-02-14 07:37:35 +00001414 return true;
Ted Kremenekfb7cb352011-03-01 20:34:48 +00001415 return Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001416 }
1417
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 case MemberExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001419 // If the base pointer or element is to a volatile pointer/field, accessing
1420 // it is a side effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001421 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001422 return false;
1423 Loc = cast<MemberExpr>(this)->getMemberLoc();
1424 R1 = SourceRange(Loc, Loc);
1425 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1426 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 case ArraySubscriptExprClass:
1429 // If the base pointer or element is to a volatile pointer/field, accessing
Chris Lattner026dc962009-02-14 07:37:35 +00001430 // it is a side effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001431 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001432 return false;
1433 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1434 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1435 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1436 return true;
Eli Friedman211f6ad2008-05-27 15:24:04 +00001437
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 case CallExprClass:
Eli Friedman852871a2009-04-29 16:35:53 +00001439 case CXXOperatorCallExprClass:
1440 case CXXMemberCallExprClass: {
Chris Lattner026dc962009-02-14 07:37:35 +00001441 // If this is a direct call, get the callee.
1442 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopesd20254f2009-12-20 23:11:08 +00001443 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner026dc962009-02-14 07:37:35 +00001444 // If the callee has attribute pure, const, or warn_unused_result, warn
1445 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattnerbc8d42c2009-10-13 04:53:48 +00001446 //
1447 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1448 // updated to match for QoI.
1449 if (FD->getAttr<WarnUnusedResultAttr>() ||
1450 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
1451 Loc = CE->getCallee()->getLocStart();
1452 R1 = CE->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Chris Lattnerbc8d42c2009-10-13 04:53:48 +00001454 if (unsigned NumArgs = CE->getNumArgs())
1455 R2 = SourceRange(CE->getArg(0)->getLocStart(),
1456 CE->getArg(NumArgs-1)->getLocEnd());
1457 return true;
1458 }
Chris Lattner026dc962009-02-14 07:37:35 +00001459 }
1460 return false;
1461 }
Anders Carlsson58beed92009-11-17 17:11:23 +00001462
1463 case CXXTemporaryObjectExprClass:
1464 case CXXConstructExprClass:
1465 return false;
1466
Fariborz Jahanianf0317742010-03-30 18:22:15 +00001467 case ObjCMessageExprClass: {
1468 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
1469 const ObjCMethodDecl *MD = ME->getMethodDecl();
1470 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
1471 Loc = getExprLoc();
1472 return true;
1473 }
Chris Lattner026dc962009-02-14 07:37:35 +00001474 return false;
Fariborz Jahanianf0317742010-03-30 18:22:15 +00001475 }
Mike Stump1eb44332009-09-09 15:08:12 +00001476
John McCall12f78a62010-12-02 01:19:52 +00001477 case ObjCPropertyRefExprClass:
Chris Lattner5e94a0d2009-08-16 16:51:50 +00001478 Loc = getExprLoc();
1479 R1 = getSourceRange();
Chris Lattnera50089e2009-08-16 16:45:18 +00001480 return true;
John McCall12f78a62010-12-02 01:19:52 +00001481
Chris Lattner611b2ec2008-07-26 19:51:01 +00001482 case StmtExprClass: {
1483 // Statement exprs don't logically have side effects themselves, but are
1484 // sometimes used in macros in ways that give them a type that is unused.
1485 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
1486 // however, if the result of the stmt expr is dead, we don't want to emit a
1487 // warning.
1488 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +00001489 if (!CS->body_empty()) {
Chris Lattner611b2ec2008-07-26 19:51:01 +00001490 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00001491 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +00001492 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
1493 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
1494 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1495 }
Mike Stump1eb44332009-09-09 15:08:12 +00001496
John McCall0faede62010-03-12 07:11:26 +00001497 if (getType()->isVoidType())
1498 return false;
Chris Lattner026dc962009-02-14 07:37:35 +00001499 Loc = cast<StmtExpr>(this)->getLParenLoc();
1500 R1 = getSourceRange();
1501 return true;
Chris Lattner611b2ec2008-07-26 19:51:01 +00001502 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001503 case CStyleCastExprClass:
Chris Lattnerfb846642009-07-28 18:25:28 +00001504 // If this is an explicit cast to void, allow it. People do this when they
1505 // think they know what they're doing :).
Chris Lattner026dc962009-02-14 07:37:35 +00001506 if (getType()->isVoidType())
Chris Lattnerfb846642009-07-28 18:25:28 +00001507 return false;
Chris Lattner026dc962009-02-14 07:37:35 +00001508 Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
1509 R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
1510 return true;
Anders Carlsson58beed92009-11-17 17:11:23 +00001511 case CXXFunctionalCastExprClass: {
John McCall0faede62010-03-12 07:11:26 +00001512 if (getType()->isVoidType())
1513 return false;
Anders Carlsson58beed92009-11-17 17:11:23 +00001514 const CastExpr *CE = cast<CastExpr>(this);
Sean Huntc3021132010-05-05 15:23:54 +00001515
Anders Carlsson58beed92009-11-17 17:11:23 +00001516 // If this is a cast to void or a constructor conversion, check the operand.
1517 // Otherwise, the result of the cast is unused.
John McCall2de56d12010-08-25 11:45:40 +00001518 if (CE->getCastKind() == CK_ToVoid ||
1519 CE->getCastKind() == CK_ConstructorConversion)
Mike Stumpdf317bf2009-11-03 23:25:48 +00001520 return (cast<CastExpr>(this)->getSubExpr()
1521 ->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Chris Lattner026dc962009-02-14 07:37:35 +00001522 Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
1523 R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
1524 return true;
Anders Carlsson58beed92009-11-17 17:11:23 +00001525 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Eli Friedman4be1f472008-05-19 21:24:43 +00001527 case ImplicitCastExprClass:
1528 // Check the operand, since implicit casts are inserted by Sema
Mike Stumpdf317bf2009-11-03 23:25:48 +00001529 return (cast<ImplicitCastExpr>(this)
1530 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Eli Friedman4be1f472008-05-19 21:24:43 +00001531
Chris Lattner04421082008-04-08 04:40:51 +00001532 case CXXDefaultArgExprClass:
Mike Stumpdf317bf2009-11-03 23:25:48 +00001533 return (cast<CXXDefaultArgExpr>(this)
1534 ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001535
1536 case CXXNewExprClass:
1537 // FIXME: In theory, there might be new expressions that don't have side
1538 // effects (e.g. a placement new with an uninitialized POD).
1539 case CXXDeleteExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001540 return false;
Anders Carlsson2d46eb22009-08-16 04:11:06 +00001541 case CXXBindTemporaryExprClass:
Mike Stumpdf317bf2009-11-03 23:25:48 +00001542 return (cast<CXXBindTemporaryExpr>(this)
1543 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
John McCall4765fa02010-12-06 08:20:24 +00001544 case ExprWithCleanupsClass:
1545 return (cast<ExprWithCleanups>(this)
Mike Stumpdf317bf2009-11-03 23:25:48 +00001546 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001547 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001548}
1549
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001550/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian7f4f86a2009-09-08 23:38:54 +00001551/// returns true, if it is; false otherwise.
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001552bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001553 switch (getStmtClass()) {
1554 default:
1555 return false;
1556 case ObjCIvarRefExprClass:
1557 return true;
Fariborz Jahanian207c5212009-02-23 18:59:50 +00001558 case Expr::UnaryOperatorClass:
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001559 return cast<UnaryOperator>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001560 case ParenExprClass:
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001561 return cast<ParenExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001562 case ImplicitCastExprClass:
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001563 return cast<ImplicitCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian06b89122009-05-05 23:28:21 +00001564 case CStyleCastExprClass:
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001565 return cast<CStyleCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregora2813ce2009-10-23 18:54:35 +00001566 case DeclRefExprClass: {
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001567 const Decl *D = cast<DeclRefExpr>(this)->getDecl();
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001568 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1569 if (VD->hasGlobalStorage())
1570 return true;
1571 QualType T = VD->getType();
Fariborz Jahanian59a53fa2009-09-16 18:09:18 +00001572 // dereferencing to a pointer is always a gc'able candidate,
1573 // unless it is __weak.
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001574 return T->isPointerType() &&
John McCall0953e762009-09-24 19:53:00 +00001575 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001576 }
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001577 return false;
1578 }
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001579 case MemberExprClass: {
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001580 const MemberExpr *M = cast<MemberExpr>(this);
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001581 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001582 }
1583 case ArraySubscriptExprClass:
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001584 return cast<ArraySubscriptExpr>(this)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001585 }
1586}
Sebastian Redl369e51f2010-09-10 20:55:33 +00001587
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00001588bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
1589 if (isTypeDependent())
1590 return false;
John McCall7eb0a9e2010-11-24 05:12:34 +00001591 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00001592}
1593
Sebastian Redl369e51f2010-09-10 20:55:33 +00001594static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1,
1595 Expr::CanThrowResult CT2) {
1596 // CanThrowResult constants are ordered so that the maximum is the correct
1597 // merge result.
1598 return CT1 > CT2 ? CT1 : CT2;
1599}
1600
1601static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) {
1602 Expr *E = const_cast<Expr*>(CE);
1603 Expr::CanThrowResult R = Expr::CT_Cannot;
John McCall7502c1d2011-02-13 04:07:26 +00001604 for (Expr::child_range I = E->children(); I && R != Expr::CT_Can; ++I) {
Sebastian Redl369e51f2010-09-10 20:55:33 +00001605 R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C));
1606 }
1607 return R;
1608}
1609
1610static Expr::CanThrowResult CanCalleeThrow(const Decl *D,
1611 bool NullThrows = true) {
1612 if (!D)
1613 return NullThrows ? Expr::CT_Can : Expr::CT_Cannot;
1614
1615 // See if we can get a function type from the decl somehow.
1616 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
1617 if (!VD) // If we have no clue what we're calling, assume the worst.
1618 return Expr::CT_Can;
1619
Sebastian Redl5221d8f2010-09-10 22:34:40 +00001620 // As an extension, we assume that __attribute__((nothrow)) functions don't
1621 // throw.
1622 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
1623 return Expr::CT_Cannot;
1624
Sebastian Redl369e51f2010-09-10 20:55:33 +00001625 QualType T = VD->getType();
1626 const FunctionProtoType *FT;
1627 if ((FT = T->getAs<FunctionProtoType>())) {
1628 } else if (const PointerType *PT = T->getAs<PointerType>())
1629 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1630 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1631 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1632 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1633 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1634 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1635 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1636
1637 if (!FT)
1638 return Expr::CT_Can;
1639
1640 return FT->hasEmptyExceptionSpec() ? Expr::CT_Cannot : Expr::CT_Can;
1641}
1642
1643static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1644 if (DC->isTypeDependent())
1645 return Expr::CT_Dependent;
1646
Sebastian Redl295995c2010-09-10 20:55:47 +00001647 if (!DC->getTypeAsWritten()->isReferenceType())
1648 return Expr::CT_Cannot;
1649
Sebastian Redl369e51f2010-09-10 20:55:33 +00001650 return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot;
1651}
1652
1653static Expr::CanThrowResult CanTypeidThrow(ASTContext &C,
1654 const CXXTypeidExpr *DC) {
1655 if (DC->isTypeOperand())
1656 return Expr::CT_Cannot;
1657
1658 Expr *Op = DC->getExprOperand();
1659 if (Op->isTypeDependent())
1660 return Expr::CT_Dependent;
1661
1662 const RecordType *RT = Op->getType()->getAs<RecordType>();
1663 if (!RT)
1664 return Expr::CT_Cannot;
1665
1666 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1667 return Expr::CT_Cannot;
1668
1669 if (Op->Classify(C).isPRValue())
1670 return Expr::CT_Cannot;
1671
1672 return Expr::CT_Can;
1673}
1674
1675Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const {
1676 // C++ [expr.unary.noexcept]p3:
1677 // [Can throw] if in a potentially-evaluated context the expression would
1678 // contain:
1679 switch (getStmtClass()) {
1680 case CXXThrowExprClass:
1681 // - a potentially evaluated throw-expression
1682 return CT_Can;
1683
1684 case CXXDynamicCastExprClass: {
1685 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1686 // where T is a reference type, that requires a run-time check
1687 CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this));
1688 if (CT == CT_Can)
1689 return CT;
1690 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1691 }
1692
1693 case CXXTypeidExprClass:
1694 // - a potentially evaluated typeid expression applied to a glvalue
1695 // expression whose type is a polymorphic class type
1696 return CanTypeidThrow(C, cast<CXXTypeidExpr>(this));
1697
1698 // - a potentially evaluated call to a function, member function, function
1699 // pointer, or member function pointer that does not have a non-throwing
1700 // exception-specification
1701 case CallExprClass:
1702 case CXXOperatorCallExprClass:
1703 case CXXMemberCallExprClass: {
1704 CanThrowResult CT = CanCalleeThrow(cast<CallExpr>(this)->getCalleeDecl());
1705 if (CT == CT_Can)
1706 return CT;
1707 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1708 }
1709
Sebastian Redl295995c2010-09-10 20:55:47 +00001710 case CXXConstructExprClass:
1711 case CXXTemporaryObjectExprClass: {
Sebastian Redl369e51f2010-09-10 20:55:33 +00001712 CanThrowResult CT = CanCalleeThrow(
1713 cast<CXXConstructExpr>(this)->getConstructor());
1714 if (CT == CT_Can)
1715 return CT;
1716 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1717 }
1718
1719 case CXXNewExprClass: {
1720 CanThrowResult CT = MergeCanThrow(
1721 CanCalleeThrow(cast<CXXNewExpr>(this)->getOperatorNew()),
1722 CanCalleeThrow(cast<CXXNewExpr>(this)->getConstructor(),
1723 /*NullThrows*/false));
1724 if (CT == CT_Can)
1725 return CT;
1726 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1727 }
1728
1729 case CXXDeleteExprClass: {
Sebastian Redl369e51f2010-09-10 20:55:33 +00001730 CanThrowResult CT = CanCalleeThrow(
1731 cast<CXXDeleteExpr>(this)->getOperatorDelete());
1732 if (CT == CT_Can)
1733 return CT;
Sebastian Redl0b34cf72010-09-10 23:27:10 +00001734 const Expr *Arg = cast<CXXDeleteExpr>(this)->getArgument();
1735 // Unwrap exactly one implicit cast, which converts all pointers to void*.
1736 if (const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1737 Arg = Cast->getSubExpr();
1738 if (const PointerType *PT = Arg->getType()->getAs<PointerType>()) {
1739 if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>()) {
1740 CanThrowResult CT2 = CanCalleeThrow(
1741 cast<CXXRecordDecl>(RT->getDecl())->getDestructor());
1742 if (CT2 == CT_Can)
1743 return CT2;
1744 CT = MergeCanThrow(CT, CT2);
1745 }
1746 }
1747 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1748 }
1749
1750 case CXXBindTemporaryExprClass: {
1751 // The bound temporary has to be destroyed again, which might throw.
1752 CanThrowResult CT = CanCalleeThrow(
1753 cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor());
1754 if (CT == CT_Can)
1755 return CT;
Sebastian Redl369e51f2010-09-10 20:55:33 +00001756 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1757 }
1758
1759 // ObjC message sends are like function calls, but never have exception
1760 // specs.
1761 case ObjCMessageExprClass:
1762 case ObjCPropertyRefExprClass:
Sebastian Redl369e51f2010-09-10 20:55:33 +00001763 return CT_Can;
1764
1765 // Many other things have subexpressions, so we have to test those.
1766 // Some are simple:
1767 case ParenExprClass:
1768 case MemberExprClass:
1769 case CXXReinterpretCastExprClass:
1770 case CXXConstCastExprClass:
1771 case ConditionalOperatorClass:
1772 case CompoundLiteralExprClass:
1773 case ExtVectorElementExprClass:
1774 case InitListExprClass:
1775 case DesignatedInitExprClass:
1776 case ParenListExprClass:
1777 case VAArgExprClass:
1778 case CXXDefaultArgExprClass:
John McCall4765fa02010-12-06 08:20:24 +00001779 case ExprWithCleanupsClass:
Sebastian Redl369e51f2010-09-10 20:55:33 +00001780 case ObjCIvarRefExprClass:
1781 case ObjCIsaExprClass:
1782 case ShuffleVectorExprClass:
1783 return CanSubExprsThrow(C, this);
1784
1785 // Some might be dependent for other reasons.
1786 case UnaryOperatorClass:
1787 case ArraySubscriptExprClass:
1788 case ImplicitCastExprClass:
1789 case CStyleCastExprClass:
1790 case CXXStaticCastExprClass:
1791 case CXXFunctionalCastExprClass:
1792 case BinaryOperatorClass:
1793 case CompoundAssignOperatorClass: {
1794 CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot;
1795 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1796 }
1797
1798 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1799 case StmtExprClass:
1800 return CT_Can;
1801
1802 case ChooseExprClass:
1803 if (isTypeDependent() || isValueDependent())
1804 return CT_Dependent;
1805 return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C);
1806
1807 // Some expressions are always dependent.
1808 case DependentScopeDeclRefExprClass:
1809 case CXXUnresolvedConstructExprClass:
1810 case CXXDependentScopeMemberExprClass:
1811 return CT_Dependent;
1812
1813 default:
1814 // All other expressions don't have subexpressions, or else they are
1815 // unevaluated.
1816 return CT_Cannot;
1817 }
1818}
1819
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001820Expr* Expr::IgnoreParens() {
1821 Expr* E = this;
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001822 while (true) {
1823 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
1824 E = P->getSubExpr();
1825 continue;
1826 }
1827 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1828 if (P->getOpcode() == UO_Extension) {
1829 E = P->getSubExpr();
1830 continue;
1831 }
1832 }
1833 return E;
1834 }
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001835}
1836
Chris Lattner56f34942008-02-13 01:02:39 +00001837/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
1838/// or CastExprs or ImplicitCastExprs, returning their operand.
1839Expr *Expr::IgnoreParenCasts() {
1840 Expr *E = this;
1841 while (true) {
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001842 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
Chris Lattner56f34942008-02-13 01:02:39 +00001843 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001844 continue;
1845 }
1846 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattner56f34942008-02-13 01:02:39 +00001847 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001848 continue;
1849 }
1850 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1851 if (P->getOpcode() == UO_Extension) {
1852 E = P->getSubExpr();
1853 continue;
1854 }
1855 }
1856 return E;
Chris Lattner56f34942008-02-13 01:02:39 +00001857 }
1858}
1859
John McCall9c5d70c2010-12-04 08:24:19 +00001860/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
1861/// casts. This is intended purely as a temporary workaround for code
1862/// that hasn't yet been rewritten to do the right thing about those
1863/// casts, and may disappear along with the last internal use.
John McCallf6a16482010-12-04 03:47:34 +00001864Expr *Expr::IgnoreParenLValueCasts() {
1865 Expr *E = this;
John McCall9c5d70c2010-12-04 08:24:19 +00001866 while (true) {
John McCallf6a16482010-12-04 03:47:34 +00001867 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1868 E = P->getSubExpr();
1869 continue;
John McCall9c5d70c2010-12-04 08:24:19 +00001870 } else if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCallf6a16482010-12-04 03:47:34 +00001871 if (P->getCastKind() == CK_LValueToRValue) {
1872 E = P->getSubExpr();
1873 continue;
1874 }
John McCall9c5d70c2010-12-04 08:24:19 +00001875 } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1876 if (P->getOpcode() == UO_Extension) {
1877 E = P->getSubExpr();
1878 continue;
1879 }
John McCallf6a16482010-12-04 03:47:34 +00001880 }
1881 break;
1882 }
1883 return E;
1884}
1885
John McCall2fc46bf2010-05-05 22:59:52 +00001886Expr *Expr::IgnoreParenImpCasts() {
1887 Expr *E = this;
1888 while (true) {
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001889 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
John McCall2fc46bf2010-05-05 22:59:52 +00001890 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001891 continue;
1892 }
1893 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2fc46bf2010-05-05 22:59:52 +00001894 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001895 continue;
1896 }
1897 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1898 if (P->getOpcode() == UO_Extension) {
1899 E = P->getSubExpr();
1900 continue;
1901 }
1902 }
1903 return E;
John McCall2fc46bf2010-05-05 22:59:52 +00001904 }
1905}
1906
Chris Lattnerecdd8412009-03-13 17:28:01 +00001907/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
1908/// value (including ptr->int casts of the same size). Strip off any
1909/// ParenExpr or CastExprs, returning their operand.
1910Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
1911 Expr *E = this;
1912 while (true) {
1913 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1914 E = P->getSubExpr();
1915 continue;
1916 }
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Chris Lattnerecdd8412009-03-13 17:28:01 +00001918 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1919 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001920 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattnerecdd8412009-03-13 17:28:01 +00001921 Expr *SE = P->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Chris Lattnerecdd8412009-03-13 17:28:01 +00001923 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
1924 E = SE;
1925 continue;
1926 }
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001928 if ((E->getType()->isPointerType() ||
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001929 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001930 (SE->getType()->isPointerType() ||
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001931 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattnerecdd8412009-03-13 17:28:01 +00001932 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
1933 E = SE;
1934 continue;
1935 }
1936 }
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001938 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1939 if (P->getOpcode() == UO_Extension) {
1940 E = P->getSubExpr();
1941 continue;
1942 }
1943 }
1944
Chris Lattnerecdd8412009-03-13 17:28:01 +00001945 return E;
1946 }
1947}
1948
Douglas Gregor6eef5192009-12-14 19:27:10 +00001949bool Expr::isDefaultArgument() const {
1950 const Expr *E = this;
1951 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
1952 E = ICE->getSubExprAsWritten();
Sean Huntc3021132010-05-05 15:23:54 +00001953
Douglas Gregor6eef5192009-12-14 19:27:10 +00001954 return isa<CXXDefaultArgExpr>(E);
1955}
Chris Lattnerecdd8412009-03-13 17:28:01 +00001956
Douglas Gregor2f599792010-04-02 18:24:57 +00001957/// \brief Skip over any no-op casts and any temporary-binding
1958/// expressions.
Anders Carlssonf8b30152010-11-28 16:40:49 +00001959static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregor2f599792010-04-02 18:24:57 +00001960 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00001961 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor2f599792010-04-02 18:24:57 +00001962 E = ICE->getSubExpr();
1963 else
1964 break;
1965 }
1966
1967 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
1968 E = BE->getSubExpr();
1969
1970 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00001971 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor2f599792010-04-02 18:24:57 +00001972 E = ICE->getSubExpr();
1973 else
1974 break;
1975 }
Anders Carlssonf8b30152010-11-28 16:40:49 +00001976
1977 return E->IgnoreParens();
Douglas Gregor2f599792010-04-02 18:24:57 +00001978}
1979
John McCall558d2ab2010-09-15 10:14:12 +00001980/// isTemporaryObject - Determines if this expression produces a
1981/// temporary of the given class type.
1982bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
1983 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
1984 return false;
1985
Anders Carlssonf8b30152010-11-28 16:40:49 +00001986 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor2f599792010-04-02 18:24:57 +00001987
John McCall58277b52010-09-15 20:59:13 +00001988 // Temporaries are by definition pr-values of class type.
Fariborz Jahaniandb148be2010-09-27 17:30:38 +00001989 if (!E->Classify(C).isPRValue()) {
1990 // In this context, property reference is a message call and is pr-value.
John McCall12f78a62010-12-02 01:19:52 +00001991 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahaniandb148be2010-09-27 17:30:38 +00001992 return false;
1993 }
Douglas Gregor2f599792010-04-02 18:24:57 +00001994
John McCall19e60ad2010-09-16 06:57:56 +00001995 // Black-list a few cases which yield pr-values of class type that don't
1996 // refer to temporaries of that type:
1997
1998 // - implicit derived-to-base conversions
John McCall558d2ab2010-09-15 10:14:12 +00001999 if (isa<ImplicitCastExpr>(E)) {
2000 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2001 case CK_DerivedToBase:
2002 case CK_UncheckedDerivedToBase:
2003 return false;
2004 default:
2005 break;
2006 }
Douglas Gregor2f599792010-04-02 18:24:57 +00002007 }
2008
John McCall19e60ad2010-09-16 06:57:56 +00002009 // - member expressions (all)
2010 if (isa<MemberExpr>(E))
2011 return false;
2012
John McCall56ca35d2011-02-17 10:25:35 +00002013 // - opaque values (all)
2014 if (isa<OpaqueValueExpr>(E))
2015 return false;
2016
John McCall558d2ab2010-09-15 10:14:12 +00002017 return true;
Douglas Gregor2f599792010-04-02 18:24:57 +00002018}
2019
Douglas Gregor898574e2008-12-05 23:32:09 +00002020/// hasAnyTypeDependentArguments - Determines if any of the expressions
2021/// in Exprs is type-dependent.
2022bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
2023 for (unsigned I = 0; I < NumExprs; ++I)
2024 if (Exprs[I]->isTypeDependent())
2025 return true;
2026
2027 return false;
2028}
2029
2030/// hasAnyValueDependentArguments - Determines if any of the expressions
2031/// in Exprs is value-dependent.
2032bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
2033 for (unsigned I = 0; I < NumExprs; ++I)
2034 if (Exprs[I]->isValueDependent())
2035 return true;
2036
2037 return false;
2038}
2039
John McCall4204f072010-08-02 21:13:48 +00002040bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002041 // This function is attempting whether an expression is an initializer
2042 // which can be evaluated at compile-time. isEvaluatable handles most
2043 // of the cases, but it can't deal with some initializer-specific
2044 // expressions, and it can't deal with aggregates; we deal with those here,
2045 // and fall back to isEvaluatable for the other cases.
2046
John McCall4204f072010-08-02 21:13:48 +00002047 // If we ever capture reference-binding directly in the AST, we can
2048 // kill the second parameter.
2049
2050 if (IsForRef) {
2051 EvalResult Result;
2052 return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
2053 }
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002054
Anders Carlssone8a32b82008-11-24 05:23:59 +00002055 switch (getStmtClass()) {
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002056 default: break;
Anders Carlssone8a32b82008-11-24 05:23:59 +00002057 case StringLiteralClass:
Steve Naroff14108da2009-07-10 23:34:53 +00002058 case ObjCStringLiteralClass:
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002059 case ObjCEncodeExprClass:
Anders Carlssone8a32b82008-11-24 05:23:59 +00002060 return true;
John McCallb4b9b152010-08-01 21:51:45 +00002061 case CXXTemporaryObjectExprClass:
2062 case CXXConstructExprClass: {
2063 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall4204f072010-08-02 21:13:48 +00002064
2065 // Only if it's
2066 // 1) an application of the trivial default constructor or
John McCallb4b9b152010-08-01 21:51:45 +00002067 if (!CE->getConstructor()->isTrivial()) return false;
John McCall4204f072010-08-02 21:13:48 +00002068 if (!CE->getNumArgs()) return true;
2069
2070 // 2) an elidable trivial copy construction of an operand which is
2071 // itself a constant initializer. Note that we consider the
2072 // operand on its own, *not* as a reference binding.
2073 return CE->isElidable() &&
2074 CE->getArg(0)->isConstantInitializer(Ctx, false);
John McCallb4b9b152010-08-01 21:51:45 +00002075 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002076 case CompoundLiteralExprClass: {
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002077 // This handles gcc's extension that allows global initializers like
2078 // "struct x {int x;} x = (struct x) {};".
2079 // FIXME: This accepts other cases it shouldn't!
Nate Begeman59b5da62009-01-18 03:20:47 +00002080 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
John McCall4204f072010-08-02 21:13:48 +00002081 return Exp->isConstantInitializer(Ctx, false);
Nate Begeman59b5da62009-01-18 03:20:47 +00002082 }
Anders Carlssone8a32b82008-11-24 05:23:59 +00002083 case InitListExprClass: {
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002084 // FIXME: This doesn't deal with fields with reference types correctly.
2085 // FIXME: This incorrectly allows pointers cast to integers to be assigned
2086 // to bitfields.
Anders Carlssone8a32b82008-11-24 05:23:59 +00002087 const InitListExpr *Exp = cast<InitListExpr>(this);
2088 unsigned numInits = Exp->getNumInits();
2089 for (unsigned i = 0; i < numInits; i++) {
John McCall4204f072010-08-02 21:13:48 +00002090 if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
Anders Carlssone8a32b82008-11-24 05:23:59 +00002091 return false;
2092 }
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002093 return true;
Anders Carlssone8a32b82008-11-24 05:23:59 +00002094 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00002095 case ImplicitValueInitExprClass:
2096 return true;
Chris Lattner3ae9f482009-10-13 07:14:16 +00002097 case ParenExprClass:
John McCall4204f072010-08-02 21:13:48 +00002098 return cast<ParenExpr>(this)->getSubExpr()
2099 ->isConstantInitializer(Ctx, IsForRef);
Abramo Bagnara5cadfab2010-09-27 07:13:32 +00002100 case ChooseExprClass:
2101 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
2102 ->isConstantInitializer(Ctx, IsForRef);
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002103 case UnaryOperatorClass: {
2104 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCall2de56d12010-08-25 11:45:40 +00002105 if (Exp->getOpcode() == UO_Extension)
John McCall4204f072010-08-02 21:13:48 +00002106 return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002107 break;
2108 }
Chris Lattner3ae9f482009-10-13 07:14:16 +00002109 case BinaryOperatorClass: {
2110 // Special case &&foo - &&bar. It would be nice to generalize this somehow
2111 // but this handles the common case.
2112 const BinaryOperator *Exp = cast<BinaryOperator>(this);
John McCall2de56d12010-08-25 11:45:40 +00002113 if (Exp->getOpcode() == BO_Sub &&
Chris Lattner3ae9f482009-10-13 07:14:16 +00002114 isa<AddrLabelExpr>(Exp->getLHS()->IgnoreParenNoopCasts(Ctx)) &&
2115 isa<AddrLabelExpr>(Exp->getRHS()->IgnoreParenNoopCasts(Ctx)))
2116 return true;
2117 break;
2118 }
John McCall4204f072010-08-02 21:13:48 +00002119 case CXXFunctionalCastExprClass:
John McCallb4b9b152010-08-01 21:51:45 +00002120 case CXXStaticCastExprClass:
Chris Lattner81045d82009-04-21 05:19:11 +00002121 case ImplicitCastExprClass:
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002122 case CStyleCastExprClass:
2123 // Handle casts with a destination that's a struct or union; this
2124 // deals with both the gcc no-op struct cast extension and the
2125 // cast-to-union extension.
2126 if (getType()->isRecordType())
John McCall4204f072010-08-02 21:13:48 +00002127 return cast<CastExpr>(this)->getSubExpr()
2128 ->isConstantInitializer(Ctx, false);
Sean Huntc3021132010-05-05 15:23:54 +00002129
Chris Lattner430656e2009-10-13 22:12:09 +00002130 // Integer->integer casts can be handled here, which is important for
2131 // things like (int)(&&x-&&y). Scary but true.
2132 if (getType()->isIntegerType() &&
2133 cast<CastExpr>(this)->getSubExpr()->getType()->isIntegerType())
John McCall4204f072010-08-02 21:13:48 +00002134 return cast<CastExpr>(this)->getSubExpr()
2135 ->isConstantInitializer(Ctx, false);
Sean Huntc3021132010-05-05 15:23:54 +00002136
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002137 break;
Anders Carlssone8a32b82008-11-24 05:23:59 +00002138 }
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002139 return isEvaluatable(Ctx);
Steve Naroff38374b02007-09-02 20:30:18 +00002140}
2141
Chandler Carruth82214a82011-02-18 23:54:50 +00002142/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
2143/// pointer constant or not, as well as the specific kind of constant detected.
2144/// Null pointer constants can be integer constant expressions with the
2145/// value zero, casts of zero to void*, nullptr (C++0X), or __null
2146/// (a GNU extension).
2147Expr::NullPointerConstantKind
2148Expr::isNullPointerConstant(ASTContext &Ctx,
2149 NullPointerConstantValueDependence NPC) const {
Douglas Gregorce940492009-09-25 04:25:58 +00002150 if (isValueDependent()) {
2151 switch (NPC) {
2152 case NPC_NeverValueDependent:
2153 assert(false && "Unexpected value dependent expression!");
2154 // If the unthinkable happens, fall through to the safest alternative.
Sean Huntc3021132010-05-05 15:23:54 +00002155
Douglas Gregorce940492009-09-25 04:25:58 +00002156 case NPC_ValueDependentIsNull:
Chandler Carruth82214a82011-02-18 23:54:50 +00002157 if (isTypeDependent() || getType()->isIntegralType(Ctx))
2158 return NPCK_ZeroInteger;
2159 else
2160 return NPCK_NotNull;
Sean Huntc3021132010-05-05 15:23:54 +00002161
Douglas Gregorce940492009-09-25 04:25:58 +00002162 case NPC_ValueDependentIsNotNull:
Chandler Carruth82214a82011-02-18 23:54:50 +00002163 return NPCK_NotNull;
Douglas Gregorce940492009-09-25 04:25:58 +00002164 }
2165 }
Daniel Dunbarf515b222009-09-18 08:46:16 +00002166
Sebastian Redl07779722008-10-31 14:43:28 +00002167 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002168 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
Sebastian Redl6215dee2008-11-04 11:45:54 +00002169 if (!Ctx.getLangOptions().CPlusPlus) {
Sebastian Redl07779722008-10-31 14:43:28 +00002170 // Check that it is a cast to void*.
Ted Kremenek6217b802009-07-29 21:53:49 +00002171 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl07779722008-10-31 14:43:28 +00002172 QualType Pointee = PT->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002173 if (!Pointee.hasQualifiers() &&
Sebastian Redl07779722008-10-31 14:43:28 +00002174 Pointee->isVoidType() && // to void*
2175 CE->getSubExpr()->getType()->isIntegerType()) // from int.
Douglas Gregorce940492009-09-25 04:25:58 +00002176 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl07779722008-10-31 14:43:28 +00002177 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002178 }
Steve Naroffaa58f002008-01-14 16:10:57 +00002179 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2180 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregorce940492009-09-25 04:25:58 +00002181 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroffaa58f002008-01-14 16:10:57 +00002182 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2183 // Accept ((void*)0) as a null pointer constant, as many other
2184 // implementations do.
Douglas Gregorce940492009-09-25 04:25:58 +00002185 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump1eb44332009-09-09 15:08:12 +00002186 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner8123a952008-04-10 02:22:51 +00002187 = dyn_cast<CXXDefaultArgExpr>(this)) {
Chris Lattner04421082008-04-08 04:40:51 +00002188 // See through default argument expressions
Douglas Gregorce940492009-09-25 04:25:58 +00002189 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor2d8b2732008-11-29 04:51:27 +00002190 } else if (isa<GNUNullExpr>(this)) {
2191 // The GNU __null extension is always a null pointer constant.
Chandler Carruth82214a82011-02-18 23:54:50 +00002192 return NPCK_GNUNull;
Steve Naroffaaffbf72008-01-14 02:53:34 +00002193 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00002194
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002195 // C++0x nullptr_t is always a null pointer constant.
2196 if (getType()->isNullPtrType())
Chandler Carruth82214a82011-02-18 23:54:50 +00002197 return NPCK_CXX0X_nullptr;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002198
Fariborz Jahanianff3a0782010-09-27 22:42:37 +00002199 if (const RecordType *UT = getType()->getAsUnionType())
2200 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2201 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2202 const Expr *InitExpr = CLE->getInitializer();
2203 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2204 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2205 }
Steve Naroffaa58f002008-01-14 16:10:57 +00002206 // This expression must be an integer type.
Sean Huntc3021132010-05-05 15:23:54 +00002207 if (!getType()->isIntegerType() ||
Fariborz Jahanian56fc0d12009-10-06 00:09:31 +00002208 (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType()))
Chandler Carruth82214a82011-02-18 23:54:50 +00002209 return NPCK_NotNull;
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 // If we have an integer constant expression, we need to *evaluate* it and
2212 // test for the value 0.
Eli Friedman09de1762009-04-25 22:37:12 +00002213 llvm::APSInt Result;
Chandler Carruth82214a82011-02-18 23:54:50 +00002214 bool IsNull = isIntegerConstantExpr(Result, Ctx) && Result == 0;
2215
2216 return (IsNull ? NPCK_ZeroInteger : NPCK_NotNull);
Reid Spencer5f016e22007-07-11 17:01:13 +00002217}
Steve Naroff31a45842007-07-28 23:10:27 +00002218
John McCallf6a16482010-12-04 03:47:34 +00002219/// \brief If this expression is an l-value for an Objective C
2220/// property, find the underlying property reference expression.
2221const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
2222 const Expr *E = this;
2223 while (true) {
2224 assert((E->getValueKind() == VK_LValue &&
2225 E->getObjectKind() == OK_ObjCProperty) &&
2226 "expression is not a property reference");
2227 E = E->IgnoreParenCasts();
2228 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2229 if (BO->getOpcode() == BO_Comma) {
2230 E = BO->getRHS();
2231 continue;
2232 }
2233 }
2234
2235 break;
2236 }
2237
2238 return cast<ObjCPropertyRefExpr>(E);
2239}
2240
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002241FieldDecl *Expr::getBitField() {
Douglas Gregor6f4a69a2009-07-06 15:38:40 +00002242 Expr *E = this->IgnoreParens();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002243
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002244 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCallf6a16482010-12-04 03:47:34 +00002245 if (ICE->getCastKind() == CK_LValueToRValue ||
2246 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002247 E = ICE->getSubExpr()->IgnoreParens();
2248 else
2249 break;
2250 }
2251
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002252 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor86f19402008-12-20 23:49:58 +00002253 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002254 if (Field->isBitField())
2255 return Field;
2256
Argyrios Kyrtzidis0f279e72010-10-30 19:52:22 +00002257 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
2258 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
2259 if (Field->isBitField())
2260 return Field;
2261
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002262 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E))
2263 if (BinOp->isAssignmentOp() && BinOp->getLHS())
2264 return BinOp->getLHS()->getBitField();
2265
2266 return 0;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002267}
2268
Anders Carlsson09380262010-01-31 17:18:49 +00002269bool Expr::refersToVectorElement() const {
2270 const Expr *E = this->IgnoreParens();
Sean Huntc3021132010-05-05 15:23:54 +00002271
Anders Carlsson09380262010-01-31 17:18:49 +00002272 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall5baba9d2010-08-25 10:28:54 +00002273 if (ICE->getValueKind() != VK_RValue &&
John McCall2de56d12010-08-25 11:45:40 +00002274 ICE->getCastKind() == CK_NoOp)
Anders Carlsson09380262010-01-31 17:18:49 +00002275 E = ICE->getSubExpr()->IgnoreParens();
2276 else
2277 break;
2278 }
Sean Huntc3021132010-05-05 15:23:54 +00002279
Anders Carlsson09380262010-01-31 17:18:49 +00002280 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
2281 return ASE->getBase()->getType()->isVectorType();
2282
2283 if (isa<ExtVectorElementExpr>(E))
2284 return true;
2285
2286 return false;
2287}
2288
Chris Lattner2140e902009-02-16 22:14:05 +00002289/// isArrow - Return true if the base expression is a pointer to vector,
2290/// return false if the base expression is a vector.
2291bool ExtVectorElementExpr::isArrow() const {
2292 return getBase()->getType()->isPointerType();
2293}
2294
Nate Begeman213541a2008-04-18 23:10:10 +00002295unsigned ExtVectorElementExpr::getNumElements() const {
John McCall183700f2009-09-21 23:43:11 +00002296 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begeman8a997642008-05-09 06:41:27 +00002297 return VT->getNumElements();
2298 return 1;
Chris Lattner4d0ac882007-08-03 16:00:20 +00002299}
2300
Nate Begeman8a997642008-05-09 06:41:27 +00002301/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begeman213541a2008-04-18 23:10:10 +00002302bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbara2b34eb2009-10-18 02:09:09 +00002303 // FIXME: Refactor this code to an accessor on the AST node which returns the
2304 // "type" of component access, and share with code below and in Sema.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002305 llvm::StringRef Comp = Accessor->getName();
Nate Begeman190d6a22009-01-18 02:01:21 +00002306
2307 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar15027422009-10-17 23:53:04 +00002308 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman190d6a22009-01-18 02:01:21 +00002309 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Nate Begeman190d6a22009-01-18 02:01:21 +00002311 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar15027422009-10-17 23:53:04 +00002312 if (Comp[0] == 's' || Comp[0] == 'S')
2313 Comp = Comp.substr(1);
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Daniel Dunbar15027422009-10-17 23:53:04 +00002315 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
2316 if (Comp.substr(i + 1).find(Comp[i]) != llvm::StringRef::npos)
Steve Narofffec0b492007-07-30 03:29:09 +00002317 return true;
Daniel Dunbar15027422009-10-17 23:53:04 +00002318
Steve Narofffec0b492007-07-30 03:29:09 +00002319 return false;
2320}
Chris Lattnerb8f849d2007-08-02 23:36:59 +00002321
Nate Begeman8a997642008-05-09 06:41:27 +00002322/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begeman3b8d1162008-05-13 21:03:02 +00002323void ExtVectorElementExpr::getEncodedElementAccess(
2324 llvm::SmallVectorImpl<unsigned> &Elts) const {
Daniel Dunbar4b55b242009-10-18 02:09:31 +00002325 llvm::StringRef Comp = Accessor->getName();
2326 if (Comp[0] == 's' || Comp[0] == 'S')
2327 Comp = Comp.substr(1);
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Daniel Dunbar4b55b242009-10-18 02:09:31 +00002329 bool isHi = Comp == "hi";
2330 bool isLo = Comp == "lo";
2331 bool isEven = Comp == "even";
2332 bool isOdd = Comp == "odd";
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Nate Begeman8a997642008-05-09 06:41:27 +00002334 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2335 uint64_t Index;
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Nate Begeman8a997642008-05-09 06:41:27 +00002337 if (isHi)
2338 Index = e + i;
2339 else if (isLo)
2340 Index = i;
2341 else if (isEven)
2342 Index = 2 * i;
2343 else if (isOdd)
2344 Index = 2 * i + 1;
2345 else
Daniel Dunbar4b55b242009-10-18 02:09:31 +00002346 Index = ExtVectorType::getAccessorIdx(Comp[i]);
Chris Lattnerb8f849d2007-08-02 23:36:59 +00002347
Nate Begeman3b8d1162008-05-13 21:03:02 +00002348 Elts.push_back(Index);
Chris Lattnerb8f849d2007-08-02 23:36:59 +00002349 }
Nate Begeman8a997642008-05-09 06:41:27 +00002350}
2351
Douglas Gregor04badcf2010-04-21 00:45:42 +00002352ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002353 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002354 SourceLocation LBracLoc,
2355 SourceLocation SuperLoc,
2356 bool IsInstanceSuper,
2357 QualType SuperType,
Sean Huntc3021132010-05-05 15:23:54 +00002358 Selector Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002359 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002360 ObjCMethodDecl *Method,
2361 Expr **Args, unsigned NumArgs,
2362 SourceLocation RBracLoc)
John McCallf89e55a2010-11-18 06:31:45 +00002363 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002364 /*TypeDependent=*/false, /*ValueDependent=*/false,
2365 /*ContainsUnexpandedParameterPack=*/false),
Douglas Gregor04badcf2010-04-21 00:45:42 +00002366 NumArgs(NumArgs), Kind(IsInstanceSuper? SuperInstance : SuperClass),
2367 HasMethod(Method != 0), SuperLoc(SuperLoc),
2368 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2369 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002370 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregorc2350e52010-03-08 16:40:19 +00002371{
Douglas Gregor04badcf2010-04-21 00:45:42 +00002372 setReceiverPointer(SuperType.getAsOpaquePtr());
2373 if (NumArgs)
2374 memcpy(getArgs(), Args, NumArgs * sizeof(Expr *));
Ted Kremenek4df728e2008-06-24 15:50:53 +00002375}
2376
Douglas Gregor04badcf2010-04-21 00:45:42 +00002377ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002378 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002379 SourceLocation LBracLoc,
2380 TypeSourceInfo *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002381 Selector Sel,
2382 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002383 ObjCMethodDecl *Method,
2384 Expr **Args, unsigned NumArgs,
2385 SourceLocation RBracLoc)
John McCallf89e55a2010-11-18 06:31:45 +00002386 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002387 T->isDependentType(), T->containsUnexpandedParameterPack()),
Douglas Gregor04badcf2010-04-21 00:45:42 +00002388 NumArgs(NumArgs), Kind(Class), HasMethod(Method != 0),
2389 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2390 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002391 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregor04badcf2010-04-21 00:45:42 +00002392{
2393 setReceiverPointer(Receiver);
Douglas Gregoraa165f82011-01-03 19:04:46 +00002394 Expr **MyArgs = getArgs();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002395 for (unsigned I = 0; I != NumArgs; ++I) {
2396 if (Args[I]->isTypeDependent())
2397 ExprBits.TypeDependent = true;
2398 if (Args[I]->isValueDependent())
2399 ExprBits.ValueDependent = true;
2400 if (Args[I]->containsUnexpandedParameterPack())
2401 ExprBits.ContainsUnexpandedParameterPack = true;
2402
2403 MyArgs[I] = Args[I];
2404 }
Ted Kremenek4df728e2008-06-24 15:50:53 +00002405}
2406
Douglas Gregor04badcf2010-04-21 00:45:42 +00002407ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002408 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002409 SourceLocation LBracLoc,
2410 Expr *Receiver,
Sean Huntc3021132010-05-05 15:23:54 +00002411 Selector Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002412 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002413 ObjCMethodDecl *Method,
2414 Expr **Args, unsigned NumArgs,
2415 SourceLocation RBracLoc)
John McCallf89e55a2010-11-18 06:31:45 +00002416 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002417 Receiver->isTypeDependent(),
2418 Receiver->containsUnexpandedParameterPack()),
Douglas Gregor04badcf2010-04-21 00:45:42 +00002419 NumArgs(NumArgs), Kind(Instance), HasMethod(Method != 0),
2420 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2421 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002422 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregor04badcf2010-04-21 00:45:42 +00002423{
2424 setReceiverPointer(Receiver);
Douglas Gregoraa165f82011-01-03 19:04:46 +00002425 Expr **MyArgs = getArgs();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002426 for (unsigned I = 0; I != NumArgs; ++I) {
2427 if (Args[I]->isTypeDependent())
2428 ExprBits.TypeDependent = true;
2429 if (Args[I]->isValueDependent())
2430 ExprBits.ValueDependent = true;
2431 if (Args[I]->containsUnexpandedParameterPack())
2432 ExprBits.ContainsUnexpandedParameterPack = true;
2433
2434 MyArgs[I] = Args[I];
2435 }
Chris Lattner0389e6b2009-04-26 00:44:05 +00002436}
2437
Douglas Gregor04badcf2010-04-21 00:45:42 +00002438ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002439 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002440 SourceLocation LBracLoc,
2441 SourceLocation SuperLoc,
2442 bool IsInstanceSuper,
2443 QualType SuperType,
Sean Huntc3021132010-05-05 15:23:54 +00002444 Selector Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002445 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002446 ObjCMethodDecl *Method,
2447 Expr **Args, unsigned NumArgs,
2448 SourceLocation RBracLoc) {
Sean Huntc3021132010-05-05 15:23:54 +00002449 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
Douglas Gregor04badcf2010-04-21 00:45:42 +00002450 NumArgs * sizeof(Expr *);
2451 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
John McCallf89e55a2010-11-18 06:31:45 +00002452 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002453 SuperType, Sel, SelLoc, Method, Args,NumArgs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002454 RBracLoc);
2455}
2456
2457ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002458 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002459 SourceLocation LBracLoc,
2460 TypeSourceInfo *Receiver,
Sean Huntc3021132010-05-05 15:23:54 +00002461 Selector Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002462 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002463 ObjCMethodDecl *Method,
2464 Expr **Args, unsigned NumArgs,
2465 SourceLocation RBracLoc) {
Sean Huntc3021132010-05-05 15:23:54 +00002466 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
Douglas Gregor04badcf2010-04-21 00:45:42 +00002467 NumArgs * sizeof(Expr *);
2468 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002469 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2470 Method, Args, NumArgs, RBracLoc);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002471}
2472
2473ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002474 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002475 SourceLocation LBracLoc,
2476 Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002477 Selector Sel,
2478 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002479 ObjCMethodDecl *Method,
2480 Expr **Args, unsigned NumArgs,
2481 SourceLocation RBracLoc) {
Sean Huntc3021132010-05-05 15:23:54 +00002482 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
Douglas Gregor04badcf2010-04-21 00:45:42 +00002483 NumArgs * sizeof(Expr *);
2484 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002485 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2486 Method, Args, NumArgs, RBracLoc);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002487}
2488
Sean Huntc3021132010-05-05 15:23:54 +00002489ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002490 unsigned NumArgs) {
Sean Huntc3021132010-05-05 15:23:54 +00002491 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
Douglas Gregor04badcf2010-04-21 00:45:42 +00002492 NumArgs * sizeof(Expr *);
2493 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2494 return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
2495}
Argyrios Kyrtzidise005d192010-12-10 20:08:30 +00002496
2497SourceRange ObjCMessageExpr::getReceiverRange() const {
2498 switch (getReceiverKind()) {
2499 case Instance:
2500 return getInstanceReceiver()->getSourceRange();
2501
2502 case Class:
2503 return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
2504
2505 case SuperInstance:
2506 case SuperClass:
2507 return getSuperLoc();
2508 }
2509
2510 return SourceLocation();
2511}
2512
Douglas Gregor04badcf2010-04-21 00:45:42 +00002513Selector ObjCMessageExpr::getSelector() const {
2514 if (HasMethod)
2515 return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
2516 ->getSelector();
Sean Huntc3021132010-05-05 15:23:54 +00002517 return Selector(SelectorOrMethod);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002518}
2519
2520ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
2521 switch (getReceiverKind()) {
2522 case Instance:
2523 if (const ObjCObjectPointerType *Ptr
2524 = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
2525 return Ptr->getInterfaceDecl();
2526 break;
2527
2528 case Class:
John McCallc12c5bb2010-05-15 11:32:37 +00002529 if (const ObjCObjectType *Ty
2530 = getClassReceiver()->getAs<ObjCObjectType>())
2531 return Ty->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002532 break;
2533
2534 case SuperInstance:
2535 if (const ObjCObjectPointerType *Ptr
2536 = getSuperType()->getAs<ObjCObjectPointerType>())
2537 return Ptr->getInterfaceDecl();
2538 break;
2539
2540 case SuperClass:
Argyrios Kyrtzidisee8a6ca2011-01-25 00:03:48 +00002541 if (const ObjCObjectType *Iface
2542 = getSuperType()->getAs<ObjCObjectType>())
2543 return Iface->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002544 break;
2545 }
2546
2547 return 0;
Ted Kremenekeb3b3242010-02-11 22:41:21 +00002548}
Chris Lattner0389e6b2009-04-26 00:44:05 +00002549
Jay Foad4ba2a172011-01-12 09:06:06 +00002550bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
Eli Friedman9a901bb2009-04-26 19:19:15 +00002551 return getCond()->EvaluateAsInt(C) != 0;
Chris Lattner27437ca2007-10-25 00:29:32 +00002552}
2553
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002554ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2555 QualType Type, SourceLocation BLoc,
2556 SourceLocation RP)
2557 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
2558 Type->isDependentType(), Type->isDependentType(),
2559 Type->containsUnexpandedParameterPack()),
2560 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr)
2561{
2562 SubExprs = new (C) Stmt*[nexpr];
2563 for (unsigned i = 0; i < nexpr; i++) {
2564 if (args[i]->isTypeDependent())
2565 ExprBits.TypeDependent = true;
2566 if (args[i]->isValueDependent())
2567 ExprBits.ValueDependent = true;
2568 if (args[i]->containsUnexpandedParameterPack())
2569 ExprBits.ContainsUnexpandedParameterPack = true;
2570
2571 SubExprs[i] = args[i];
2572 }
2573}
2574
Nate Begeman888376a2009-08-12 02:28:50 +00002575void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
2576 unsigned NumExprs) {
2577 if (SubExprs) C.Deallocate(SubExprs);
2578
2579 SubExprs = new (C) Stmt* [NumExprs];
Douglas Gregor94cd5d12009-04-16 00:01:45 +00002580 this->NumExprs = NumExprs;
2581 memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
Mike Stump1eb44332009-09-09 15:08:12 +00002582}
Nate Begeman888376a2009-08-12 02:28:50 +00002583
Ted Kremenek77ed8e42007-08-24 18:13:47 +00002584//===----------------------------------------------------------------------===//
Douglas Gregor05c13a32009-01-22 00:58:24 +00002585// DesignatedInitExpr
2586//===----------------------------------------------------------------------===//
2587
2588IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() {
2589 assert(Kind == FieldDesignator && "Only valid on a field designator");
2590 if (Field.NameOrField & 0x01)
2591 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
2592 else
2593 return getField()->getIdentifier();
2594}
2595
Sean Huntc3021132010-05-05 15:23:54 +00002596DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
Douglas Gregor319d57f2010-01-06 23:17:19 +00002597 unsigned NumDesignators,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002598 const Designator *Designators,
Mike Stump1eb44332009-09-09 15:08:12 +00002599 SourceLocation EqualOrColonLoc,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002600 bool GNUSyntax,
Mike Stump1eb44332009-09-09 15:08:12 +00002601 Expr **IndexExprs,
Douglas Gregor9ea62762009-05-21 23:17:49 +00002602 unsigned NumIndexExprs,
2603 Expr *Init)
Mike Stump1eb44332009-09-09 15:08:12 +00002604 : Expr(DesignatedInitExprClass, Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002605 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002606 Init->isTypeDependent(), Init->isValueDependent(),
2607 Init->containsUnexpandedParameterPack()),
Mike Stump1eb44332009-09-09 15:08:12 +00002608 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
2609 NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
Douglas Gregor319d57f2010-01-06 23:17:19 +00002610 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregor9ea62762009-05-21 23:17:49 +00002611
2612 // Record the initializer itself.
John McCall7502c1d2011-02-13 04:07:26 +00002613 child_range Child = children();
Douglas Gregor9ea62762009-05-21 23:17:49 +00002614 *Child++ = Init;
2615
2616 // Copy the designators and their subexpressions, computing
2617 // value-dependence along the way.
2618 unsigned IndexIdx = 0;
2619 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002620 this->Designators[I] = Designators[I];
Douglas Gregor9ea62762009-05-21 23:17:49 +00002621
2622 if (this->Designators[I].isArrayDesignator()) {
2623 // Compute type- and value-dependence.
2624 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002625 if (Index->isTypeDependent() || Index->isValueDependent())
2626 ExprBits.ValueDependent = true;
2627
2628 // Propagate unexpanded parameter packs.
2629 if (Index->containsUnexpandedParameterPack())
2630 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002631
2632 // Copy the index expressions into permanent storage.
2633 *Child++ = IndexExprs[IndexIdx++];
2634 } else if (this->Designators[I].isArrayRangeDesignator()) {
2635 // Compute type- and value-dependence.
2636 Expr *Start = IndexExprs[IndexIdx];
2637 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002638 if (Start->isTypeDependent() || Start->isValueDependent() ||
2639 End->isTypeDependent() || End->isValueDependent())
2640 ExprBits.ValueDependent = true;
2641
2642 // Propagate unexpanded parameter packs.
2643 if (Start->containsUnexpandedParameterPack() ||
2644 End->containsUnexpandedParameterPack())
2645 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002646
2647 // Copy the start/end expressions into permanent storage.
2648 *Child++ = IndexExprs[IndexIdx++];
2649 *Child++ = IndexExprs[IndexIdx++];
2650 }
2651 }
2652
2653 assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002654}
2655
Douglas Gregor05c13a32009-01-22 00:58:24 +00002656DesignatedInitExpr *
Mike Stump1eb44332009-09-09 15:08:12 +00002657DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
Douglas Gregor05c13a32009-01-22 00:58:24 +00002658 unsigned NumDesignators,
2659 Expr **IndexExprs, unsigned NumIndexExprs,
2660 SourceLocation ColonOrEqualLoc,
2661 bool UsesColonSyntax, Expr *Init) {
Steve Naroffc0ac4922009-01-27 23:20:32 +00002662 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
Steve Naroffc0ac4922009-01-27 23:20:32 +00002663 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
Douglas Gregor319d57f2010-01-06 23:17:19 +00002664 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
Douglas Gregor9ea62762009-05-21 23:17:49 +00002665 ColonOrEqualLoc, UsesColonSyntax,
2666 IndexExprs, NumIndexExprs, Init);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002667}
2668
Mike Stump1eb44332009-09-09 15:08:12 +00002669DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
Douglas Gregord077d752009-04-16 00:55:48 +00002670 unsigned NumIndexExprs) {
2671 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
2672 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
2673 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
2674}
2675
Douglas Gregor319d57f2010-01-06 23:17:19 +00002676void DesignatedInitExpr::setDesignators(ASTContext &C,
2677 const Designator *Desigs,
Douglas Gregord077d752009-04-16 00:55:48 +00002678 unsigned NumDesigs) {
Douglas Gregor319d57f2010-01-06 23:17:19 +00002679 Designators = new (C) Designator[NumDesigs];
Douglas Gregord077d752009-04-16 00:55:48 +00002680 NumDesignators = NumDesigs;
2681 for (unsigned I = 0; I != NumDesigs; ++I)
2682 Designators[I] = Desigs[I];
2683}
2684
Douglas Gregor05c13a32009-01-22 00:58:24 +00002685SourceRange DesignatedInitExpr::getSourceRange() const {
2686 SourceLocation StartLoc;
Chris Lattnerd603eaa2009-02-16 22:33:34 +00002687 Designator &First =
2688 *const_cast<DesignatedInitExpr*>(this)->designators_begin();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002689 if (First.isFieldDesignator()) {
Douglas Gregoreeae8f02009-03-28 00:41:23 +00002690 if (GNUSyntax)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002691 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
2692 else
2693 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
2694 } else
Chris Lattnerd603eaa2009-02-16 22:33:34 +00002695 StartLoc =
2696 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002697 return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
2698}
2699
Douglas Gregor05c13a32009-01-22 00:58:24 +00002700Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
2701 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
2702 char* Ptr = static_cast<char*>(static_cast<void *>(this));
2703 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002704 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2705 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2706}
2707
2708Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
Mike Stump1eb44332009-09-09 15:08:12 +00002709 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregor05c13a32009-01-22 00:58:24 +00002710 "Requires array range designator");
2711 char* Ptr = static_cast<char*>(static_cast<void *>(this));
2712 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002713 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2714 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2715}
2716
2717Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
Mike Stump1eb44332009-09-09 15:08:12 +00002718 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregor05c13a32009-01-22 00:58:24 +00002719 "Requires array range designator");
2720 char* Ptr = static_cast<char*>(static_cast<void *>(this));
2721 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002722 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2723 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
2724}
2725
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002726/// \brief Replaces the designator at index @p Idx with the series
2727/// of designators in [First, Last).
Douglas Gregor319d57f2010-01-06 23:17:19 +00002728void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
Mike Stump1eb44332009-09-09 15:08:12 +00002729 const Designator *First,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002730 const Designator *Last) {
2731 unsigned NumNewDesignators = Last - First;
2732 if (NumNewDesignators == 0) {
2733 std::copy_backward(Designators + Idx + 1,
2734 Designators + NumDesignators,
2735 Designators + Idx);
2736 --NumNewDesignators;
2737 return;
2738 } else if (NumNewDesignators == 1) {
2739 Designators[Idx] = *First;
2740 return;
2741 }
2742
Mike Stump1eb44332009-09-09 15:08:12 +00002743 Designator *NewDesignators
Douglas Gregor319d57f2010-01-06 23:17:19 +00002744 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002745 std::copy(Designators, Designators + Idx, NewDesignators);
2746 std::copy(First, Last, NewDesignators + Idx);
2747 std::copy(Designators + Idx + 1, Designators + NumDesignators,
2748 NewDesignators + Idx + NumNewDesignators);
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002749 Designators = NewDesignators;
2750 NumDesignators = NumDesignators - 1 + NumNewDesignators;
2751}
2752
Mike Stump1eb44332009-09-09 15:08:12 +00002753ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00002754 Expr **exprs, unsigned nexprs,
2755 SourceLocation rparenloc)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002756 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
2757 false, false, false),
2758 NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Nate Begeman2ef13e52009-08-10 23:49:36 +00002760 Exprs = new (C) Stmt*[nexprs];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002761 for (unsigned i = 0; i != nexprs; ++i) {
2762 if (exprs[i]->isTypeDependent())
2763 ExprBits.TypeDependent = true;
2764 if (exprs[i]->isValueDependent())
2765 ExprBits.ValueDependent = true;
2766 if (exprs[i]->containsUnexpandedParameterPack())
2767 ExprBits.ContainsUnexpandedParameterPack = true;
2768
Nate Begeman2ef13e52009-08-10 23:49:36 +00002769 Exprs[i] = exprs[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002770 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00002771}
2772
John McCalle996ffd2011-02-16 08:02:54 +00002773const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
2774 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
2775 e = ewc->getSubExpr();
2776 e = cast<CXXConstructExpr>(e)->getArg(0);
2777 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2778 e = ice->getSubExpr();
2779 return cast<OpaqueValueExpr>(e);
2780}
2781
Douglas Gregor05c13a32009-01-22 00:58:24 +00002782//===----------------------------------------------------------------------===//
Ted Kremenekce2fc3a2008-10-27 18:40:21 +00002783// ExprIterator.
2784//===----------------------------------------------------------------------===//
2785
2786Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
2787Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
2788Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
2789const Expr* ConstExprIterator::operator[](size_t idx) const {
2790 return cast<Expr>(I[idx]);
2791}
2792const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
2793const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
2794
2795//===----------------------------------------------------------------------===//
Ted Kremenek77ed8e42007-08-24 18:13:47 +00002796// Child Iterators for iterating over subexpressions/substatements
2797//===----------------------------------------------------------------------===//
2798
Sebastian Redl05189992008-11-11 17:56:53 +00002799// SizeOfAlignOfExpr
John McCall63c00d72011-02-09 08:16:59 +00002800Stmt::child_range SizeOfAlignOfExpr::children() {
Sebastian Redl05189992008-11-11 17:56:53 +00002801 // If this is of a type and the type is a VLA type (and not a typedef), the
2802 // size expression of the VLA needs to be treated as an executable expression.
2803 // Why isn't this weirdness documented better in StmtIterator?
2804 if (isArgumentType()) {
John McCallf4c73712011-01-19 06:33:43 +00002805 if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
Sebastian Redl05189992008-11-11 17:56:53 +00002806 getArgumentType().getTypePtr()))
John McCall63c00d72011-02-09 08:16:59 +00002807 return child_range(child_iterator(T), child_iterator());
2808 return child_range();
Sebastian Redl05189992008-11-11 17:56:53 +00002809 }
John McCall63c00d72011-02-09 08:16:59 +00002810 return child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek9ac59282007-10-18 23:28:49 +00002811}
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002812
Steve Naroff563477d2007-09-18 23:55:05 +00002813// ObjCMessageExpr
John McCall63c00d72011-02-09 08:16:59 +00002814Stmt::child_range ObjCMessageExpr::children() {
2815 Stmt **begin;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002816 if (getReceiverKind() == Instance)
John McCall63c00d72011-02-09 08:16:59 +00002817 begin = reinterpret_cast<Stmt **>(this + 1);
2818 else
2819 begin = reinterpret_cast<Stmt **>(getArgs());
2820 return child_range(begin,
2821 reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
Steve Naroff563477d2007-09-18 23:55:05 +00002822}
2823
Steve Naroff4eb206b2008-09-03 18:15:37 +00002824// Blocks
John McCall6b5a61b2011-02-07 10:33:21 +00002825BlockDeclRefExpr::BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
Douglas Gregora779d9c2011-01-19 21:32:01 +00002826 SourceLocation l, bool ByRef,
John McCall6b5a61b2011-02-07 10:33:21 +00002827 bool constAdded)
Douglas Gregord967e312011-01-19 21:52:31 +00002828 : Expr(BlockDeclRefExprClass, t, VK, OK_Ordinary, false, false,
Douglas Gregora779d9c2011-01-19 21:32:01 +00002829 d->isParameterPack()),
John McCall6b5a61b2011-02-07 10:33:21 +00002830 D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded)
Douglas Gregora779d9c2011-01-19 21:32:01 +00002831{
Douglas Gregord967e312011-01-19 21:52:31 +00002832 bool TypeDependent = false;
2833 bool ValueDependent = false;
2834 computeDeclRefDependence(D, getType(), TypeDependent, ValueDependent);
2835 ExprBits.TypeDependent = TypeDependent;
2836 ExprBits.ValueDependent = ValueDependent;
Douglas Gregora779d9c2011-01-19 21:32:01 +00002837}
2838