1 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Expr class and subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/AST/Expr.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Lex/LiteralSupport.h"
25 #include "clang/Lex/Lexer.h"
26 #include "clang/Sema/SemaDiagnostic.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <cstring>
34 using namespace clang;
35
getBestDynamicClassType() const36 const CXXRecordDecl *Expr::getBestDynamicClassType() const {
37 const Expr *E = ignoreParenBaseCasts();
38
39 QualType DerivedType = E->getType();
40 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
41 DerivedType = PTy->getPointeeType();
42
43 if (DerivedType->isDependentType())
44 return NULL;
45
46 const RecordType *Ty = DerivedType->castAs<RecordType>();
47 Decl *D = Ty->getDecl();
48 return cast<CXXRecordDecl>(D);
49 }
50
51 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
52 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
53 /// but also int expressions which are produced by things like comparisons in
54 /// C.
isKnownToHaveBooleanValue() const55 bool Expr::isKnownToHaveBooleanValue() const {
56 const Expr *E = IgnoreParens();
57
58 // If this value has _Bool type, it is obvious 0/1.
59 if (E->getType()->isBooleanType()) return true;
60 // If this is a non-scalar-integer type, we don't care enough to try.
61 if (!E->getType()->isIntegralOrEnumerationType()) return false;
62
63 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
64 switch (UO->getOpcode()) {
65 case UO_Plus:
66 return UO->getSubExpr()->isKnownToHaveBooleanValue();
67 default:
68 return false;
69 }
70 }
71
72 // Only look through implicit casts. If the user writes
73 // '(int) (a && b)' treat it as an arbitrary int.
74 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
75 return CE->getSubExpr()->isKnownToHaveBooleanValue();
76
77 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
78 switch (BO->getOpcode()) {
79 default: return false;
80 case BO_LT: // Relational operators.
81 case BO_GT:
82 case BO_LE:
83 case BO_GE:
84 case BO_EQ: // Equality operators.
85 case BO_NE:
86 case BO_LAnd: // AND operator.
87 case BO_LOr: // Logical OR operator.
88 return true;
89
90 case BO_And: // Bitwise AND operator.
91 case BO_Xor: // Bitwise XOR operator.
92 case BO_Or: // Bitwise OR operator.
93 // Handle things like (x==2)|(y==12).
94 return BO->getLHS()->isKnownToHaveBooleanValue() &&
95 BO->getRHS()->isKnownToHaveBooleanValue();
96
97 case BO_Comma:
98 case BO_Assign:
99 return BO->getRHS()->isKnownToHaveBooleanValue();
100 }
101 }
102
103 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
104 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
105 CO->getFalseExpr()->isKnownToHaveBooleanValue();
106
107 return false;
108 }
109
110 // Amusing macro metaprogramming hack: check whether a class provides
111 // a more specific implementation of getExprLoc().
112 //
113 // See also Stmt.cpp:{getLocStart(),getLocEnd()}.
114 namespace {
115 /// This implementation is used when a class provides a custom
116 /// implementation of getExprLoc.
117 template <class E, class T>
getExprLocImpl(const Expr * expr,SourceLocation (T::* v)()const)118 SourceLocation getExprLocImpl(const Expr *expr,
119 SourceLocation (T::*v)() const) {
120 return static_cast<const E*>(expr)->getExprLoc();
121 }
122
123 /// This implementation is used when a class doesn't provide
124 /// a custom implementation of getExprLoc. Overload resolution
125 /// should pick it over the implementation above because it's
126 /// more specialized according to function template partial ordering.
127 template <class E>
getExprLocImpl(const Expr * expr,SourceLocation (Expr::* v)()const)128 SourceLocation getExprLocImpl(const Expr *expr,
129 SourceLocation (Expr::*v)() const) {
130 return static_cast<const E*>(expr)->getLocStart();
131 }
132 }
133
getExprLoc() const134 SourceLocation Expr::getExprLoc() const {
135 switch (getStmtClass()) {
136 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
137 #define ABSTRACT_STMT(type)
138 #define STMT(type, base) \
139 case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break;
140 #define EXPR(type, base) \
141 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
142 #include "clang/AST/StmtNodes.inc"
143 }
144 llvm_unreachable("unknown statement kind");
145 }
146
147 //===----------------------------------------------------------------------===//
148 // Primary Expressions.
149 //===----------------------------------------------------------------------===//
150
151 /// \brief Compute the type-, value-, and instantiation-dependence of a
152 /// declaration reference
153 /// based on the declaration being referenced.
computeDeclRefDependence(ASTContext & Ctx,NamedDecl * D,QualType T,bool & TypeDependent,bool & ValueDependent,bool & InstantiationDependent)154 static void computeDeclRefDependence(ASTContext &Ctx, NamedDecl *D, QualType T,
155 bool &TypeDependent,
156 bool &ValueDependent,
157 bool &InstantiationDependent) {
158 TypeDependent = false;
159 ValueDependent = false;
160 InstantiationDependent = false;
161
162 // (TD) C++ [temp.dep.expr]p3:
163 // An id-expression is type-dependent if it contains:
164 //
165 // and
166 //
167 // (VD) C++ [temp.dep.constexpr]p2:
168 // An identifier is value-dependent if it is:
169
170 // (TD) - an identifier that was declared with dependent type
171 // (VD) - a name declared with a dependent type,
172 if (T->isDependentType()) {
173 TypeDependent = true;
174 ValueDependent = true;
175 InstantiationDependent = true;
176 return;
177 } else if (T->isInstantiationDependentType()) {
178 InstantiationDependent = true;
179 }
180
181 // (TD) - a conversion-function-id that specifies a dependent type
182 if (D->getDeclName().getNameKind()
183 == DeclarationName::CXXConversionFunctionName) {
184 QualType T = D->getDeclName().getCXXNameType();
185 if (T->isDependentType()) {
186 TypeDependent = true;
187 ValueDependent = true;
188 InstantiationDependent = true;
189 return;
190 }
191
192 if (T->isInstantiationDependentType())
193 InstantiationDependent = true;
194 }
195
196 // (VD) - the name of a non-type template parameter,
197 if (isa<NonTypeTemplateParmDecl>(D)) {
198 ValueDependent = true;
199 InstantiationDependent = true;
200 return;
201 }
202
203 // (VD) - a constant with integral or enumeration type and is
204 // initialized with an expression that is value-dependent.
205 // (VD) - a constant with literal type and is initialized with an
206 // expression that is value-dependent [C++11].
207 // (VD) - FIXME: Missing from the standard:
208 // - an entity with reference type and is initialized with an
209 // expression that is value-dependent [C++11]
210 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
211 if ((Ctx.getLangOpts().CPlusPlus0x ?
212 Var->getType()->isLiteralType() :
213 Var->getType()->isIntegralOrEnumerationType()) &&
214 (Var->getType().isConstQualified() ||
215 Var->getType()->isReferenceType())) {
216 if (const Expr *Init = Var->getAnyInitializer())
217 if (Init->isValueDependent()) {
218 ValueDependent = true;
219 InstantiationDependent = true;
220 }
221 }
222
223 // (VD) - FIXME: Missing from the standard:
224 // - a member function or a static data member of the current
225 // instantiation
226 if (Var->isStaticDataMember() &&
227 Var->getDeclContext()->isDependentContext()) {
228 ValueDependent = true;
229 InstantiationDependent = true;
230 }
231
232 return;
233 }
234
235 // (VD) - FIXME: Missing from the standard:
236 // - a member function or a static data member of the current
237 // instantiation
238 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
239 ValueDependent = true;
240 InstantiationDependent = true;
241 }
242 }
243
computeDependence(ASTContext & Ctx)244 void DeclRefExpr::computeDependence(ASTContext &Ctx) {
245 bool TypeDependent = false;
246 bool ValueDependent = false;
247 bool InstantiationDependent = false;
248 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
249 ValueDependent, InstantiationDependent);
250
251 // (TD) C++ [temp.dep.expr]p3:
252 // An id-expression is type-dependent if it contains:
253 //
254 // and
255 //
256 // (VD) C++ [temp.dep.constexpr]p2:
257 // An identifier is value-dependent if it is:
258 if (!TypeDependent && !ValueDependent &&
259 hasExplicitTemplateArgs() &&
260 TemplateSpecializationType::anyDependentTemplateArguments(
261 getTemplateArgs(),
262 getNumTemplateArgs(),
263 InstantiationDependent)) {
264 TypeDependent = true;
265 ValueDependent = true;
266 InstantiationDependent = true;
267 }
268
269 ExprBits.TypeDependent = TypeDependent;
270 ExprBits.ValueDependent = ValueDependent;
271 ExprBits.InstantiationDependent = InstantiationDependent;
272
273 // Is the declaration a parameter pack?
274 if (getDecl()->isParameterPack())
275 ExprBits.ContainsUnexpandedParameterPack = true;
276 }
277
DeclRefExpr(ASTContext & Ctx,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * D,bool RefersToEnclosingLocal,const DeclarationNameInfo & NameInfo,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs,QualType T,ExprValueKind VK)278 DeclRefExpr::DeclRefExpr(ASTContext &Ctx,
279 NestedNameSpecifierLoc QualifierLoc,
280 SourceLocation TemplateKWLoc,
281 ValueDecl *D, bool RefersToEnclosingLocal,
282 const DeclarationNameInfo &NameInfo,
283 NamedDecl *FoundD,
284 const TemplateArgumentListInfo *TemplateArgs,
285 QualType T, ExprValueKind VK)
286 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
287 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
288 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
289 if (QualifierLoc)
290 getInternalQualifierLoc() = QualifierLoc;
291 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
292 if (FoundD)
293 getInternalFoundDecl() = FoundD;
294 DeclRefExprBits.HasTemplateKWAndArgsInfo
295 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
296 DeclRefExprBits.RefersToEnclosingLocal = RefersToEnclosingLocal;
297 if (TemplateArgs) {
298 bool Dependent = false;
299 bool InstantiationDependent = false;
300 bool ContainsUnexpandedParameterPack = false;
301 getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
302 Dependent,
303 InstantiationDependent,
304 ContainsUnexpandedParameterPack);
305 if (InstantiationDependent)
306 setInstantiationDependent(true);
307 } else if (TemplateKWLoc.isValid()) {
308 getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
309 }
310 DeclRefExprBits.HadMultipleCandidates = 0;
311
312 computeDependence(Ctx);
313 }
314
Create(ASTContext & Context,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * D,bool RefersToEnclosingLocal,SourceLocation NameLoc,QualType T,ExprValueKind VK,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs)315 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
316 NestedNameSpecifierLoc QualifierLoc,
317 SourceLocation TemplateKWLoc,
318 ValueDecl *D,
319 bool RefersToEnclosingLocal,
320 SourceLocation NameLoc,
321 QualType T,
322 ExprValueKind VK,
323 NamedDecl *FoundD,
324 const TemplateArgumentListInfo *TemplateArgs) {
325 return Create(Context, QualifierLoc, TemplateKWLoc, D,
326 RefersToEnclosingLocal,
327 DeclarationNameInfo(D->getDeclName(), NameLoc),
328 T, VK, FoundD, TemplateArgs);
329 }
330
Create(ASTContext & Context,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * D,bool RefersToEnclosingLocal,const DeclarationNameInfo & NameInfo,QualType T,ExprValueKind VK,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs)331 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
332 NestedNameSpecifierLoc QualifierLoc,
333 SourceLocation TemplateKWLoc,
334 ValueDecl *D,
335 bool RefersToEnclosingLocal,
336 const DeclarationNameInfo &NameInfo,
337 QualType T,
338 ExprValueKind VK,
339 NamedDecl *FoundD,
340 const TemplateArgumentListInfo *TemplateArgs) {
341 // Filter out cases where the found Decl is the same as the value refenenced.
342 if (D == FoundD)
343 FoundD = 0;
344
345 std::size_t Size = sizeof(DeclRefExpr);
346 if (QualifierLoc != 0)
347 Size += sizeof(NestedNameSpecifierLoc);
348 if (FoundD)
349 Size += sizeof(NamedDecl *);
350 if (TemplateArgs)
351 Size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
352 else if (TemplateKWLoc.isValid())
353 Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
354
355 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
356 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
357 RefersToEnclosingLocal,
358 NameInfo, FoundD, TemplateArgs, T, VK);
359 }
360
CreateEmpty(ASTContext & Context,bool HasQualifier,bool HasFoundDecl,bool HasTemplateKWAndArgsInfo,unsigned NumTemplateArgs)361 DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
362 bool HasQualifier,
363 bool HasFoundDecl,
364 bool HasTemplateKWAndArgsInfo,
365 unsigned NumTemplateArgs) {
366 std::size_t Size = sizeof(DeclRefExpr);
367 if (HasQualifier)
368 Size += sizeof(NestedNameSpecifierLoc);
369 if (HasFoundDecl)
370 Size += sizeof(NamedDecl *);
371 if (HasTemplateKWAndArgsInfo)
372 Size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
373
374 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
375 return new (Mem) DeclRefExpr(EmptyShell());
376 }
377
getSourceRange() const378 SourceRange DeclRefExpr::getSourceRange() const {
379 SourceRange R = getNameInfo().getSourceRange();
380 if (hasQualifier())
381 R.setBegin(getQualifierLoc().getBeginLoc());
382 if (hasExplicitTemplateArgs())
383 R.setEnd(getRAngleLoc());
384 return R;
385 }
getLocStart() const386 SourceLocation DeclRefExpr::getLocStart() const {
387 if (hasQualifier())
388 return getQualifierLoc().getBeginLoc();
389 return getNameInfo().getLocStart();
390 }
getLocEnd() const391 SourceLocation DeclRefExpr::getLocEnd() const {
392 if (hasExplicitTemplateArgs())
393 return getRAngleLoc();
394 return getNameInfo().getLocEnd();
395 }
396
397 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
398 // expr" policy instead.
ComputeName(IdentType IT,const Decl * CurrentDecl)399 std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
400 ASTContext &Context = CurrentDecl->getASTContext();
401
402 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
403 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
404 return FD->getNameAsString();
405
406 SmallString<256> Name;
407 llvm::raw_svector_ostream Out(Name);
408
409 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
410 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
411 Out << "virtual ";
412 if (MD->isStatic())
413 Out << "static ";
414 }
415
416 PrintingPolicy Policy(Context.getLangOpts());
417 std::string Proto = FD->getQualifiedNameAsString(Policy);
418 llvm::raw_string_ostream POut(Proto);
419
420 const FunctionDecl *Decl = FD;
421 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
422 Decl = Pattern;
423 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
424 const FunctionProtoType *FT = 0;
425 if (FD->hasWrittenPrototype())
426 FT = dyn_cast<FunctionProtoType>(AFT);
427
428 POut << "(";
429 if (FT) {
430 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
431 if (i) POut << ", ";
432 POut << Decl->getParamDecl(i)->getType().stream(Policy);
433 }
434
435 if (FT->isVariadic()) {
436 if (FD->getNumParams()) POut << ", ";
437 POut << "...";
438 }
439 }
440 POut << ")";
441
442 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
443 const FunctionType *FT = cast<FunctionType>(MD->getType().getTypePtr());
444 if (FT->isConst())
445 POut << " const";
446 if (FT->isVolatile())
447 POut << " volatile";
448 RefQualifierKind Ref = MD->getRefQualifier();
449 if (Ref == RQ_LValue)
450 POut << " &";
451 else if (Ref == RQ_RValue)
452 POut << " &&";
453 }
454
455 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
456 SpecsTy Specs;
457 const DeclContext *Ctx = FD->getDeclContext();
458 while (Ctx && isa<NamedDecl>(Ctx)) {
459 const ClassTemplateSpecializationDecl *Spec
460 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
461 if (Spec && !Spec->isExplicitSpecialization())
462 Specs.push_back(Spec);
463 Ctx = Ctx->getParent();
464 }
465
466 std::string TemplateParams;
467 llvm::raw_string_ostream TOut(TemplateParams);
468 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
469 I != E; ++I) {
470 const TemplateParameterList *Params
471 = (*I)->getSpecializedTemplate()->getTemplateParameters();
472 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
473 assert(Params->size() == Args.size());
474 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
475 StringRef Param = Params->getParam(i)->getName();
476 if (Param.empty()) continue;
477 TOut << Param << " = ";
478 Args.get(i).print(Policy, TOut);
479 TOut << ", ";
480 }
481 }
482
483 FunctionTemplateSpecializationInfo *FSI
484 = FD->getTemplateSpecializationInfo();
485 if (FSI && !FSI->isExplicitSpecialization()) {
486 const TemplateParameterList* Params
487 = FSI->getTemplate()->getTemplateParameters();
488 const TemplateArgumentList* Args = FSI->TemplateArguments;
489 assert(Params->size() == Args->size());
490 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
491 StringRef Param = Params->getParam(i)->getName();
492 if (Param.empty()) continue;
493 TOut << Param << " = ";
494 Args->get(i).print(Policy, TOut);
495 TOut << ", ";
496 }
497 }
498
499 TOut.flush();
500 if (!TemplateParams.empty()) {
501 // remove the trailing comma and space
502 TemplateParams.resize(TemplateParams.size() - 2);
503 POut << " [" << TemplateParams << "]";
504 }
505
506 POut.flush();
507
508 if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
509 AFT->getResultType().getAsStringInternal(Proto, Policy);
510
511 Out << Proto;
512
513 Out.flush();
514 return Name.str().str();
515 }
516 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
517 SmallString<256> Name;
518 llvm::raw_svector_ostream Out(Name);
519 Out << (MD->isInstanceMethod() ? '-' : '+');
520 Out << '[';
521
522 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
523 // a null check to avoid a crash.
524 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
525 Out << *ID;
526
527 if (const ObjCCategoryImplDecl *CID =
528 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
529 Out << '(' << *CID << ')';
530
531 Out << ' ';
532 Out << MD->getSelector().getAsString();
533 Out << ']';
534
535 Out.flush();
536 return Name.str().str();
537 }
538 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
539 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
540 return "top level";
541 }
542 return "";
543 }
544
setIntValue(ASTContext & C,const llvm::APInt & Val)545 void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
546 if (hasAllocation())
547 C.Deallocate(pVal);
548
549 BitWidth = Val.getBitWidth();
550 unsigned NumWords = Val.getNumWords();
551 const uint64_t* Words = Val.getRawData();
552 if (NumWords > 1) {
553 pVal = new (C) uint64_t[NumWords];
554 std::copy(Words, Words + NumWords, pVal);
555 } else if (NumWords == 1)
556 VAL = Words[0];
557 else
558 VAL = 0;
559 }
560
IntegerLiteral(ASTContext & C,const llvm::APInt & V,QualType type,SourceLocation l)561 IntegerLiteral::IntegerLiteral(ASTContext &C, const llvm::APInt &V,
562 QualType type, SourceLocation l)
563 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
564 false, false),
565 Loc(l) {
566 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
567 assert(V.getBitWidth() == C.getIntWidth(type) &&
568 "Integer type is not the correct size for constant.");
569 setValue(C, V);
570 }
571
572 IntegerLiteral *
Create(ASTContext & C,const llvm::APInt & V,QualType type,SourceLocation l)573 IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
574 QualType type, SourceLocation l) {
575 return new (C) IntegerLiteral(C, V, type, l);
576 }
577
578 IntegerLiteral *
Create(ASTContext & C,EmptyShell Empty)579 IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
580 return new (C) IntegerLiteral(Empty);
581 }
582
FloatingLiteral(ASTContext & C,const llvm::APFloat & V,bool isexact,QualType Type,SourceLocation L)583 FloatingLiteral::FloatingLiteral(ASTContext &C, const llvm::APFloat &V,
584 bool isexact, QualType Type, SourceLocation L)
585 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
586 false, false), Loc(L) {
587 FloatingLiteralBits.IsIEEE =
588 &C.getTargetInfo().getLongDoubleFormat() == &llvm::APFloat::IEEEquad;
589 FloatingLiteralBits.IsExact = isexact;
590 setValue(C, V);
591 }
592
FloatingLiteral(ASTContext & C,EmptyShell Empty)593 FloatingLiteral::FloatingLiteral(ASTContext &C, EmptyShell Empty)
594 : Expr(FloatingLiteralClass, Empty) {
595 FloatingLiteralBits.IsIEEE =
596 &C.getTargetInfo().getLongDoubleFormat() == &llvm::APFloat::IEEEquad;
597 FloatingLiteralBits.IsExact = false;
598 }
599
600 FloatingLiteral *
Create(ASTContext & C,const llvm::APFloat & V,bool isexact,QualType Type,SourceLocation L)601 FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
602 bool isexact, QualType Type, SourceLocation L) {
603 return new (C) FloatingLiteral(C, V, isexact, Type, L);
604 }
605
606 FloatingLiteral *
Create(ASTContext & C,EmptyShell Empty)607 FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
608 return new (C) FloatingLiteral(C, Empty);
609 }
610
611 /// getValueAsApproximateDouble - This returns the value as an inaccurate
612 /// double. Note that this may cause loss of precision, but is useful for
613 /// debugging dumps, etc.
getValueAsApproximateDouble() const614 double FloatingLiteral::getValueAsApproximateDouble() const {
615 llvm::APFloat V = getValue();
616 bool ignored;
617 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
618 &ignored);
619 return V.convertToDouble();
620 }
621
mapCharByteWidth(TargetInfo const & target,StringKind k)622 int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
623 int CharByteWidth = 0;
624 switch(k) {
625 case Ascii:
626 case UTF8:
627 CharByteWidth = target.getCharWidth();
628 break;
629 case Wide:
630 CharByteWidth = target.getWCharWidth();
631 break;
632 case UTF16:
633 CharByteWidth = target.getChar16Width();
634 break;
635 case UTF32:
636 CharByteWidth = target.getChar32Width();
637 break;
638 }
639 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
640 CharByteWidth /= 8;
641 assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
642 && "character byte widths supported are 1, 2, and 4 only");
643 return CharByteWidth;
644 }
645
Create(ASTContext & C,StringRef Str,StringKind Kind,bool Pascal,QualType Ty,const SourceLocation * Loc,unsigned NumStrs)646 StringLiteral *StringLiteral::Create(ASTContext &C, StringRef Str,
647 StringKind Kind, bool Pascal, QualType Ty,
648 const SourceLocation *Loc,
649 unsigned NumStrs) {
650 // Allocate enough space for the StringLiteral plus an array of locations for
651 // any concatenated string tokens.
652 void *Mem = C.Allocate(sizeof(StringLiteral)+
653 sizeof(SourceLocation)*(NumStrs-1),
654 llvm::alignOf<StringLiteral>());
655 StringLiteral *SL = new (Mem) StringLiteral(Ty);
656
657 // OPTIMIZE: could allocate this appended to the StringLiteral.
658 SL->setString(C,Str,Kind,Pascal);
659
660 SL->TokLocs[0] = Loc[0];
661 SL->NumConcatenated = NumStrs;
662
663 if (NumStrs != 1)
664 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
665 return SL;
666 }
667
CreateEmpty(ASTContext & C,unsigned NumStrs)668 StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
669 void *Mem = C.Allocate(sizeof(StringLiteral)+
670 sizeof(SourceLocation)*(NumStrs-1),
671 llvm::alignOf<StringLiteral>());
672 StringLiteral *SL = new (Mem) StringLiteral(QualType());
673 SL->CharByteWidth = 0;
674 SL->Length = 0;
675 SL->NumConcatenated = NumStrs;
676 return SL;
677 }
678
outputString(raw_ostream & OS)679 void StringLiteral::outputString(raw_ostream &OS) {
680 switch (getKind()) {
681 case Ascii: break; // no prefix.
682 case Wide: OS << 'L'; break;
683 case UTF8: OS << "u8"; break;
684 case UTF16: OS << 'u'; break;
685 case UTF32: OS << 'U'; break;
686 }
687 OS << '"';
688 static const char Hex[] = "0123456789ABCDEF";
689
690 unsigned LastSlashX = getLength();
691 for (unsigned I = 0, N = getLength(); I != N; ++I) {
692 switch (uint32_t Char = getCodeUnit(I)) {
693 default:
694 // FIXME: Convert UTF-8 back to codepoints before rendering.
695
696 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
697 // Leave invalid surrogates alone; we'll use \x for those.
698 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
699 Char <= 0xdbff) {
700 uint32_t Trail = getCodeUnit(I + 1);
701 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
702 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
703 ++I;
704 }
705 }
706
707 if (Char > 0xff) {
708 // If this is a wide string, output characters over 0xff using \x
709 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
710 // codepoint: use \x escapes for invalid codepoints.
711 if (getKind() == Wide ||
712 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
713 // FIXME: Is this the best way to print wchar_t?
714 OS << "\\x";
715 int Shift = 28;
716 while ((Char >> Shift) == 0)
717 Shift -= 4;
718 for (/**/; Shift >= 0; Shift -= 4)
719 OS << Hex[(Char >> Shift) & 15];
720 LastSlashX = I;
721 break;
722 }
723
724 if (Char > 0xffff)
725 OS << "\\U00"
726 << Hex[(Char >> 20) & 15]
727 << Hex[(Char >> 16) & 15];
728 else
729 OS << "\\u";
730 OS << Hex[(Char >> 12) & 15]
731 << Hex[(Char >> 8) & 15]
732 << Hex[(Char >> 4) & 15]
733 << Hex[(Char >> 0) & 15];
734 break;
735 }
736
737 // If we used \x... for the previous character, and this character is a
738 // hexadecimal digit, prevent it being slurped as part of the \x.
739 if (LastSlashX + 1 == I) {
740 switch (Char) {
741 case '0': case '1': case '2': case '3': case '4':
742 case '5': case '6': case '7': case '8': case '9':
743 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
744 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
745 OS << "\"\"";
746 }
747 }
748
749 assert(Char <= 0xff &&
750 "Characters above 0xff should already have been handled.");
751
752 if (isprint(Char))
753 OS << (char)Char;
754 else // Output anything hard as an octal escape.
755 OS << '\\'
756 << (char)('0' + ((Char >> 6) & 7))
757 << (char)('0' + ((Char >> 3) & 7))
758 << (char)('0' + ((Char >> 0) & 7));
759 break;
760 // Handle some common non-printable cases to make dumps prettier.
761 case '\\': OS << "\\\\"; break;
762 case '"': OS << "\\\""; break;
763 case '\n': OS << "\\n"; break;
764 case '\t': OS << "\\t"; break;
765 case '\a': OS << "\\a"; break;
766 case '\b': OS << "\\b"; break;
767 }
768 }
769 OS << '"';
770 }
771
setString(ASTContext & C,StringRef Str,StringKind Kind,bool IsPascal)772 void StringLiteral::setString(ASTContext &C, StringRef Str,
773 StringKind Kind, bool IsPascal) {
774 //FIXME: we assume that the string data comes from a target that uses the same
775 // code unit size and endianess for the type of string.
776 this->Kind = Kind;
777 this->IsPascal = IsPascal;
778
779 CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
780 assert((Str.size()%CharByteWidth == 0)
781 && "size of data must be multiple of CharByteWidth");
782 Length = Str.size()/CharByteWidth;
783
784 switch(CharByteWidth) {
785 case 1: {
786 char *AStrData = new (C) char[Length];
787 std::memcpy(AStrData,Str.data(),Str.size());
788 StrData.asChar = AStrData;
789 break;
790 }
791 case 2: {
792 uint16_t *AStrData = new (C) uint16_t[Length];
793 std::memcpy(AStrData,Str.data(),Str.size());
794 StrData.asUInt16 = AStrData;
795 break;
796 }
797 case 4: {
798 uint32_t *AStrData = new (C) uint32_t[Length];
799 std::memcpy(AStrData,Str.data(),Str.size());
800 StrData.asUInt32 = AStrData;
801 break;
802 }
803 default:
804 assert(false && "unsupported CharByteWidth");
805 }
806 }
807
808 /// getLocationOfByte - Return a source location that points to the specified
809 /// byte of this string literal.
810 ///
811 /// Strings are amazingly complex. They can be formed from multiple tokens and
812 /// can have escape sequences in them in addition to the usual trigraph and
813 /// escaped newline business. This routine handles this complexity.
814 ///
815 SourceLocation StringLiteral::
getLocationOfByte(unsigned ByteNo,const SourceManager & SM,const LangOptions & Features,const TargetInfo & Target) const816 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
817 const LangOptions &Features, const TargetInfo &Target) const {
818 assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) &&
819 "Only narrow string literals are currently supported");
820
821 // Loop over all of the tokens in this string until we find the one that
822 // contains the byte we're looking for.
823 unsigned TokNo = 0;
824 while (1) {
825 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
826 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
827
828 // Get the spelling of the string so that we can get the data that makes up
829 // the string literal, not the identifier for the macro it is potentially
830 // expanded through.
831 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
832
833 // Re-lex the token to get its length and original spelling.
834 std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
835 bool Invalid = false;
836 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
837 if (Invalid)
838 return StrTokSpellingLoc;
839
840 const char *StrData = Buffer.data()+LocInfo.second;
841
842 // Create a lexer starting at the beginning of this token.
843 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
844 Buffer.begin(), StrData, Buffer.end());
845 Token TheTok;
846 TheLexer.LexFromRawLexer(TheTok);
847
848 // Use the StringLiteralParser to compute the length of the string in bytes.
849 StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
850 unsigned TokNumBytes = SLP.GetStringLength();
851
852 // If the byte is in this token, return the location of the byte.
853 if (ByteNo < TokNumBytes ||
854 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
855 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
856
857 // Now that we know the offset of the token in the spelling, use the
858 // preprocessor to get the offset in the original source.
859 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
860 }
861
862 // Move to the next string token.
863 ++TokNo;
864 ByteNo -= TokNumBytes;
865 }
866 }
867
868
869
870 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
871 /// corresponds to, e.g. "sizeof" or "[pre]++".
getOpcodeStr(Opcode Op)872 const char *UnaryOperator::getOpcodeStr(Opcode Op) {
873 switch (Op) {
874 case UO_PostInc: return "++";
875 case UO_PostDec: return "--";
876 case UO_PreInc: return "++";
877 case UO_PreDec: return "--";
878 case UO_AddrOf: return "&";
879 case UO_Deref: return "*";
880 case UO_Plus: return "+";
881 case UO_Minus: return "-";
882 case UO_Not: return "~";
883 case UO_LNot: return "!";
884 case UO_Real: return "__real";
885 case UO_Imag: return "__imag";
886 case UO_Extension: return "__extension__";
887 }
888 llvm_unreachable("Unknown unary operator");
889 }
890
891 UnaryOperatorKind
getOverloadedOpcode(OverloadedOperatorKind OO,bool Postfix)892 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
893 switch (OO) {
894 default: llvm_unreachable("No unary operator for overloaded function");
895 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
896 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
897 case OO_Amp: return UO_AddrOf;
898 case OO_Star: return UO_Deref;
899 case OO_Plus: return UO_Plus;
900 case OO_Minus: return UO_Minus;
901 case OO_Tilde: return UO_Not;
902 case OO_Exclaim: return UO_LNot;
903 }
904 }
905
getOverloadedOperator(Opcode Opc)906 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
907 switch (Opc) {
908 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
909 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
910 case UO_AddrOf: return OO_Amp;
911 case UO_Deref: return OO_Star;
912 case UO_Plus: return OO_Plus;
913 case UO_Minus: return OO_Minus;
914 case UO_Not: return OO_Tilde;
915 case UO_LNot: return OO_Exclaim;
916 default: return OO_None;
917 }
918 }
919
920
921 //===----------------------------------------------------------------------===//
922 // Postfix Operators.
923 //===----------------------------------------------------------------------===//
924
CallExpr(ASTContext & C,StmtClass SC,Expr * fn,unsigned NumPreArgs,ArrayRef<Expr * > args,QualType t,ExprValueKind VK,SourceLocation rparenloc)925 CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
926 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
927 SourceLocation rparenloc)
928 : Expr(SC, t, VK, OK_Ordinary,
929 fn->isTypeDependent(),
930 fn->isValueDependent(),
931 fn->isInstantiationDependent(),
932 fn->containsUnexpandedParameterPack()),
933 NumArgs(args.size()) {
934
935 SubExprs = new (C) Stmt*[args.size()+PREARGS_START+NumPreArgs];
936 SubExprs[FN] = fn;
937 for (unsigned i = 0; i != args.size(); ++i) {
938 if (args[i]->isTypeDependent())
939 ExprBits.TypeDependent = true;
940 if (args[i]->isValueDependent())
941 ExprBits.ValueDependent = true;
942 if (args[i]->isInstantiationDependent())
943 ExprBits.InstantiationDependent = true;
944 if (args[i]->containsUnexpandedParameterPack())
945 ExprBits.ContainsUnexpandedParameterPack = true;
946
947 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
948 }
949
950 CallExprBits.NumPreArgs = NumPreArgs;
951 RParenLoc = rparenloc;
952 }
953
CallExpr(ASTContext & C,Expr * fn,ArrayRef<Expr * > args,QualType t,ExprValueKind VK,SourceLocation rparenloc)954 CallExpr::CallExpr(ASTContext& C, Expr *fn, ArrayRef<Expr*> args,
955 QualType t, ExprValueKind VK, SourceLocation rparenloc)
956 : Expr(CallExprClass, t, VK, OK_Ordinary,
957 fn->isTypeDependent(),
958 fn->isValueDependent(),
959 fn->isInstantiationDependent(),
960 fn->containsUnexpandedParameterPack()),
961 NumArgs(args.size()) {
962
963 SubExprs = new (C) Stmt*[args.size()+PREARGS_START];
964 SubExprs[FN] = fn;
965 for (unsigned i = 0; i != args.size(); ++i) {
966 if (args[i]->isTypeDependent())
967 ExprBits.TypeDependent = true;
968 if (args[i]->isValueDependent())
969 ExprBits.ValueDependent = true;
970 if (args[i]->isInstantiationDependent())
971 ExprBits.InstantiationDependent = true;
972 if (args[i]->containsUnexpandedParameterPack())
973 ExprBits.ContainsUnexpandedParameterPack = true;
974
975 SubExprs[i+PREARGS_START] = args[i];
976 }
977
978 CallExprBits.NumPreArgs = 0;
979 RParenLoc = rparenloc;
980 }
981
CallExpr(ASTContext & C,StmtClass SC,EmptyShell Empty)982 CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
983 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
984 // FIXME: Why do we allocate this?
985 SubExprs = new (C) Stmt*[PREARGS_START];
986 CallExprBits.NumPreArgs = 0;
987 }
988
CallExpr(ASTContext & C,StmtClass SC,unsigned NumPreArgs,EmptyShell Empty)989 CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs,
990 EmptyShell Empty)
991 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
992 // FIXME: Why do we allocate this?
993 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
994 CallExprBits.NumPreArgs = NumPreArgs;
995 }
996
getCalleeDecl()997 Decl *CallExpr::getCalleeDecl() {
998 Expr *CEE = getCallee()->IgnoreParenImpCasts();
999
1000 while (SubstNonTypeTemplateParmExpr *NTTP
1001 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1002 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1003 }
1004
1005 // If we're calling a dereference, look at the pointer instead.
1006 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1007 if (BO->isPtrMemOp())
1008 CEE = BO->getRHS()->IgnoreParenCasts();
1009 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1010 if (UO->getOpcode() == UO_Deref)
1011 CEE = UO->getSubExpr()->IgnoreParenCasts();
1012 }
1013 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
1014 return DRE->getDecl();
1015 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1016 return ME->getMemberDecl();
1017
1018 return 0;
1019 }
1020
getDirectCallee()1021 FunctionDecl *CallExpr::getDirectCallee() {
1022 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
1023 }
1024
1025 /// setNumArgs - This changes the number of arguments present in this call.
1026 /// Any orphaned expressions are deleted by this, and any new operands are set
1027 /// to null.
setNumArgs(ASTContext & C,unsigned NumArgs)1028 void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
1029 // No change, just return.
1030 if (NumArgs == getNumArgs()) return;
1031
1032 // If shrinking # arguments, just delete the extras and forgot them.
1033 if (NumArgs < getNumArgs()) {
1034 this->NumArgs = NumArgs;
1035 return;
1036 }
1037
1038 // Otherwise, we are growing the # arguments. New an bigger argument array.
1039 unsigned NumPreArgs = getNumPreArgs();
1040 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
1041 // Copy over args.
1042 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
1043 NewSubExprs[i] = SubExprs[i];
1044 // Null out new args.
1045 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
1046 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
1047 NewSubExprs[i] = 0;
1048
1049 if (SubExprs) C.Deallocate(SubExprs);
1050 SubExprs = NewSubExprs;
1051 this->NumArgs = NumArgs;
1052 }
1053
1054 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If
1055 /// not, return 0.
isBuiltinCall() const1056 unsigned CallExpr::isBuiltinCall() const {
1057 // All simple function calls (e.g. func()) are implicitly cast to pointer to
1058 // function. As a result, we try and obtain the DeclRefExpr from the
1059 // ImplicitCastExpr.
1060 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1061 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
1062 return 0;
1063
1064 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1065 if (!DRE)
1066 return 0;
1067
1068 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1069 if (!FDecl)
1070 return 0;
1071
1072 if (!FDecl->getIdentifier())
1073 return 0;
1074
1075 return FDecl->getBuiltinID();
1076 }
1077
getCallReturnType() const1078 QualType CallExpr::getCallReturnType() const {
1079 QualType CalleeType = getCallee()->getType();
1080 if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
1081 CalleeType = FnTypePtr->getPointeeType();
1082 else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
1083 CalleeType = BPT->getPointeeType();
1084 else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember))
1085 // This should never be overloaded and so should never return null.
1086 CalleeType = Expr::findBoundMemberType(getCallee());
1087
1088 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1089 return FnType->getResultType();
1090 }
1091
getSourceRange() const1092 SourceRange CallExpr::getSourceRange() const {
1093 if (isa<CXXOperatorCallExpr>(this))
1094 return cast<CXXOperatorCallExpr>(this)->getSourceRange();
1095
1096 SourceLocation begin = getCallee()->getLocStart();
1097 if (begin.isInvalid() && getNumArgs() > 0)
1098 begin = getArg(0)->getLocStart();
1099 SourceLocation end = getRParenLoc();
1100 if (end.isInvalid() && getNumArgs() > 0)
1101 end = getArg(getNumArgs() - 1)->getLocEnd();
1102 return SourceRange(begin, end);
1103 }
getLocStart() const1104 SourceLocation CallExpr::getLocStart() const {
1105 if (isa<CXXOperatorCallExpr>(this))
1106 return cast<CXXOperatorCallExpr>(this)->getSourceRange().getBegin();
1107
1108 SourceLocation begin = getCallee()->getLocStart();
1109 if (begin.isInvalid() && getNumArgs() > 0)
1110 begin = getArg(0)->getLocStart();
1111 return begin;
1112 }
getLocEnd() const1113 SourceLocation CallExpr::getLocEnd() const {
1114 if (isa<CXXOperatorCallExpr>(this))
1115 return cast<CXXOperatorCallExpr>(this)->getSourceRange().getEnd();
1116
1117 SourceLocation end = getRParenLoc();
1118 if (end.isInvalid() && getNumArgs() > 0)
1119 end = getArg(getNumArgs() - 1)->getLocEnd();
1120 return end;
1121 }
1122
Create(ASTContext & C,QualType type,SourceLocation OperatorLoc,TypeSourceInfo * tsi,ArrayRef<OffsetOfNode> comps,ArrayRef<Expr * > exprs,SourceLocation RParenLoc)1123 OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
1124 SourceLocation OperatorLoc,
1125 TypeSourceInfo *tsi,
1126 ArrayRef<OffsetOfNode> comps,
1127 ArrayRef<Expr*> exprs,
1128 SourceLocation RParenLoc) {
1129 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
1130 sizeof(OffsetOfNode) * comps.size() +
1131 sizeof(Expr*) * exprs.size());
1132
1133 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1134 RParenLoc);
1135 }
1136
CreateEmpty(ASTContext & C,unsigned numComps,unsigned numExprs)1137 OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
1138 unsigned numComps, unsigned numExprs) {
1139 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
1140 sizeof(OffsetOfNode) * numComps +
1141 sizeof(Expr*) * numExprs);
1142 return new (Mem) OffsetOfExpr(numComps, numExprs);
1143 }
1144
OffsetOfExpr(ASTContext & C,QualType type,SourceLocation OperatorLoc,TypeSourceInfo * tsi,ArrayRef<OffsetOfNode> comps,ArrayRef<Expr * > exprs,SourceLocation RParenLoc)1145 OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
1146 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1147 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1148 SourceLocation RParenLoc)
1149 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1150 /*TypeDependent=*/false,
1151 /*ValueDependent=*/tsi->getType()->isDependentType(),
1152 tsi->getType()->isInstantiationDependentType(),
1153 tsi->getType()->containsUnexpandedParameterPack()),
1154 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1155 NumComps(comps.size()), NumExprs(exprs.size())
1156 {
1157 for (unsigned i = 0; i != comps.size(); ++i) {
1158 setComponent(i, comps[i]);
1159 }
1160
1161 for (unsigned i = 0; i != exprs.size(); ++i) {
1162 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
1163 ExprBits.ValueDependent = true;
1164 if (exprs[i]->containsUnexpandedParameterPack())
1165 ExprBits.ContainsUnexpandedParameterPack = true;
1166
1167 setIndexExpr(i, exprs[i]);
1168 }
1169 }
1170
getFieldName() const1171 IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
1172 assert(getKind() == Field || getKind() == Identifier);
1173 if (getKind() == Field)
1174 return getField()->getIdentifier();
1175
1176 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1177 }
1178
Create(ASTContext & C,Expr * base,bool isarrow,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * memberdecl,DeclAccessPair founddecl,DeclarationNameInfo nameinfo,const TemplateArgumentListInfo * targs,QualType ty,ExprValueKind vk,ExprObjectKind ok)1179 MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
1180 NestedNameSpecifierLoc QualifierLoc,
1181 SourceLocation TemplateKWLoc,
1182 ValueDecl *memberdecl,
1183 DeclAccessPair founddecl,
1184 DeclarationNameInfo nameinfo,
1185 const TemplateArgumentListInfo *targs,
1186 QualType ty,
1187 ExprValueKind vk,
1188 ExprObjectKind ok) {
1189 std::size_t Size = sizeof(MemberExpr);
1190
1191 bool hasQualOrFound = (QualifierLoc ||
1192 founddecl.getDecl() != memberdecl ||
1193 founddecl.getAccess() != memberdecl->getAccess());
1194 if (hasQualOrFound)
1195 Size += sizeof(MemberNameQualifier);
1196
1197 if (targs)
1198 Size += ASTTemplateKWAndArgsInfo::sizeFor(targs->size());
1199 else if (TemplateKWLoc.isValid())
1200 Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
1201
1202 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
1203 MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
1204 ty, vk, ok);
1205
1206 if (hasQualOrFound) {
1207 // FIXME: Wrong. We should be looking at the member declaration we found.
1208 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1209 E->setValueDependent(true);
1210 E->setTypeDependent(true);
1211 E->setInstantiationDependent(true);
1212 }
1213 else if (QualifierLoc &&
1214 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1215 E->setInstantiationDependent(true);
1216
1217 E->HasQualifierOrFoundDecl = true;
1218
1219 MemberNameQualifier *NQ = E->getMemberQualifier();
1220 NQ->QualifierLoc = QualifierLoc;
1221 NQ->FoundDecl = founddecl;
1222 }
1223
1224 E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
1225
1226 if (targs) {
1227 bool Dependent = false;
1228 bool InstantiationDependent = false;
1229 bool ContainsUnexpandedParameterPack = false;
1230 E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *targs,
1231 Dependent,
1232 InstantiationDependent,
1233 ContainsUnexpandedParameterPack);
1234 if (InstantiationDependent)
1235 E->setInstantiationDependent(true);
1236 } else if (TemplateKWLoc.isValid()) {
1237 E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
1238 }
1239
1240 return E;
1241 }
1242
getSourceRange() const1243 SourceRange MemberExpr::getSourceRange() const {
1244 return SourceRange(getLocStart(), getLocEnd());
1245 }
getLocStart() const1246 SourceLocation MemberExpr::getLocStart() const {
1247 if (isImplicitAccess()) {
1248 if (hasQualifier())
1249 return getQualifierLoc().getBeginLoc();
1250 return MemberLoc;
1251 }
1252
1253 // FIXME: We don't want this to happen. Rather, we should be able to
1254 // detect all kinds of implicit accesses more cleanly.
1255 SourceLocation BaseStartLoc = getBase()->getLocStart();
1256 if (BaseStartLoc.isValid())
1257 return BaseStartLoc;
1258 return MemberLoc;
1259 }
getLocEnd() const1260 SourceLocation MemberExpr::getLocEnd() const {
1261 if (hasExplicitTemplateArgs())
1262 return getRAngleLoc();
1263 return getMemberNameInfo().getEndLoc();
1264 }
1265
CheckCastConsistency() const1266 void CastExpr::CheckCastConsistency() const {
1267 switch (getCastKind()) {
1268 case CK_DerivedToBase:
1269 case CK_UncheckedDerivedToBase:
1270 case CK_DerivedToBaseMemberPointer:
1271 case CK_BaseToDerived:
1272 case CK_BaseToDerivedMemberPointer:
1273 assert(!path_empty() && "Cast kind should have a base path!");
1274 break;
1275
1276 case CK_CPointerToObjCPointerCast:
1277 assert(getType()->isObjCObjectPointerType());
1278 assert(getSubExpr()->getType()->isPointerType());
1279 goto CheckNoBasePath;
1280
1281 case CK_BlockPointerToObjCPointerCast:
1282 assert(getType()->isObjCObjectPointerType());
1283 assert(getSubExpr()->getType()->isBlockPointerType());
1284 goto CheckNoBasePath;
1285
1286 case CK_ReinterpretMemberPointer:
1287 assert(getType()->isMemberPointerType());
1288 assert(getSubExpr()->getType()->isMemberPointerType());
1289 goto CheckNoBasePath;
1290
1291 case CK_BitCast:
1292 // Arbitrary casts to C pointer types count as bitcasts.
1293 // Otherwise, we should only have block and ObjC pointer casts
1294 // here if they stay within the type kind.
1295 if (!getType()->isPointerType()) {
1296 assert(getType()->isObjCObjectPointerType() ==
1297 getSubExpr()->getType()->isObjCObjectPointerType());
1298 assert(getType()->isBlockPointerType() ==
1299 getSubExpr()->getType()->isBlockPointerType());
1300 }
1301 goto CheckNoBasePath;
1302
1303 case CK_AnyPointerToBlockPointerCast:
1304 assert(getType()->isBlockPointerType());
1305 assert(getSubExpr()->getType()->isAnyPointerType() &&
1306 !getSubExpr()->getType()->isBlockPointerType());
1307 goto CheckNoBasePath;
1308
1309 case CK_CopyAndAutoreleaseBlockObject:
1310 assert(getType()->isBlockPointerType());
1311 assert(getSubExpr()->getType()->isBlockPointerType());
1312 goto CheckNoBasePath;
1313
1314 case CK_FunctionToPointerDecay:
1315 assert(getType()->isPointerType());
1316 assert(getSubExpr()->getType()->isFunctionType());
1317 goto CheckNoBasePath;
1318
1319 // These should not have an inheritance path.
1320 case CK_Dynamic:
1321 case CK_ToUnion:
1322 case CK_ArrayToPointerDecay:
1323 case CK_NullToMemberPointer:
1324 case CK_NullToPointer:
1325 case CK_ConstructorConversion:
1326 case CK_IntegralToPointer:
1327 case CK_PointerToIntegral:
1328 case CK_ToVoid:
1329 case CK_VectorSplat:
1330 case CK_IntegralCast:
1331 case CK_IntegralToFloating:
1332 case CK_FloatingToIntegral:
1333 case CK_FloatingCast:
1334 case CK_ObjCObjectLValueCast:
1335 case CK_FloatingRealToComplex:
1336 case CK_FloatingComplexToReal:
1337 case CK_FloatingComplexCast:
1338 case CK_FloatingComplexToIntegralComplex:
1339 case CK_IntegralRealToComplex:
1340 case CK_IntegralComplexToReal:
1341 case CK_IntegralComplexCast:
1342 case CK_IntegralComplexToFloatingComplex:
1343 case CK_ARCProduceObject:
1344 case CK_ARCConsumeObject:
1345 case CK_ARCReclaimReturnedObject:
1346 case CK_ARCExtendBlockObject:
1347 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1348 goto CheckNoBasePath;
1349
1350 case CK_Dependent:
1351 case CK_LValueToRValue:
1352 case CK_NoOp:
1353 case CK_AtomicToNonAtomic:
1354 case CK_NonAtomicToAtomic:
1355 case CK_PointerToBoolean:
1356 case CK_IntegralToBoolean:
1357 case CK_FloatingToBoolean:
1358 case CK_MemberPointerToBoolean:
1359 case CK_FloatingComplexToBoolean:
1360 case CK_IntegralComplexToBoolean:
1361 case CK_LValueBitCast: // -> bool&
1362 case CK_UserDefinedConversion: // operator bool()
1363 case CK_BuiltinFnToFnPtr:
1364 CheckNoBasePath:
1365 assert(path_empty() && "Cast kind should not have a base path!");
1366 break;
1367 }
1368 }
1369
getCastKindName() const1370 const char *CastExpr::getCastKindName() const {
1371 switch (getCastKind()) {
1372 case CK_Dependent:
1373 return "Dependent";
1374 case CK_BitCast:
1375 return "BitCast";
1376 case CK_LValueBitCast:
1377 return "LValueBitCast";
1378 case CK_LValueToRValue:
1379 return "LValueToRValue";
1380 case CK_NoOp:
1381 return "NoOp";
1382 case CK_BaseToDerived:
1383 return "BaseToDerived";
1384 case CK_DerivedToBase:
1385 return "DerivedToBase";
1386 case CK_UncheckedDerivedToBase:
1387 return "UncheckedDerivedToBase";
1388 case CK_Dynamic:
1389 return "Dynamic";
1390 case CK_ToUnion:
1391 return "ToUnion";
1392 case CK_ArrayToPointerDecay:
1393 return "ArrayToPointerDecay";
1394 case CK_FunctionToPointerDecay:
1395 return "FunctionToPointerDecay";
1396 case CK_NullToMemberPointer:
1397 return "NullToMemberPointer";
1398 case CK_NullToPointer:
1399 return "NullToPointer";
1400 case CK_BaseToDerivedMemberPointer:
1401 return "BaseToDerivedMemberPointer";
1402 case CK_DerivedToBaseMemberPointer:
1403 return "DerivedToBaseMemberPointer";
1404 case CK_ReinterpretMemberPointer:
1405 return "ReinterpretMemberPointer";
1406 case CK_UserDefinedConversion:
1407 return "UserDefinedConversion";
1408 case CK_ConstructorConversion:
1409 return "ConstructorConversion";
1410 case CK_IntegralToPointer:
1411 return "IntegralToPointer";
1412 case CK_PointerToIntegral:
1413 return "PointerToIntegral";
1414 case CK_PointerToBoolean:
1415 return "PointerToBoolean";
1416 case CK_ToVoid:
1417 return "ToVoid";
1418 case CK_VectorSplat:
1419 return "VectorSplat";
1420 case CK_IntegralCast:
1421 return "IntegralCast";
1422 case CK_IntegralToBoolean:
1423 return "IntegralToBoolean";
1424 case CK_IntegralToFloating:
1425 return "IntegralToFloating";
1426 case CK_FloatingToIntegral:
1427 return "FloatingToIntegral";
1428 case CK_FloatingCast:
1429 return "FloatingCast";
1430 case CK_FloatingToBoolean:
1431 return "FloatingToBoolean";
1432 case CK_MemberPointerToBoolean:
1433 return "MemberPointerToBoolean";
1434 case CK_CPointerToObjCPointerCast:
1435 return "CPointerToObjCPointerCast";
1436 case CK_BlockPointerToObjCPointerCast:
1437 return "BlockPointerToObjCPointerCast";
1438 case CK_AnyPointerToBlockPointerCast:
1439 return "AnyPointerToBlockPointerCast";
1440 case CK_ObjCObjectLValueCast:
1441 return "ObjCObjectLValueCast";
1442 case CK_FloatingRealToComplex:
1443 return "FloatingRealToComplex";
1444 case CK_FloatingComplexToReal:
1445 return "FloatingComplexToReal";
1446 case CK_FloatingComplexToBoolean:
1447 return "FloatingComplexToBoolean";
1448 case CK_FloatingComplexCast:
1449 return "FloatingComplexCast";
1450 case CK_FloatingComplexToIntegralComplex:
1451 return "FloatingComplexToIntegralComplex";
1452 case CK_IntegralRealToComplex:
1453 return "IntegralRealToComplex";
1454 case CK_IntegralComplexToReal:
1455 return "IntegralComplexToReal";
1456 case CK_IntegralComplexToBoolean:
1457 return "IntegralComplexToBoolean";
1458 case CK_IntegralComplexCast:
1459 return "IntegralComplexCast";
1460 case CK_IntegralComplexToFloatingComplex:
1461 return "IntegralComplexToFloatingComplex";
1462 case CK_ARCConsumeObject:
1463 return "ARCConsumeObject";
1464 case CK_ARCProduceObject:
1465 return "ARCProduceObject";
1466 case CK_ARCReclaimReturnedObject:
1467 return "ARCReclaimReturnedObject";
1468 case CK_ARCExtendBlockObject:
1469 return "ARCCExtendBlockObject";
1470 case CK_AtomicToNonAtomic:
1471 return "AtomicToNonAtomic";
1472 case CK_NonAtomicToAtomic:
1473 return "NonAtomicToAtomic";
1474 case CK_CopyAndAutoreleaseBlockObject:
1475 return "CopyAndAutoreleaseBlockObject";
1476 case CK_BuiltinFnToFnPtr:
1477 return "BuiltinFnToFnPtr";
1478 }
1479
1480 llvm_unreachable("Unhandled cast kind!");
1481 }
1482
getSubExprAsWritten()1483 Expr *CastExpr::getSubExprAsWritten() {
1484 Expr *SubExpr = 0;
1485 CastExpr *E = this;
1486 do {
1487 SubExpr = E->getSubExpr();
1488
1489 // Skip through reference binding to temporary.
1490 if (MaterializeTemporaryExpr *Materialize
1491 = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1492 SubExpr = Materialize->GetTemporaryExpr();
1493
1494 // Skip any temporary bindings; they're implicit.
1495 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1496 SubExpr = Binder->getSubExpr();
1497
1498 // Conversions by constructor and conversion functions have a
1499 // subexpression describing the call; strip it off.
1500 if (E->getCastKind() == CK_ConstructorConversion)
1501 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
1502 else if (E->getCastKind() == CK_UserDefinedConversion)
1503 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1504
1505 // If the subexpression we're left with is an implicit cast, look
1506 // through that, too.
1507 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1508
1509 return SubExpr;
1510 }
1511
path_buffer()1512 CXXBaseSpecifier **CastExpr::path_buffer() {
1513 switch (getStmtClass()) {
1514 #define ABSTRACT_STMT(x)
1515 #define CASTEXPR(Type, Base) \
1516 case Stmt::Type##Class: \
1517 return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1518 #define STMT(Type, Base)
1519 #include "clang/AST/StmtNodes.inc"
1520 default:
1521 llvm_unreachable("non-cast expressions not possible here");
1522 }
1523 }
1524
setCastPath(const CXXCastPath & Path)1525 void CastExpr::setCastPath(const CXXCastPath &Path) {
1526 assert(Path.size() == path_size());
1527 memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1528 }
1529
Create(ASTContext & C,QualType T,CastKind Kind,Expr * Operand,const CXXCastPath * BasePath,ExprValueKind VK)1530 ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
1531 CastKind Kind, Expr *Operand,
1532 const CXXCastPath *BasePath,
1533 ExprValueKind VK) {
1534 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1535 void *Buffer =
1536 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1537 ImplicitCastExpr *E =
1538 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1539 if (PathSize) E->setCastPath(*BasePath);
1540 return E;
1541 }
1542
CreateEmpty(ASTContext & C,unsigned PathSize)1543 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
1544 unsigned PathSize) {
1545 void *Buffer =
1546 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1547 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1548 }
1549
1550
Create(ASTContext & C,QualType T,ExprValueKind VK,CastKind K,Expr * Op,const CXXCastPath * BasePath,TypeSourceInfo * WrittenTy,SourceLocation L,SourceLocation R)1551 CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
1552 ExprValueKind VK, CastKind K, Expr *Op,
1553 const CXXCastPath *BasePath,
1554 TypeSourceInfo *WrittenTy,
1555 SourceLocation L, SourceLocation R) {
1556 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1557 void *Buffer =
1558 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1559 CStyleCastExpr *E =
1560 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1561 if (PathSize) E->setCastPath(*BasePath);
1562 return E;
1563 }
1564
CreateEmpty(ASTContext & C,unsigned PathSize)1565 CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
1566 void *Buffer =
1567 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1568 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1569 }
1570
1571 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1572 /// corresponds to, e.g. "<<=".
getOpcodeStr(Opcode Op)1573 const char *BinaryOperator::getOpcodeStr(Opcode Op) {
1574 switch (Op) {
1575 case BO_PtrMemD: return ".*";
1576 case BO_PtrMemI: return "->*";
1577 case BO_Mul: return "*";
1578 case BO_Div: return "/";
1579 case BO_Rem: return "%";
1580 case BO_Add: return "+";
1581 case BO_Sub: return "-";
1582 case BO_Shl: return "<<";
1583 case BO_Shr: return ">>";
1584 case BO_LT: return "<";
1585 case BO_GT: return ">";
1586 case BO_LE: return "<=";
1587 case BO_GE: return ">=";
1588 case BO_EQ: return "==";
1589 case BO_NE: return "!=";
1590 case BO_And: return "&";
1591 case BO_Xor: return "^";
1592 case BO_Or: return "|";
1593 case BO_LAnd: return "&&";
1594 case BO_LOr: return "||";
1595 case BO_Assign: return "=";
1596 case BO_MulAssign: return "*=";
1597 case BO_DivAssign: return "/=";
1598 case BO_RemAssign: return "%=";
1599 case BO_AddAssign: return "+=";
1600 case BO_SubAssign: return "-=";
1601 case BO_ShlAssign: return "<<=";
1602 case BO_ShrAssign: return ">>=";
1603 case BO_AndAssign: return "&=";
1604 case BO_XorAssign: return "^=";
1605 case BO_OrAssign: return "|=";
1606 case BO_Comma: return ",";
1607 }
1608
1609 llvm_unreachable("Invalid OpCode!");
1610 }
1611
1612 BinaryOperatorKind
getOverloadedOpcode(OverloadedOperatorKind OO)1613 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1614 switch (OO) {
1615 default: llvm_unreachable("Not an overloadable binary operator");
1616 case OO_Plus: return BO_Add;
1617 case OO_Minus: return BO_Sub;
1618 case OO_Star: return BO_Mul;
1619 case OO_Slash: return BO_Div;
1620 case OO_Percent: return BO_Rem;
1621 case OO_Caret: return BO_Xor;
1622 case OO_Amp: return BO_And;
1623 case OO_Pipe: return BO_Or;
1624 case OO_Equal: return BO_Assign;
1625 case OO_Less: return BO_LT;
1626 case OO_Greater: return BO_GT;
1627 case OO_PlusEqual: return BO_AddAssign;
1628 case OO_MinusEqual: return BO_SubAssign;
1629 case OO_StarEqual: return BO_MulAssign;
1630 case OO_SlashEqual: return BO_DivAssign;
1631 case OO_PercentEqual: return BO_RemAssign;
1632 case OO_CaretEqual: return BO_XorAssign;
1633 case OO_AmpEqual: return BO_AndAssign;
1634 case OO_PipeEqual: return BO_OrAssign;
1635 case OO_LessLess: return BO_Shl;
1636 case OO_GreaterGreater: return BO_Shr;
1637 case OO_LessLessEqual: return BO_ShlAssign;
1638 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1639 case OO_EqualEqual: return BO_EQ;
1640 case OO_ExclaimEqual: return BO_NE;
1641 case OO_LessEqual: return BO_LE;
1642 case OO_GreaterEqual: return BO_GE;
1643 case OO_AmpAmp: return BO_LAnd;
1644 case OO_PipePipe: return BO_LOr;
1645 case OO_Comma: return BO_Comma;
1646 case OO_ArrowStar: return BO_PtrMemI;
1647 }
1648 }
1649
getOverloadedOperator(Opcode Opc)1650 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1651 static const OverloadedOperatorKind OverOps[] = {
1652 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1653 OO_Star, OO_Slash, OO_Percent,
1654 OO_Plus, OO_Minus,
1655 OO_LessLess, OO_GreaterGreater,
1656 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1657 OO_EqualEqual, OO_ExclaimEqual,
1658 OO_Amp,
1659 OO_Caret,
1660 OO_Pipe,
1661 OO_AmpAmp,
1662 OO_PipePipe,
1663 OO_Equal, OO_StarEqual,
1664 OO_SlashEqual, OO_PercentEqual,
1665 OO_PlusEqual, OO_MinusEqual,
1666 OO_LessLessEqual, OO_GreaterGreaterEqual,
1667 OO_AmpEqual, OO_CaretEqual,
1668 OO_PipeEqual,
1669 OO_Comma
1670 };
1671 return OverOps[Opc];
1672 }
1673
InitListExpr(ASTContext & C,SourceLocation lbraceloc,ArrayRef<Expr * > initExprs,SourceLocation rbraceloc)1674 InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
1675 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
1676 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1677 false, false),
1678 InitExprs(C, initExprs.size()),
1679 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0)
1680 {
1681 sawArrayRangeDesignator(false);
1682 setInitializesStdInitializerList(false);
1683 for (unsigned I = 0; I != initExprs.size(); ++I) {
1684 if (initExprs[I]->isTypeDependent())
1685 ExprBits.TypeDependent = true;
1686 if (initExprs[I]->isValueDependent())
1687 ExprBits.ValueDependent = true;
1688 if (initExprs[I]->isInstantiationDependent())
1689 ExprBits.InstantiationDependent = true;
1690 if (initExprs[I]->containsUnexpandedParameterPack())
1691 ExprBits.ContainsUnexpandedParameterPack = true;
1692 }
1693
1694 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
1695 }
1696
reserveInits(ASTContext & C,unsigned NumInits)1697 void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
1698 if (NumInits > InitExprs.size())
1699 InitExprs.reserve(C, NumInits);
1700 }
1701
resizeInits(ASTContext & C,unsigned NumInits)1702 void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
1703 InitExprs.resize(C, NumInits, 0);
1704 }
1705
updateInit(ASTContext & C,unsigned Init,Expr * expr)1706 Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
1707 if (Init >= InitExprs.size()) {
1708 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
1709 InitExprs.back() = expr;
1710 return 0;
1711 }
1712
1713 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1714 InitExprs[Init] = expr;
1715 return Result;
1716 }
1717
setArrayFiller(Expr * filler)1718 void InitListExpr::setArrayFiller(Expr *filler) {
1719 assert(!hasArrayFiller() && "Filler already set!");
1720 ArrayFillerOrUnionFieldInit = filler;
1721 // Fill out any "holes" in the array due to designated initializers.
1722 Expr **inits = getInits();
1723 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
1724 if (inits[i] == 0)
1725 inits[i] = filler;
1726 }
1727
isStringLiteralInit() const1728 bool InitListExpr::isStringLiteralInit() const {
1729 if (getNumInits() != 1)
1730 return false;
1731 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
1732 if (!AT || !AT->getElementType()->isIntegerType())
1733 return false;
1734 const Expr *Init = getInit(0)->IgnoreParens();
1735 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
1736 }
1737
getSourceRange() const1738 SourceRange InitListExpr::getSourceRange() const {
1739 if (SyntacticForm)
1740 return SyntacticForm->getSourceRange();
1741 SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1742 if (Beg.isInvalid()) {
1743 // Find the first non-null initializer.
1744 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1745 E = InitExprs.end();
1746 I != E; ++I) {
1747 if (Stmt *S = *I) {
1748 Beg = S->getLocStart();
1749 break;
1750 }
1751 }
1752 }
1753 if (End.isInvalid()) {
1754 // Find the first non-null initializer from the end.
1755 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1756 E = InitExprs.rend();
1757 I != E; ++I) {
1758 if (Stmt *S = *I) {
1759 End = S->getSourceRange().getEnd();
1760 break;
1761 }
1762 }
1763 }
1764 return SourceRange(Beg, End);
1765 }
1766
1767 /// getFunctionType - Return the underlying function type for this block.
1768 ///
getFunctionType() const1769 const FunctionProtoType *BlockExpr::getFunctionType() const {
1770 // The block pointer is never sugared, but the function type might be.
1771 return cast<BlockPointerType>(getType())
1772 ->getPointeeType()->castAs<FunctionProtoType>();
1773 }
1774
getCaretLocation() const1775 SourceLocation BlockExpr::getCaretLocation() const {
1776 return TheBlock->getCaretLocation();
1777 }
getBody() const1778 const Stmt *BlockExpr::getBody() const {
1779 return TheBlock->getBody();
1780 }
getBody()1781 Stmt *BlockExpr::getBody() {
1782 return TheBlock->getBody();
1783 }
1784
1785
1786 //===----------------------------------------------------------------------===//
1787 // Generic Expression Routines
1788 //===----------------------------------------------------------------------===//
1789
1790 /// isUnusedResultAWarning - Return true if this immediate expression should
1791 /// be warned about if the result is unused. If so, fill in Loc and Ranges
1792 /// with location to warn on and the source range[s] to report with the
1793 /// warning.
isUnusedResultAWarning(const Expr * & WarnE,SourceLocation & Loc,SourceRange & R1,SourceRange & R2,ASTContext & Ctx) const1794 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
1795 SourceRange &R1, SourceRange &R2,
1796 ASTContext &Ctx) const {
1797 // Don't warn if the expr is type dependent. The type could end up
1798 // instantiating to void.
1799 if (isTypeDependent())
1800 return false;
1801
1802 switch (getStmtClass()) {
1803 default:
1804 if (getType()->isVoidType())
1805 return false;
1806 WarnE = this;
1807 Loc = getExprLoc();
1808 R1 = getSourceRange();
1809 return true;
1810 case ParenExprClass:
1811 return cast<ParenExpr>(this)->getSubExpr()->
1812 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
1813 case GenericSelectionExprClass:
1814 return cast<GenericSelectionExpr>(this)->getResultExpr()->
1815 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
1816 case UnaryOperatorClass: {
1817 const UnaryOperator *UO = cast<UnaryOperator>(this);
1818
1819 switch (UO->getOpcode()) {
1820 case UO_Plus:
1821 case UO_Minus:
1822 case UO_AddrOf:
1823 case UO_Not:
1824 case UO_LNot:
1825 case UO_Deref:
1826 break;
1827 case UO_PostInc:
1828 case UO_PostDec:
1829 case UO_PreInc:
1830 case UO_PreDec: // ++/--
1831 return false; // Not a warning.
1832 case UO_Real:
1833 case UO_Imag:
1834 // accessing a piece of a volatile complex is a side-effect.
1835 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1836 .isVolatileQualified())
1837 return false;
1838 break;
1839 case UO_Extension:
1840 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
1841 }
1842 WarnE = this;
1843 Loc = UO->getOperatorLoc();
1844 R1 = UO->getSubExpr()->getSourceRange();
1845 return true;
1846 }
1847 case BinaryOperatorClass: {
1848 const BinaryOperator *BO = cast<BinaryOperator>(this);
1849 switch (BO->getOpcode()) {
1850 default:
1851 break;
1852 // Consider the RHS of comma for side effects. LHS was checked by
1853 // Sema::CheckCommaOperands.
1854 case BO_Comma:
1855 // ((foo = <blah>), 0) is an idiom for hiding the result (and
1856 // lvalue-ness) of an assignment written in a macro.
1857 if (IntegerLiteral *IE =
1858 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1859 if (IE->getValue() == 0)
1860 return false;
1861 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
1862 // Consider '||', '&&' to have side effects if the LHS or RHS does.
1863 case BO_LAnd:
1864 case BO_LOr:
1865 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
1866 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
1867 return false;
1868 break;
1869 }
1870 if (BO->isAssignmentOp())
1871 return false;
1872 WarnE = this;
1873 Loc = BO->getOperatorLoc();
1874 R1 = BO->getLHS()->getSourceRange();
1875 R2 = BO->getRHS()->getSourceRange();
1876 return true;
1877 }
1878 case CompoundAssignOperatorClass:
1879 case VAArgExprClass:
1880 case AtomicExprClass:
1881 return false;
1882
1883 case ConditionalOperatorClass: {
1884 // If only one of the LHS or RHS is a warning, the operator might
1885 // be being used for control flow. Only warn if both the LHS and
1886 // RHS are warnings.
1887 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
1888 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
1889 return false;
1890 if (!Exp->getLHS())
1891 return true;
1892 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
1893 }
1894
1895 case MemberExprClass:
1896 WarnE = this;
1897 Loc = cast<MemberExpr>(this)->getMemberLoc();
1898 R1 = SourceRange(Loc, Loc);
1899 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1900 return true;
1901
1902 case ArraySubscriptExprClass:
1903 WarnE = this;
1904 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1905 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1906 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1907 return true;
1908
1909 case CXXOperatorCallExprClass: {
1910 // We warn about operator== and operator!= even when user-defined operator
1911 // overloads as there is no reasonable way to define these such that they
1912 // have non-trivial, desirable side-effects. See the -Wunused-comparison
1913 // warning: these operators are commonly typo'ed, and so warning on them
1914 // provides additional value as well. If this list is updated,
1915 // DiagnoseUnusedComparison should be as well.
1916 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
1917 if (Op->getOperator() == OO_EqualEqual ||
1918 Op->getOperator() == OO_ExclaimEqual) {
1919 WarnE = this;
1920 Loc = Op->getOperatorLoc();
1921 R1 = Op->getSourceRange();
1922 return true;
1923 }
1924
1925 // Fallthrough for generic call handling.
1926 }
1927 case CallExprClass:
1928 case CXXMemberCallExprClass:
1929 case UserDefinedLiteralClass: {
1930 // If this is a direct call, get the callee.
1931 const CallExpr *CE = cast<CallExpr>(this);
1932 if (const Decl *FD = CE->getCalleeDecl()) {
1933 // If the callee has attribute pure, const, or warn_unused_result, warn
1934 // about it. void foo() { strlen("bar"); } should warn.
1935 //
1936 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1937 // updated to match for QoI.
1938 if (FD->getAttr<WarnUnusedResultAttr>() ||
1939 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
1940 WarnE = this;
1941 Loc = CE->getCallee()->getLocStart();
1942 R1 = CE->getCallee()->getSourceRange();
1943
1944 if (unsigned NumArgs = CE->getNumArgs())
1945 R2 = SourceRange(CE->getArg(0)->getLocStart(),
1946 CE->getArg(NumArgs-1)->getLocEnd());
1947 return true;
1948 }
1949 }
1950 return false;
1951 }
1952
1953 case CXXTemporaryObjectExprClass:
1954 case CXXConstructExprClass:
1955 return false;
1956
1957 case ObjCMessageExprClass: {
1958 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
1959 if (Ctx.getLangOpts().ObjCAutoRefCount &&
1960 ME->isInstanceMessage() &&
1961 !ME->getType()->isVoidType() &&
1962 ME->getSelector().getIdentifierInfoForSlot(0) &&
1963 ME->getSelector().getIdentifierInfoForSlot(0)
1964 ->getName().startswith("init")) {
1965 WarnE = this;
1966 Loc = getExprLoc();
1967 R1 = ME->getSourceRange();
1968 return true;
1969 }
1970
1971 const ObjCMethodDecl *MD = ME->getMethodDecl();
1972 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
1973 WarnE = this;
1974 Loc = getExprLoc();
1975 return true;
1976 }
1977 return false;
1978 }
1979
1980 case ObjCPropertyRefExprClass:
1981 WarnE = this;
1982 Loc = getExprLoc();
1983 R1 = getSourceRange();
1984 return true;
1985
1986 case PseudoObjectExprClass: {
1987 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
1988
1989 // Only complain about things that have the form of a getter.
1990 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
1991 isa<BinaryOperator>(PO->getSyntacticForm()))
1992 return false;
1993
1994 WarnE = this;
1995 Loc = getExprLoc();
1996 R1 = getSourceRange();
1997 return true;
1998 }
1999
2000 case StmtExprClass: {
2001 // Statement exprs don't logically have side effects themselves, but are
2002 // sometimes used in macros in ways that give them a type that is unused.
2003 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2004 // however, if the result of the stmt expr is dead, we don't want to emit a
2005 // warning.
2006 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2007 if (!CS->body_empty()) {
2008 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2009 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2010 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2011 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2012 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2013 }
2014
2015 if (getType()->isVoidType())
2016 return false;
2017 WarnE = this;
2018 Loc = cast<StmtExpr>(this)->getLParenLoc();
2019 R1 = getSourceRange();
2020 return true;
2021 }
2022 case CStyleCastExprClass: {
2023 // Ignore an explicit cast to void unless the operand is a non-trivial
2024 // volatile lvalue.
2025 const CastExpr *CE = cast<CastExpr>(this);
2026 if (CE->getCastKind() == CK_ToVoid) {
2027 if (CE->getSubExpr()->isGLValue() &&
2028 CE->getSubExpr()->getType().isVolatileQualified()) {
2029 const DeclRefExpr *DRE =
2030 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2031 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2032 cast<VarDecl>(DRE->getDecl())->hasLocalStorage())) {
2033 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2034 R1, R2, Ctx);
2035 }
2036 }
2037 return false;
2038 }
2039
2040 // If this is a cast to a constructor conversion, check the operand.
2041 // Otherwise, the result of the cast is unused.
2042 if (CE->getCastKind() == CK_ConstructorConversion)
2043 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2044
2045 WarnE = this;
2046 if (const CXXFunctionalCastExpr *CXXCE =
2047 dyn_cast<CXXFunctionalCastExpr>(this)) {
2048 Loc = CXXCE->getTypeBeginLoc();
2049 R1 = CXXCE->getSubExpr()->getSourceRange();
2050 } else {
2051 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2052 Loc = CStyleCE->getLParenLoc();
2053 R1 = CStyleCE->getSubExpr()->getSourceRange();
2054 }
2055 return true;
2056 }
2057 case ImplicitCastExprClass: {
2058 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2059
2060 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2061 if (ICE->getCastKind() == CK_LValueToRValue &&
2062 ICE->getSubExpr()->getType().isVolatileQualified())
2063 return false;
2064
2065 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2066 }
2067 case CXXDefaultArgExprClass:
2068 return (cast<CXXDefaultArgExpr>(this)
2069 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2070
2071 case CXXNewExprClass:
2072 // FIXME: In theory, there might be new expressions that don't have side
2073 // effects (e.g. a placement new with an uninitialized POD).
2074 case CXXDeleteExprClass:
2075 return false;
2076 case CXXBindTemporaryExprClass:
2077 return (cast<CXXBindTemporaryExpr>(this)
2078 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2079 case ExprWithCleanupsClass:
2080 return (cast<ExprWithCleanups>(this)
2081 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2082 }
2083 }
2084
2085 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2086 /// returns true, if it is; false otherwise.
isOBJCGCCandidate(ASTContext & Ctx) const2087 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2088 const Expr *E = IgnoreParens();
2089 switch (E->getStmtClass()) {
2090 default:
2091 return false;
2092 case ObjCIvarRefExprClass:
2093 return true;
2094 case Expr::UnaryOperatorClass:
2095 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2096 case ImplicitCastExprClass:
2097 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2098 case MaterializeTemporaryExprClass:
2099 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2100 ->isOBJCGCCandidate(Ctx);
2101 case CStyleCastExprClass:
2102 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2103 case DeclRefExprClass: {
2104 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2105
2106 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2107 if (VD->hasGlobalStorage())
2108 return true;
2109 QualType T = VD->getType();
2110 // dereferencing to a pointer is always a gc'able candidate,
2111 // unless it is __weak.
2112 return T->isPointerType() &&
2113 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2114 }
2115 return false;
2116 }
2117 case MemberExprClass: {
2118 const MemberExpr *M = cast<MemberExpr>(E);
2119 return M->getBase()->isOBJCGCCandidate(Ctx);
2120 }
2121 case ArraySubscriptExprClass:
2122 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2123 }
2124 }
2125
isBoundMemberFunction(ASTContext & Ctx) const2126 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2127 if (isTypeDependent())
2128 return false;
2129 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2130 }
2131
findBoundMemberType(const Expr * expr)2132 QualType Expr::findBoundMemberType(const Expr *expr) {
2133 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2134
2135 // Bound member expressions are always one of these possibilities:
2136 // x->m x.m x->*y x.*y
2137 // (possibly parenthesized)
2138
2139 expr = expr->IgnoreParens();
2140 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2141 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2142 return mem->getMemberDecl()->getType();
2143 }
2144
2145 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2146 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2147 ->getPointeeType();
2148 assert(type->isFunctionType());
2149 return type;
2150 }
2151
2152 assert(isa<UnresolvedMemberExpr>(expr));
2153 return QualType();
2154 }
2155
IgnoreParens()2156 Expr* Expr::IgnoreParens() {
2157 Expr* E = this;
2158 while (true) {
2159 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2160 E = P->getSubExpr();
2161 continue;
2162 }
2163 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2164 if (P->getOpcode() == UO_Extension) {
2165 E = P->getSubExpr();
2166 continue;
2167 }
2168 }
2169 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2170 if (!P->isResultDependent()) {
2171 E = P->getResultExpr();
2172 continue;
2173 }
2174 }
2175 return E;
2176 }
2177 }
2178
2179 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2180 /// or CastExprs or ImplicitCastExprs, returning their operand.
IgnoreParenCasts()2181 Expr *Expr::IgnoreParenCasts() {
2182 Expr *E = this;
2183 while (true) {
2184 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2185 E = P->getSubExpr();
2186 continue;
2187 }
2188 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2189 E = P->getSubExpr();
2190 continue;
2191 }
2192 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2193 if (P->getOpcode() == UO_Extension) {
2194 E = P->getSubExpr();
2195 continue;
2196 }
2197 }
2198 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2199 if (!P->isResultDependent()) {
2200 E = P->getResultExpr();
2201 continue;
2202 }
2203 }
2204 if (MaterializeTemporaryExpr *Materialize
2205 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2206 E = Materialize->GetTemporaryExpr();
2207 continue;
2208 }
2209 if (SubstNonTypeTemplateParmExpr *NTTP
2210 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2211 E = NTTP->getReplacement();
2212 continue;
2213 }
2214 return E;
2215 }
2216 }
2217
2218 /// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2219 /// casts. This is intended purely as a temporary workaround for code
2220 /// that hasn't yet been rewritten to do the right thing about those
2221 /// casts, and may disappear along with the last internal use.
IgnoreParenLValueCasts()2222 Expr *Expr::IgnoreParenLValueCasts() {
2223 Expr *E = this;
2224 while (true) {
2225 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2226 E = P->getSubExpr();
2227 continue;
2228 } else if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2229 if (P->getCastKind() == CK_LValueToRValue) {
2230 E = P->getSubExpr();
2231 continue;
2232 }
2233 } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2234 if (P->getOpcode() == UO_Extension) {
2235 E = P->getSubExpr();
2236 continue;
2237 }
2238 } else if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2239 if (!P->isResultDependent()) {
2240 E = P->getResultExpr();
2241 continue;
2242 }
2243 } else if (MaterializeTemporaryExpr *Materialize
2244 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2245 E = Materialize->GetTemporaryExpr();
2246 continue;
2247 } else if (SubstNonTypeTemplateParmExpr *NTTP
2248 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2249 E = NTTP->getReplacement();
2250 continue;
2251 }
2252 break;
2253 }
2254 return E;
2255 }
2256
ignoreParenBaseCasts()2257 Expr *Expr::ignoreParenBaseCasts() {
2258 Expr *E = this;
2259 while (true) {
2260 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2261 E = P->getSubExpr();
2262 continue;
2263 }
2264 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2265 if (CE->getCastKind() == CK_DerivedToBase ||
2266 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2267 CE->getCastKind() == CK_NoOp) {
2268 E = CE->getSubExpr();
2269 continue;
2270 }
2271 }
2272
2273 return E;
2274 }
2275 }
2276
IgnoreParenImpCasts()2277 Expr *Expr::IgnoreParenImpCasts() {
2278 Expr *E = this;
2279 while (true) {
2280 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2281 E = P->getSubExpr();
2282 continue;
2283 }
2284 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
2285 E = P->getSubExpr();
2286 continue;
2287 }
2288 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2289 if (P->getOpcode() == UO_Extension) {
2290 E = P->getSubExpr();
2291 continue;
2292 }
2293 }
2294 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2295 if (!P->isResultDependent()) {
2296 E = P->getResultExpr();
2297 continue;
2298 }
2299 }
2300 if (MaterializeTemporaryExpr *Materialize
2301 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2302 E = Materialize->GetTemporaryExpr();
2303 continue;
2304 }
2305 if (SubstNonTypeTemplateParmExpr *NTTP
2306 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2307 E = NTTP->getReplacement();
2308 continue;
2309 }
2310 return E;
2311 }
2312 }
2313
IgnoreConversionOperator()2314 Expr *Expr::IgnoreConversionOperator() {
2315 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2316 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2317 return MCE->getImplicitObjectArgument();
2318 }
2319 return this;
2320 }
2321
2322 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2323 /// value (including ptr->int casts of the same size). Strip off any
2324 /// ParenExpr or CastExprs, returning their operand.
IgnoreParenNoopCasts(ASTContext & Ctx)2325 Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2326 Expr *E = this;
2327 while (true) {
2328 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2329 E = P->getSubExpr();
2330 continue;
2331 }
2332
2333 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2334 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2335 // ptr<->int casts of the same width. We also ignore all identity casts.
2336 Expr *SE = P->getSubExpr();
2337
2338 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2339 E = SE;
2340 continue;
2341 }
2342
2343 if ((E->getType()->isPointerType() ||
2344 E->getType()->isIntegralType(Ctx)) &&
2345 (SE->getType()->isPointerType() ||
2346 SE->getType()->isIntegralType(Ctx)) &&
2347 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2348 E = SE;
2349 continue;
2350 }
2351 }
2352
2353 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2354 if (P->getOpcode() == UO_Extension) {
2355 E = P->getSubExpr();
2356 continue;
2357 }
2358 }
2359
2360 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2361 if (!P->isResultDependent()) {
2362 E = P->getResultExpr();
2363 continue;
2364 }
2365 }
2366
2367 if (SubstNonTypeTemplateParmExpr *NTTP
2368 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2369 E = NTTP->getReplacement();
2370 continue;
2371 }
2372
2373 return E;
2374 }
2375 }
2376
isDefaultArgument() const2377 bool Expr::isDefaultArgument() const {
2378 const Expr *E = this;
2379 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2380 E = M->GetTemporaryExpr();
2381
2382 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2383 E = ICE->getSubExprAsWritten();
2384
2385 return isa<CXXDefaultArgExpr>(E);
2386 }
2387
2388 /// \brief Skip over any no-op casts and any temporary-binding
2389 /// expressions.
skipTemporaryBindingsNoOpCastsAndParens(const Expr * E)2390 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
2391 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2392 E = M->GetTemporaryExpr();
2393
2394 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2395 if (ICE->getCastKind() == CK_NoOp)
2396 E = ICE->getSubExpr();
2397 else
2398 break;
2399 }
2400
2401 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2402 E = BE->getSubExpr();
2403
2404 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2405 if (ICE->getCastKind() == CK_NoOp)
2406 E = ICE->getSubExpr();
2407 else
2408 break;
2409 }
2410
2411 return E->IgnoreParens();
2412 }
2413
2414 /// isTemporaryObject - Determines if this expression produces a
2415 /// temporary of the given class type.
isTemporaryObject(ASTContext & C,const CXXRecordDecl * TempTy) const2416 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2417 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2418 return false;
2419
2420 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
2421
2422 // Temporaries are by definition pr-values of class type.
2423 if (!E->Classify(C).isPRValue()) {
2424 // In this context, property reference is a message call and is pr-value.
2425 if (!isa<ObjCPropertyRefExpr>(E))
2426 return false;
2427 }
2428
2429 // Black-list a few cases which yield pr-values of class type that don't
2430 // refer to temporaries of that type:
2431
2432 // - implicit derived-to-base conversions
2433 if (isa<ImplicitCastExpr>(E)) {
2434 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2435 case CK_DerivedToBase:
2436 case CK_UncheckedDerivedToBase:
2437 return false;
2438 default:
2439 break;
2440 }
2441 }
2442
2443 // - member expressions (all)
2444 if (isa<MemberExpr>(E))
2445 return false;
2446
2447 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2448 if (BO->isPtrMemOp())
2449 return false;
2450
2451 // - opaque values (all)
2452 if (isa<OpaqueValueExpr>(E))
2453 return false;
2454
2455 return true;
2456 }
2457
isImplicitCXXThis() const2458 bool Expr::isImplicitCXXThis() const {
2459 const Expr *E = this;
2460
2461 // Strip away parentheses and casts we don't care about.
2462 while (true) {
2463 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2464 E = Paren->getSubExpr();
2465 continue;
2466 }
2467
2468 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2469 if (ICE->getCastKind() == CK_NoOp ||
2470 ICE->getCastKind() == CK_LValueToRValue ||
2471 ICE->getCastKind() == CK_DerivedToBase ||
2472 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2473 E = ICE->getSubExpr();
2474 continue;
2475 }
2476 }
2477
2478 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2479 if (UnOp->getOpcode() == UO_Extension) {
2480 E = UnOp->getSubExpr();
2481 continue;
2482 }
2483 }
2484
2485 if (const MaterializeTemporaryExpr *M
2486 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2487 E = M->GetTemporaryExpr();
2488 continue;
2489 }
2490
2491 break;
2492 }
2493
2494 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2495 return This->isImplicit();
2496
2497 return false;
2498 }
2499
2500 /// hasAnyTypeDependentArguments - Determines if any of the expressions
2501 /// in Exprs is type-dependent.
hasAnyTypeDependentArguments(llvm::ArrayRef<Expr * > Exprs)2502 bool Expr::hasAnyTypeDependentArguments(llvm::ArrayRef<Expr *> Exprs) {
2503 for (unsigned I = 0; I < Exprs.size(); ++I)
2504 if (Exprs[I]->isTypeDependent())
2505 return true;
2506
2507 return false;
2508 }
2509
isConstantInitializer(ASTContext & Ctx,bool IsForRef) const2510 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
2511 // This function is attempting whether an expression is an initializer
2512 // which can be evaluated at compile-time. isEvaluatable handles most
2513 // of the cases, but it can't deal with some initializer-specific
2514 // expressions, and it can't deal with aggregates; we deal with those here,
2515 // and fall back to isEvaluatable for the other cases.
2516
2517 // If we ever capture reference-binding directly in the AST, we can
2518 // kill the second parameter.
2519
2520 if (IsForRef) {
2521 EvalResult Result;
2522 return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
2523 }
2524
2525 switch (getStmtClass()) {
2526 default: break;
2527 case IntegerLiteralClass:
2528 case FloatingLiteralClass:
2529 case StringLiteralClass:
2530 case ObjCStringLiteralClass:
2531 case ObjCEncodeExprClass:
2532 return true;
2533 case CXXTemporaryObjectExprClass:
2534 case CXXConstructExprClass: {
2535 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2536
2537 // Only if it's
2538 if (CE->getConstructor()->isTrivial()) {
2539 // 1) an application of the trivial default constructor or
2540 if (!CE->getNumArgs()) return true;
2541
2542 // 2) an elidable trivial copy construction of an operand which is
2543 // itself a constant initializer. Note that we consider the
2544 // operand on its own, *not* as a reference binding.
2545 if (CE->isElidable() &&
2546 CE->getArg(0)->isConstantInitializer(Ctx, false))
2547 return true;
2548 }
2549
2550 // 3) a foldable constexpr constructor.
2551 break;
2552 }
2553 case CompoundLiteralExprClass: {
2554 // This handles gcc's extension that allows global initializers like
2555 // "struct x {int x;} x = (struct x) {};".
2556 // FIXME: This accepts other cases it shouldn't!
2557 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2558 return Exp->isConstantInitializer(Ctx, false);
2559 }
2560 case InitListExprClass: {
2561 // FIXME: This doesn't deal with fields with reference types correctly.
2562 // FIXME: This incorrectly allows pointers cast to integers to be assigned
2563 // to bitfields.
2564 const InitListExpr *Exp = cast<InitListExpr>(this);
2565 unsigned numInits = Exp->getNumInits();
2566 for (unsigned i = 0; i < numInits; i++) {
2567 if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
2568 return false;
2569 }
2570 return true;
2571 }
2572 case ImplicitValueInitExprClass:
2573 return true;
2574 case ParenExprClass:
2575 return cast<ParenExpr>(this)->getSubExpr()
2576 ->isConstantInitializer(Ctx, IsForRef);
2577 case GenericSelectionExprClass:
2578 if (cast<GenericSelectionExpr>(this)->isResultDependent())
2579 return false;
2580 return cast<GenericSelectionExpr>(this)->getResultExpr()
2581 ->isConstantInitializer(Ctx, IsForRef);
2582 case ChooseExprClass:
2583 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
2584 ->isConstantInitializer(Ctx, IsForRef);
2585 case UnaryOperatorClass: {
2586 const UnaryOperator* Exp = cast<UnaryOperator>(this);
2587 if (Exp->getOpcode() == UO_Extension)
2588 return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
2589 break;
2590 }
2591 case CXXFunctionalCastExprClass:
2592 case CXXStaticCastExprClass:
2593 case ImplicitCastExprClass:
2594 case CStyleCastExprClass: {
2595 const CastExpr *CE = cast<CastExpr>(this);
2596
2597 // If we're promoting an integer to an _Atomic type then this is constant
2598 // if the integer is constant. We also need to check the converse in case
2599 // someone does something like:
2600 //
2601 // int a = (_Atomic(int))42;
2602 //
2603 // I doubt anyone would write code like this directly, but it's quite
2604 // possible as the result of macro expansions.
2605 if (CE->getCastKind() == CK_NonAtomicToAtomic ||
2606 CE->getCastKind() == CK_AtomicToNonAtomic)
2607 return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2608
2609 // Handle bitcasts of vector constants.
2610 if (getType()->isVectorType() && CE->getCastKind() == CK_BitCast)
2611 return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2612
2613 // Handle misc casts we want to ignore.
2614 // FIXME: Is it really safe to ignore all these?
2615 if (CE->getCastKind() == CK_NoOp ||
2616 CE->getCastKind() == CK_LValueToRValue ||
2617 CE->getCastKind() == CK_ToUnion ||
2618 CE->getCastKind() == CK_ConstructorConversion)
2619 return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2620
2621 break;
2622 }
2623 case MaterializeTemporaryExprClass:
2624 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2625 ->isConstantInitializer(Ctx, false);
2626 }
2627 return isEvaluatable(Ctx);
2628 }
2629
HasSideEffects(const ASTContext & Ctx) const2630 bool Expr::HasSideEffects(const ASTContext &Ctx) const {
2631 if (isInstantiationDependent())
2632 return true;
2633
2634 switch (getStmtClass()) {
2635 case NoStmtClass:
2636 #define ABSTRACT_STMT(Type)
2637 #define STMT(Type, Base) case Type##Class:
2638 #define EXPR(Type, Base)
2639 #include "clang/AST/StmtNodes.inc"
2640 llvm_unreachable("unexpected Expr kind");
2641
2642 case DependentScopeDeclRefExprClass:
2643 case CXXUnresolvedConstructExprClass:
2644 case CXXDependentScopeMemberExprClass:
2645 case UnresolvedLookupExprClass:
2646 case UnresolvedMemberExprClass:
2647 case PackExpansionExprClass:
2648 case SubstNonTypeTemplateParmPackExprClass:
2649 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
2650
2651 case DeclRefExprClass:
2652 case ObjCIvarRefExprClass:
2653 case PredefinedExprClass:
2654 case IntegerLiteralClass:
2655 case FloatingLiteralClass:
2656 case ImaginaryLiteralClass:
2657 case StringLiteralClass:
2658 case CharacterLiteralClass:
2659 case OffsetOfExprClass:
2660 case ImplicitValueInitExprClass:
2661 case UnaryExprOrTypeTraitExprClass:
2662 case AddrLabelExprClass:
2663 case GNUNullExprClass:
2664 case CXXBoolLiteralExprClass:
2665 case CXXNullPtrLiteralExprClass:
2666 case CXXThisExprClass:
2667 case CXXScalarValueInitExprClass:
2668 case TypeTraitExprClass:
2669 case UnaryTypeTraitExprClass:
2670 case BinaryTypeTraitExprClass:
2671 case ArrayTypeTraitExprClass:
2672 case ExpressionTraitExprClass:
2673 case CXXNoexceptExprClass:
2674 case SizeOfPackExprClass:
2675 case ObjCStringLiteralClass:
2676 case ObjCEncodeExprClass:
2677 case ObjCBoolLiteralExprClass:
2678 case CXXUuidofExprClass:
2679 case OpaqueValueExprClass:
2680 // These never have a side-effect.
2681 return false;
2682
2683 case CallExprClass:
2684 case CompoundAssignOperatorClass:
2685 case VAArgExprClass:
2686 case AtomicExprClass:
2687 case StmtExprClass:
2688 case CXXOperatorCallExprClass:
2689 case CXXMemberCallExprClass:
2690 case UserDefinedLiteralClass:
2691 case CXXThrowExprClass:
2692 case CXXNewExprClass:
2693 case CXXDeleteExprClass:
2694 case ExprWithCleanupsClass:
2695 case CXXBindTemporaryExprClass:
2696 case BlockExprClass:
2697 case CUDAKernelCallExprClass:
2698 // These always have a side-effect.
2699 return true;
2700
2701 case ParenExprClass:
2702 case ArraySubscriptExprClass:
2703 case MemberExprClass:
2704 case ConditionalOperatorClass:
2705 case BinaryConditionalOperatorClass:
2706 case CompoundLiteralExprClass:
2707 case ExtVectorElementExprClass:
2708 case DesignatedInitExprClass:
2709 case ParenListExprClass:
2710 case CXXPseudoDestructorExprClass:
2711 case SubstNonTypeTemplateParmExprClass:
2712 case MaterializeTemporaryExprClass:
2713 case ShuffleVectorExprClass:
2714 case AsTypeExprClass:
2715 // These have a side-effect if any subexpression does.
2716 break;
2717
2718 case UnaryOperatorClass:
2719 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
2720 return true;
2721 break;
2722
2723 case BinaryOperatorClass:
2724 if (cast<BinaryOperator>(this)->isAssignmentOp())
2725 return true;
2726 break;
2727
2728 case InitListExprClass:
2729 // FIXME: The children for an InitListExpr doesn't include the array filler.
2730 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
2731 if (E->HasSideEffects(Ctx))
2732 return true;
2733 break;
2734
2735 case GenericSelectionExprClass:
2736 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2737 HasSideEffects(Ctx);
2738
2739 case ChooseExprClass:
2740 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)->HasSideEffects(Ctx);
2741
2742 case CXXDefaultArgExprClass:
2743 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(Ctx);
2744
2745 case CXXDynamicCastExprClass: {
2746 // A dynamic_cast expression has side-effects if it can throw.
2747 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
2748 if (DCE->getTypeAsWritten()->isReferenceType() &&
2749 DCE->getCastKind() == CK_Dynamic)
2750 return true;
2751 } // Fall through.
2752 case ImplicitCastExprClass:
2753 case CStyleCastExprClass:
2754 case CXXStaticCastExprClass:
2755 case CXXReinterpretCastExprClass:
2756 case CXXConstCastExprClass:
2757 case CXXFunctionalCastExprClass: {
2758 const CastExpr *CE = cast<CastExpr>(this);
2759 if (CE->getCastKind() == CK_LValueToRValue &&
2760 CE->getSubExpr()->getType().isVolatileQualified())
2761 return true;
2762 break;
2763 }
2764
2765 case CXXTypeidExprClass:
2766 // typeid might throw if its subexpression is potentially-evaluated, so has
2767 // side-effects in that case whether or not its subexpression does.
2768 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
2769
2770 case CXXConstructExprClass:
2771 case CXXTemporaryObjectExprClass: {
2772 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2773 if (!CE->getConstructor()->isTrivial())
2774 return true;
2775 // A trivial constructor does not add any side-effects of its own. Just look
2776 // at its arguments.
2777 break;
2778 }
2779
2780 case LambdaExprClass: {
2781 const LambdaExpr *LE = cast<LambdaExpr>(this);
2782 for (LambdaExpr::capture_iterator I = LE->capture_begin(),
2783 E = LE->capture_end(); I != E; ++I)
2784 if (I->getCaptureKind() == LCK_ByCopy)
2785 // FIXME: Only has a side-effect if the variable is volatile or if
2786 // the copy would invoke a non-trivial copy constructor.
2787 return true;
2788 return false;
2789 }
2790
2791 case PseudoObjectExprClass: {
2792 // Only look for side-effects in the semantic form, and look past
2793 // OpaqueValueExpr bindings in that form.
2794 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2795 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
2796 E = PO->semantics_end();
2797 I != E; ++I) {
2798 const Expr *Subexpr = *I;
2799 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
2800 Subexpr = OVE->getSourceExpr();
2801 if (Subexpr->HasSideEffects(Ctx))
2802 return true;
2803 }
2804 return false;
2805 }
2806
2807 case ObjCBoxedExprClass:
2808 case ObjCArrayLiteralClass:
2809 case ObjCDictionaryLiteralClass:
2810 case ObjCMessageExprClass:
2811 case ObjCSelectorExprClass:
2812 case ObjCProtocolExprClass:
2813 case ObjCPropertyRefExprClass:
2814 case ObjCIsaExprClass:
2815 case ObjCIndirectCopyRestoreExprClass:
2816 case ObjCSubscriptRefExprClass:
2817 case ObjCBridgedCastExprClass:
2818 // FIXME: Classify these cases better.
2819 return true;
2820 }
2821
2822 // Recurse to children.
2823 for (const_child_range SubStmts = children(); SubStmts; ++SubStmts)
2824 if (const Stmt *S = *SubStmts)
2825 if (cast<Expr>(S)->HasSideEffects(Ctx))
2826 return true;
2827
2828 return false;
2829 }
2830
2831 namespace {
2832 /// \brief Look for a call to a non-trivial function within an expression.
2833 class NonTrivialCallFinder : public EvaluatedExprVisitor<NonTrivialCallFinder>
2834 {
2835 typedef EvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
2836
2837 bool NonTrivial;
2838
2839 public:
NonTrivialCallFinder(ASTContext & Context)2840 explicit NonTrivialCallFinder(ASTContext &Context)
2841 : Inherited(Context), NonTrivial(false) { }
2842
hasNonTrivialCall() const2843 bool hasNonTrivialCall() const { return NonTrivial; }
2844
VisitCallExpr(CallExpr * E)2845 void VisitCallExpr(CallExpr *E) {
2846 if (CXXMethodDecl *Method
2847 = dyn_cast_or_null<CXXMethodDecl>(E->getCalleeDecl())) {
2848 if (Method->isTrivial()) {
2849 // Recurse to children of the call.
2850 Inherited::VisitStmt(E);
2851 return;
2852 }
2853 }
2854
2855 NonTrivial = true;
2856 }
2857
VisitCXXConstructExpr(CXXConstructExpr * E)2858 void VisitCXXConstructExpr(CXXConstructExpr *E) {
2859 if (E->getConstructor()->isTrivial()) {
2860 // Recurse to children of the call.
2861 Inherited::VisitStmt(E);
2862 return;
2863 }
2864
2865 NonTrivial = true;
2866 }
2867
VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr * E)2868 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2869 if (E->getTemporary()->getDestructor()->isTrivial()) {
2870 Inherited::VisitStmt(E);
2871 return;
2872 }
2873
2874 NonTrivial = true;
2875 }
2876 };
2877 }
2878
hasNonTrivialCall(ASTContext & Ctx)2879 bool Expr::hasNonTrivialCall(ASTContext &Ctx) {
2880 NonTrivialCallFinder Finder(Ctx);
2881 Finder.Visit(this);
2882 return Finder.hasNonTrivialCall();
2883 }
2884
2885 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
2886 /// pointer constant or not, as well as the specific kind of constant detected.
2887 /// Null pointer constants can be integer constant expressions with the
2888 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
2889 /// (a GNU extension).
2890 Expr::NullPointerConstantKind
isNullPointerConstant(ASTContext & Ctx,NullPointerConstantValueDependence NPC) const2891 Expr::isNullPointerConstant(ASTContext &Ctx,
2892 NullPointerConstantValueDependence NPC) const {
2893 if (isValueDependent()) {
2894 switch (NPC) {
2895 case NPC_NeverValueDependent:
2896 llvm_unreachable("Unexpected value dependent expression!");
2897 case NPC_ValueDependentIsNull:
2898 if (isTypeDependent() || getType()->isIntegralType(Ctx))
2899 return NPCK_ZeroExpression;
2900 else
2901 return NPCK_NotNull;
2902
2903 case NPC_ValueDependentIsNotNull:
2904 return NPCK_NotNull;
2905 }
2906 }
2907
2908 // Strip off a cast to void*, if it exists. Except in C++.
2909 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
2910 if (!Ctx.getLangOpts().CPlusPlus) {
2911 // Check that it is a cast to void*.
2912 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
2913 QualType Pointee = PT->getPointeeType();
2914 if (!Pointee.hasQualifiers() &&
2915 Pointee->isVoidType() && // to void*
2916 CE->getSubExpr()->getType()->isIntegerType()) // from int.
2917 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2918 }
2919 }
2920 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2921 // Ignore the ImplicitCastExpr type entirely.
2922 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2923 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2924 // Accept ((void*)0) as a null pointer constant, as many other
2925 // implementations do.
2926 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2927 } else if (const GenericSelectionExpr *GE =
2928 dyn_cast<GenericSelectionExpr>(this)) {
2929 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
2930 } else if (const CXXDefaultArgExpr *DefaultArg
2931 = dyn_cast<CXXDefaultArgExpr>(this)) {
2932 // See through default argument expressions
2933 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
2934 } else if (isa<GNUNullExpr>(this)) {
2935 // The GNU __null extension is always a null pointer constant.
2936 return NPCK_GNUNull;
2937 } else if (const MaterializeTemporaryExpr *M
2938 = dyn_cast<MaterializeTemporaryExpr>(this)) {
2939 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
2940 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
2941 if (const Expr *Source = OVE->getSourceExpr())
2942 return Source->isNullPointerConstant(Ctx, NPC);
2943 }
2944
2945 // C++0x nullptr_t is always a null pointer constant.
2946 if (getType()->isNullPtrType())
2947 return NPCK_CXX0X_nullptr;
2948
2949 if (const RecordType *UT = getType()->getAsUnionType())
2950 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2951 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2952 const Expr *InitExpr = CLE->getInitializer();
2953 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2954 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2955 }
2956 // This expression must be an integer type.
2957 if (!getType()->isIntegerType() ||
2958 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
2959 return NPCK_NotNull;
2960
2961 // If we have an integer constant expression, we need to *evaluate* it and
2962 // test for the value 0. Don't use the C++11 constant expression semantics
2963 // for this, for now; once the dust settles on core issue 903, we might only
2964 // allow a literal 0 here in C++11 mode.
2965 if (Ctx.getLangOpts().CPlusPlus0x) {
2966 if (!isCXX98IntegralConstantExpr(Ctx))
2967 return NPCK_NotNull;
2968 } else {
2969 if (!isIntegerConstantExpr(Ctx))
2970 return NPCK_NotNull;
2971 }
2972
2973 if (EvaluateKnownConstInt(Ctx) != 0)
2974 return NPCK_NotNull;
2975
2976 if (isa<IntegerLiteral>(this))
2977 return NPCK_ZeroLiteral;
2978 return NPCK_ZeroExpression;
2979 }
2980
2981 /// \brief If this expression is an l-value for an Objective C
2982 /// property, find the underlying property reference expression.
getObjCProperty() const2983 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
2984 const Expr *E = this;
2985 while (true) {
2986 assert((E->getValueKind() == VK_LValue &&
2987 E->getObjectKind() == OK_ObjCProperty) &&
2988 "expression is not a property reference");
2989 E = E->IgnoreParenCasts();
2990 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2991 if (BO->getOpcode() == BO_Comma) {
2992 E = BO->getRHS();
2993 continue;
2994 }
2995 }
2996
2997 break;
2998 }
2999
3000 return cast<ObjCPropertyRefExpr>(E);
3001 }
3002
getBitField()3003 FieldDecl *Expr::getBitField() {
3004 Expr *E = this->IgnoreParens();
3005
3006 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3007 if (ICE->getCastKind() == CK_LValueToRValue ||
3008 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
3009 E = ICE->getSubExpr()->IgnoreParens();
3010 else
3011 break;
3012 }
3013
3014 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3015 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3016 if (Field->isBitField())
3017 return Field;
3018
3019 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
3020 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3021 if (Field->isBitField())
3022 return Field;
3023
3024 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3025 if (BinOp->isAssignmentOp() && BinOp->getLHS())
3026 return BinOp->getLHS()->getBitField();
3027
3028 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3029 return BinOp->getRHS()->getBitField();
3030 }
3031
3032 return 0;
3033 }
3034
refersToVectorElement() const3035 bool Expr::refersToVectorElement() const {
3036 const Expr *E = this->IgnoreParens();
3037
3038 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3039 if (ICE->getValueKind() != VK_RValue &&
3040 ICE->getCastKind() == CK_NoOp)
3041 E = ICE->getSubExpr()->IgnoreParens();
3042 else
3043 break;
3044 }
3045
3046 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3047 return ASE->getBase()->getType()->isVectorType();
3048
3049 if (isa<ExtVectorElementExpr>(E))
3050 return true;
3051
3052 return false;
3053 }
3054
3055 /// isArrow - Return true if the base expression is a pointer to vector,
3056 /// return false if the base expression is a vector.
isArrow() const3057 bool ExtVectorElementExpr::isArrow() const {
3058 return getBase()->getType()->isPointerType();
3059 }
3060
getNumElements() const3061 unsigned ExtVectorElementExpr::getNumElements() const {
3062 if (const VectorType *VT = getType()->getAs<VectorType>())
3063 return VT->getNumElements();
3064 return 1;
3065 }
3066
3067 /// containsDuplicateElements - Return true if any element access is repeated.
containsDuplicateElements() const3068 bool ExtVectorElementExpr::containsDuplicateElements() const {
3069 // FIXME: Refactor this code to an accessor on the AST node which returns the
3070 // "type" of component access, and share with code below and in Sema.
3071 StringRef Comp = Accessor->getName();
3072
3073 // Halving swizzles do not contain duplicate elements.
3074 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
3075 return false;
3076
3077 // Advance past s-char prefix on hex swizzles.
3078 if (Comp[0] == 's' || Comp[0] == 'S')
3079 Comp = Comp.substr(1);
3080
3081 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
3082 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
3083 return true;
3084
3085 return false;
3086 }
3087
3088 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
getEncodedElementAccess(SmallVectorImpl<unsigned> & Elts) const3089 void ExtVectorElementExpr::getEncodedElementAccess(
3090 SmallVectorImpl<unsigned> &Elts) const {
3091 StringRef Comp = Accessor->getName();
3092 if (Comp[0] == 's' || Comp[0] == 'S')
3093 Comp = Comp.substr(1);
3094
3095 bool isHi = Comp == "hi";
3096 bool isLo = Comp == "lo";
3097 bool isEven = Comp == "even";
3098 bool isOdd = Comp == "odd";
3099
3100 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3101 uint64_t Index;
3102
3103 if (isHi)
3104 Index = e + i;
3105 else if (isLo)
3106 Index = i;
3107 else if (isEven)
3108 Index = 2 * i;
3109 else if (isOdd)
3110 Index = 2 * i + 1;
3111 else
3112 Index = ExtVectorType::getAccessorIdx(Comp[i]);
3113
3114 Elts.push_back(Index);
3115 }
3116 }
3117
ObjCMessageExpr(QualType T,ExprValueKind VK,SourceLocation LBracLoc,SourceLocation SuperLoc,bool IsInstanceSuper,QualType SuperType,Selector Sel,ArrayRef<SourceLocation> SelLocs,SelectorLocationsKind SelLocsK,ObjCMethodDecl * Method,ArrayRef<Expr * > Args,SourceLocation RBracLoc,bool isImplicit)3118 ObjCMessageExpr::ObjCMessageExpr(QualType T,
3119 ExprValueKind VK,
3120 SourceLocation LBracLoc,
3121 SourceLocation SuperLoc,
3122 bool IsInstanceSuper,
3123 QualType SuperType,
3124 Selector Sel,
3125 ArrayRef<SourceLocation> SelLocs,
3126 SelectorLocationsKind SelLocsK,
3127 ObjCMethodDecl *Method,
3128 ArrayRef<Expr *> Args,
3129 SourceLocation RBracLoc,
3130 bool isImplicit)
3131 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
3132 /*TypeDependent=*/false, /*ValueDependent=*/false,
3133 /*InstantiationDependent=*/false,
3134 /*ContainsUnexpandedParameterPack=*/false),
3135 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
3136 : Sel.getAsOpaquePtr())),
3137 Kind(IsInstanceSuper? SuperInstance : SuperClass),
3138 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
3139 SuperLoc(SuperLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
3140 {
3141 initArgsAndSelLocs(Args, SelLocs, SelLocsK);
3142 setReceiverPointer(SuperType.getAsOpaquePtr());
3143 }
3144
ObjCMessageExpr(QualType T,ExprValueKind VK,SourceLocation LBracLoc,TypeSourceInfo * Receiver,Selector Sel,ArrayRef<SourceLocation> SelLocs,SelectorLocationsKind SelLocsK,ObjCMethodDecl * Method,ArrayRef<Expr * > Args,SourceLocation RBracLoc,bool isImplicit)3145 ObjCMessageExpr::ObjCMessageExpr(QualType T,
3146 ExprValueKind VK,
3147 SourceLocation LBracLoc,
3148 TypeSourceInfo *Receiver,
3149 Selector Sel,
3150 ArrayRef<SourceLocation> SelLocs,
3151 SelectorLocationsKind SelLocsK,
3152 ObjCMethodDecl *Method,
3153 ArrayRef<Expr *> Args,
3154 SourceLocation RBracLoc,
3155 bool isImplicit)
3156 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
3157 T->isDependentType(), T->isInstantiationDependentType(),
3158 T->containsUnexpandedParameterPack()),
3159 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
3160 : Sel.getAsOpaquePtr())),
3161 Kind(Class),
3162 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
3163 LBracLoc(LBracLoc), RBracLoc(RBracLoc)
3164 {
3165 initArgsAndSelLocs(Args, SelLocs, SelLocsK);
3166 setReceiverPointer(Receiver);
3167 }
3168
ObjCMessageExpr(QualType T,ExprValueKind VK,SourceLocation LBracLoc,Expr * Receiver,Selector Sel,ArrayRef<SourceLocation> SelLocs,SelectorLocationsKind SelLocsK,ObjCMethodDecl * Method,ArrayRef<Expr * > Args,SourceLocation RBracLoc,bool isImplicit)3169 ObjCMessageExpr::ObjCMessageExpr(QualType T,
3170 ExprValueKind VK,
3171 SourceLocation LBracLoc,
3172 Expr *Receiver,
3173 Selector Sel,
3174 ArrayRef<SourceLocation> SelLocs,
3175 SelectorLocationsKind SelLocsK,
3176 ObjCMethodDecl *Method,
3177 ArrayRef<Expr *> Args,
3178 SourceLocation RBracLoc,
3179 bool isImplicit)
3180 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
3181 Receiver->isTypeDependent(),
3182 Receiver->isInstantiationDependent(),
3183 Receiver->containsUnexpandedParameterPack()),
3184 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
3185 : Sel.getAsOpaquePtr())),
3186 Kind(Instance),
3187 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
3188 LBracLoc(LBracLoc), RBracLoc(RBracLoc)
3189 {
3190 initArgsAndSelLocs(Args, SelLocs, SelLocsK);
3191 setReceiverPointer(Receiver);
3192 }
3193
initArgsAndSelLocs(ArrayRef<Expr * > Args,ArrayRef<SourceLocation> SelLocs,SelectorLocationsKind SelLocsK)3194 void ObjCMessageExpr::initArgsAndSelLocs(ArrayRef<Expr *> Args,
3195 ArrayRef<SourceLocation> SelLocs,
3196 SelectorLocationsKind SelLocsK) {
3197 setNumArgs(Args.size());
3198 Expr **MyArgs = getArgs();
3199 for (unsigned I = 0; I != Args.size(); ++I) {
3200 if (Args[I]->isTypeDependent())
3201 ExprBits.TypeDependent = true;
3202 if (Args[I]->isValueDependent())
3203 ExprBits.ValueDependent = true;
3204 if (Args[I]->isInstantiationDependent())
3205 ExprBits.InstantiationDependent = true;
3206 if (Args[I]->containsUnexpandedParameterPack())
3207 ExprBits.ContainsUnexpandedParameterPack = true;
3208
3209 MyArgs[I] = Args[I];
3210 }
3211
3212 SelLocsKind = SelLocsK;
3213 if (!isImplicit()) {
3214 if (SelLocsK == SelLoc_NonStandard)
3215 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
3216 }
3217 }
3218
Create(ASTContext & Context,QualType T,ExprValueKind VK,SourceLocation LBracLoc,SourceLocation SuperLoc,bool IsInstanceSuper,QualType SuperType,Selector Sel,ArrayRef<SourceLocation> SelLocs,ObjCMethodDecl * Method,ArrayRef<Expr * > Args,SourceLocation RBracLoc,bool isImplicit)3219 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
3220 ExprValueKind VK,
3221 SourceLocation LBracLoc,
3222 SourceLocation SuperLoc,
3223 bool IsInstanceSuper,
3224 QualType SuperType,
3225 Selector Sel,
3226 ArrayRef<SourceLocation> SelLocs,
3227 ObjCMethodDecl *Method,
3228 ArrayRef<Expr *> Args,
3229 SourceLocation RBracLoc,
3230 bool isImplicit) {
3231 assert((!SelLocs.empty() || isImplicit) &&
3232 "No selector locs for non-implicit message");
3233 ObjCMessageExpr *Mem;
3234 SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3235 if (isImplicit)
3236 Mem = alloc(Context, Args.size(), 0);
3237 else
3238 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
3239 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
3240 SuperType, Sel, SelLocs, SelLocsK,
3241 Method, Args, RBracLoc, isImplicit);
3242 }
3243
Create(ASTContext & Context,QualType T,ExprValueKind VK,SourceLocation LBracLoc,TypeSourceInfo * Receiver,Selector Sel,ArrayRef<SourceLocation> SelLocs,ObjCMethodDecl * Method,ArrayRef<Expr * > Args,SourceLocation RBracLoc,bool isImplicit)3244 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
3245 ExprValueKind VK,
3246 SourceLocation LBracLoc,
3247 TypeSourceInfo *Receiver,
3248 Selector Sel,
3249 ArrayRef<SourceLocation> SelLocs,
3250 ObjCMethodDecl *Method,
3251 ArrayRef<Expr *> Args,
3252 SourceLocation RBracLoc,
3253 bool isImplicit) {
3254 assert((!SelLocs.empty() || isImplicit) &&
3255 "No selector locs for non-implicit message");
3256 ObjCMessageExpr *Mem;
3257 SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3258 if (isImplicit)
3259 Mem = alloc(Context, Args.size(), 0);
3260 else
3261 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
3262 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
3263 SelLocs, SelLocsK, Method, Args, RBracLoc,
3264 isImplicit);
3265 }
3266
Create(ASTContext & Context,QualType T,ExprValueKind VK,SourceLocation LBracLoc,Expr * Receiver,Selector Sel,ArrayRef<SourceLocation> SelLocs,ObjCMethodDecl * Method,ArrayRef<Expr * > Args,SourceLocation RBracLoc,bool isImplicit)3267 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
3268 ExprValueKind VK,
3269 SourceLocation LBracLoc,
3270 Expr *Receiver,
3271 Selector Sel,
3272 ArrayRef<SourceLocation> SelLocs,
3273 ObjCMethodDecl *Method,
3274 ArrayRef<Expr *> Args,
3275 SourceLocation RBracLoc,
3276 bool isImplicit) {
3277 assert((!SelLocs.empty() || isImplicit) &&
3278 "No selector locs for non-implicit message");
3279 ObjCMessageExpr *Mem;
3280 SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3281 if (isImplicit)
3282 Mem = alloc(Context, Args.size(), 0);
3283 else
3284 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
3285 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
3286 SelLocs, SelLocsK, Method, Args, RBracLoc,
3287 isImplicit);
3288 }
3289
CreateEmpty(ASTContext & Context,unsigned NumArgs,unsigned NumStoredSelLocs)3290 ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
3291 unsigned NumArgs,
3292 unsigned NumStoredSelLocs) {
3293 ObjCMessageExpr *Mem = alloc(Context, NumArgs, NumStoredSelLocs);
3294 return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
3295 }
3296
alloc(ASTContext & C,ArrayRef<Expr * > Args,SourceLocation RBraceLoc,ArrayRef<SourceLocation> SelLocs,Selector Sel,SelectorLocationsKind & SelLocsK)3297 ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C,
3298 ArrayRef<Expr *> Args,
3299 SourceLocation RBraceLoc,
3300 ArrayRef<SourceLocation> SelLocs,
3301 Selector Sel,
3302 SelectorLocationsKind &SelLocsK) {
3303 SelLocsK = hasStandardSelectorLocs(Sel, SelLocs, Args, RBraceLoc);
3304 unsigned NumStoredSelLocs = (SelLocsK == SelLoc_NonStandard) ? SelLocs.size()
3305 : 0;
3306 return alloc(C, Args.size(), NumStoredSelLocs);
3307 }
3308
alloc(ASTContext & C,unsigned NumArgs,unsigned NumStoredSelLocs)3309 ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C,
3310 unsigned NumArgs,
3311 unsigned NumStoredSelLocs) {
3312 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
3313 NumArgs * sizeof(Expr *) + NumStoredSelLocs * sizeof(SourceLocation);
3314 return (ObjCMessageExpr *)C.Allocate(Size,
3315 llvm::AlignOf<ObjCMessageExpr>::Alignment);
3316 }
3317
getSelectorLocs(SmallVectorImpl<SourceLocation> & SelLocs) const3318 void ObjCMessageExpr::getSelectorLocs(
3319 SmallVectorImpl<SourceLocation> &SelLocs) const {
3320 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
3321 SelLocs.push_back(getSelectorLoc(i));
3322 }
3323
getReceiverRange() const3324 SourceRange ObjCMessageExpr::getReceiverRange() const {
3325 switch (getReceiverKind()) {
3326 case Instance:
3327 return getInstanceReceiver()->getSourceRange();
3328
3329 case Class:
3330 return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
3331
3332 case SuperInstance:
3333 case SuperClass:
3334 return getSuperLoc();
3335 }
3336
3337 llvm_unreachable("Invalid ReceiverKind!");
3338 }
3339
getSelector() const3340 Selector ObjCMessageExpr::getSelector() const {
3341 if (HasMethod)
3342 return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
3343 ->getSelector();
3344 return Selector(SelectorOrMethod);
3345 }
3346
getReceiverInterface() const3347 ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
3348 switch (getReceiverKind()) {
3349 case Instance:
3350 if (const ObjCObjectPointerType *Ptr
3351 = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
3352 return Ptr->getInterfaceDecl();
3353 break;
3354
3355 case Class:
3356 if (const ObjCObjectType *Ty
3357 = getClassReceiver()->getAs<ObjCObjectType>())
3358 return Ty->getInterface();
3359 break;
3360
3361 case SuperInstance:
3362 if (const ObjCObjectPointerType *Ptr
3363 = getSuperType()->getAs<ObjCObjectPointerType>())
3364 return Ptr->getInterfaceDecl();
3365 break;
3366
3367 case SuperClass:
3368 if (const ObjCObjectType *Iface
3369 = getSuperType()->getAs<ObjCObjectType>())
3370 return Iface->getInterface();
3371 break;
3372 }
3373
3374 return 0;
3375 }
3376
getBridgeKindName() const3377 StringRef ObjCBridgedCastExpr::getBridgeKindName() const {
3378 switch (getBridgeKind()) {
3379 case OBC_Bridge:
3380 return "__bridge";
3381 case OBC_BridgeTransfer:
3382 return "__bridge_transfer";
3383 case OBC_BridgeRetained:
3384 return "__bridge_retained";
3385 }
3386
3387 llvm_unreachable("Invalid BridgeKind!");
3388 }
3389
isConditionTrue(const ASTContext & C) const3390 bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
3391 return getCond()->EvaluateKnownConstInt(C) != 0;
3392 }
3393
ShuffleVectorExpr(ASTContext & C,ArrayRef<Expr * > args,QualType Type,SourceLocation BLoc,SourceLocation RP)3394 ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, ArrayRef<Expr*> args,
3395 QualType Type, SourceLocation BLoc,
3396 SourceLocation RP)
3397 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3398 Type->isDependentType(), Type->isDependentType(),
3399 Type->isInstantiationDependentType(),
3400 Type->containsUnexpandedParameterPack()),
3401 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3402 {
3403 SubExprs = new (C) Stmt*[args.size()];
3404 for (unsigned i = 0; i != args.size(); i++) {
3405 if (args[i]->isTypeDependent())
3406 ExprBits.TypeDependent = true;
3407 if (args[i]->isValueDependent())
3408 ExprBits.ValueDependent = true;
3409 if (args[i]->isInstantiationDependent())
3410 ExprBits.InstantiationDependent = true;
3411 if (args[i]->containsUnexpandedParameterPack())
3412 ExprBits.ContainsUnexpandedParameterPack = true;
3413
3414 SubExprs[i] = args[i];
3415 }
3416 }
3417
setExprs(ASTContext & C,Expr ** Exprs,unsigned NumExprs)3418 void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
3419 unsigned NumExprs) {
3420 if (SubExprs) C.Deallocate(SubExprs);
3421
3422 SubExprs = new (C) Stmt* [NumExprs];
3423 this->NumExprs = NumExprs;
3424 memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
3425 }
3426
GenericSelectionExpr(ASTContext & Context,SourceLocation GenericLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack,unsigned ResultIndex)3427 GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3428 SourceLocation GenericLoc, Expr *ControllingExpr,
3429 ArrayRef<TypeSourceInfo*> AssocTypes,
3430 ArrayRef<Expr*> AssocExprs,
3431 SourceLocation DefaultLoc,
3432 SourceLocation RParenLoc,
3433 bool ContainsUnexpandedParameterPack,
3434 unsigned ResultIndex)
3435 : Expr(GenericSelectionExprClass,
3436 AssocExprs[ResultIndex]->getType(),
3437 AssocExprs[ResultIndex]->getValueKind(),
3438 AssocExprs[ResultIndex]->getObjectKind(),
3439 AssocExprs[ResultIndex]->isTypeDependent(),
3440 AssocExprs[ResultIndex]->isValueDependent(),
3441 AssocExprs[ResultIndex]->isInstantiationDependent(),
3442 ContainsUnexpandedParameterPack),
3443 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3444 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3445 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3446 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3447 SubExprs[CONTROLLING] = ControllingExpr;
3448 assert(AssocTypes.size() == AssocExprs.size());
3449 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3450 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
3451 }
3452
GenericSelectionExpr(ASTContext & Context,SourceLocation GenericLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack)3453 GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3454 SourceLocation GenericLoc, Expr *ControllingExpr,
3455 ArrayRef<TypeSourceInfo*> AssocTypes,
3456 ArrayRef<Expr*> AssocExprs,
3457 SourceLocation DefaultLoc,
3458 SourceLocation RParenLoc,
3459 bool ContainsUnexpandedParameterPack)
3460 : Expr(GenericSelectionExprClass,
3461 Context.DependentTy,
3462 VK_RValue,
3463 OK_Ordinary,
3464 /*isTypeDependent=*/true,
3465 /*isValueDependent=*/true,
3466 /*isInstantiationDependent=*/true,
3467 ContainsUnexpandedParameterPack),
3468 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3469 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3470 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3471 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3472 SubExprs[CONTROLLING] = ControllingExpr;
3473 assert(AssocTypes.size() == AssocExprs.size());
3474 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3475 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
3476 }
3477
3478 //===----------------------------------------------------------------------===//
3479 // DesignatedInitExpr
3480 //===----------------------------------------------------------------------===//
3481
getFieldName() const3482 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
3483 assert(Kind == FieldDesignator && "Only valid on a field designator");
3484 if (Field.NameOrField & 0x01)
3485 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3486 else
3487 return getField()->getIdentifier();
3488 }
3489
DesignatedInitExpr(ASTContext & C,QualType Ty,unsigned NumDesignators,const Designator * Designators,SourceLocation EqualOrColonLoc,bool GNUSyntax,ArrayRef<Expr * > IndexExprs,Expr * Init)3490 DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
3491 unsigned NumDesignators,
3492 const Designator *Designators,
3493 SourceLocation EqualOrColonLoc,
3494 bool GNUSyntax,
3495 ArrayRef<Expr*> IndexExprs,
3496 Expr *Init)
3497 : Expr(DesignatedInitExprClass, Ty,
3498 Init->getValueKind(), Init->getObjectKind(),
3499 Init->isTypeDependent(), Init->isValueDependent(),
3500 Init->isInstantiationDependent(),
3501 Init->containsUnexpandedParameterPack()),
3502 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
3503 NumDesignators(NumDesignators), NumSubExprs(IndexExprs.size() + 1) {
3504 this->Designators = new (C) Designator[NumDesignators];
3505
3506 // Record the initializer itself.
3507 child_range Child = children();
3508 *Child++ = Init;
3509
3510 // Copy the designators and their subexpressions, computing
3511 // value-dependence along the way.
3512 unsigned IndexIdx = 0;
3513 for (unsigned I = 0; I != NumDesignators; ++I) {
3514 this->Designators[I] = Designators[I];
3515
3516 if (this->Designators[I].isArrayDesignator()) {
3517 // Compute type- and value-dependence.
3518 Expr *Index = IndexExprs[IndexIdx];
3519 if (Index->isTypeDependent() || Index->isValueDependent())
3520 ExprBits.ValueDependent = true;
3521 if (Index->isInstantiationDependent())
3522 ExprBits.InstantiationDependent = true;
3523 // Propagate unexpanded parameter packs.
3524 if (Index->containsUnexpandedParameterPack())
3525 ExprBits.ContainsUnexpandedParameterPack = true;
3526
3527 // Copy the index expressions into permanent storage.
3528 *Child++ = IndexExprs[IndexIdx++];
3529 } else if (this->Designators[I].isArrayRangeDesignator()) {
3530 // Compute type- and value-dependence.
3531 Expr *Start = IndexExprs[IndexIdx];
3532 Expr *End = IndexExprs[IndexIdx + 1];
3533 if (Start->isTypeDependent() || Start->isValueDependent() ||
3534 End->isTypeDependent() || End->isValueDependent()) {
3535 ExprBits.ValueDependent = true;
3536 ExprBits.InstantiationDependent = true;
3537 } else if (Start->isInstantiationDependent() ||
3538 End->isInstantiationDependent()) {
3539 ExprBits.InstantiationDependent = true;
3540 }
3541
3542 // Propagate unexpanded parameter packs.
3543 if (Start->containsUnexpandedParameterPack() ||
3544 End->containsUnexpandedParameterPack())
3545 ExprBits.ContainsUnexpandedParameterPack = true;
3546
3547 // Copy the start/end expressions into permanent storage.
3548 *Child++ = IndexExprs[IndexIdx++];
3549 *Child++ = IndexExprs[IndexIdx++];
3550 }
3551 }
3552
3553 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
3554 }
3555
3556 DesignatedInitExpr *
Create(ASTContext & C,Designator * Designators,unsigned NumDesignators,ArrayRef<Expr * > IndexExprs,SourceLocation ColonOrEqualLoc,bool UsesColonSyntax,Expr * Init)3557 DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
3558 unsigned NumDesignators,
3559 ArrayRef<Expr*> IndexExprs,
3560 SourceLocation ColonOrEqualLoc,
3561 bool UsesColonSyntax, Expr *Init) {
3562 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3563 sizeof(Stmt *) * (IndexExprs.size() + 1), 8);
3564 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
3565 ColonOrEqualLoc, UsesColonSyntax,
3566 IndexExprs, Init);
3567 }
3568
CreateEmpty(ASTContext & C,unsigned NumIndexExprs)3569 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
3570 unsigned NumIndexExprs) {
3571 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3572 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3573 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3574 }
3575
setDesignators(ASTContext & C,const Designator * Desigs,unsigned NumDesigs)3576 void DesignatedInitExpr::setDesignators(ASTContext &C,
3577 const Designator *Desigs,
3578 unsigned NumDesigs) {
3579 Designators = new (C) Designator[NumDesigs];
3580 NumDesignators = NumDesigs;
3581 for (unsigned I = 0; I != NumDesigs; ++I)
3582 Designators[I] = Desigs[I];
3583 }
3584
getDesignatorsSourceRange() const3585 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3586 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3587 if (size() == 1)
3588 return DIE->getDesignator(0)->getSourceRange();
3589 return SourceRange(DIE->getDesignator(0)->getStartLocation(),
3590 DIE->getDesignator(size()-1)->getEndLocation());
3591 }
3592
getSourceRange() const3593 SourceRange DesignatedInitExpr::getSourceRange() const {
3594 SourceLocation StartLoc;
3595 Designator &First =
3596 *const_cast<DesignatedInitExpr*>(this)->designators_begin();
3597 if (First.isFieldDesignator()) {
3598 if (GNUSyntax)
3599 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3600 else
3601 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3602 } else
3603 StartLoc =
3604 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
3605 return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
3606 }
3607
getArrayIndex(const Designator & D)3608 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
3609 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
3610 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3611 Ptr += sizeof(DesignatedInitExpr);
3612 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3613 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3614 }
3615
getArrayRangeStart(const Designator & D)3616 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
3617 assert(D.Kind == Designator::ArrayRangeDesignator &&
3618 "Requires array range designator");
3619 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3620 Ptr += sizeof(DesignatedInitExpr);
3621 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3622 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3623 }
3624
getArrayRangeEnd(const Designator & D)3625 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
3626 assert(D.Kind == Designator::ArrayRangeDesignator &&
3627 "Requires array range designator");
3628 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3629 Ptr += sizeof(DesignatedInitExpr);
3630 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3631 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
3632 }
3633
3634 /// \brief Replaces the designator at index @p Idx with the series
3635 /// of designators in [First, Last).
ExpandDesignator(ASTContext & C,unsigned Idx,const Designator * First,const Designator * Last)3636 void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
3637 const Designator *First,
3638 const Designator *Last) {
3639 unsigned NumNewDesignators = Last - First;
3640 if (NumNewDesignators == 0) {
3641 std::copy_backward(Designators + Idx + 1,
3642 Designators + NumDesignators,
3643 Designators + Idx);
3644 --NumNewDesignators;
3645 return;
3646 } else if (NumNewDesignators == 1) {
3647 Designators[Idx] = *First;
3648 return;
3649 }
3650
3651 Designator *NewDesignators
3652 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
3653 std::copy(Designators, Designators + Idx, NewDesignators);
3654 std::copy(First, Last, NewDesignators + Idx);
3655 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3656 NewDesignators + Idx + NumNewDesignators);
3657 Designators = NewDesignators;
3658 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3659 }
3660
ParenListExpr(ASTContext & C,SourceLocation lparenloc,ArrayRef<Expr * > exprs,SourceLocation rparenloc)3661 ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
3662 ArrayRef<Expr*> exprs,
3663 SourceLocation rparenloc)
3664 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
3665 false, false, false, false),
3666 NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3667 Exprs = new (C) Stmt*[exprs.size()];
3668 for (unsigned i = 0; i != exprs.size(); ++i) {
3669 if (exprs[i]->isTypeDependent())
3670 ExprBits.TypeDependent = true;
3671 if (exprs[i]->isValueDependent())
3672 ExprBits.ValueDependent = true;
3673 if (exprs[i]->isInstantiationDependent())
3674 ExprBits.InstantiationDependent = true;
3675 if (exprs[i]->containsUnexpandedParameterPack())
3676 ExprBits.ContainsUnexpandedParameterPack = true;
3677
3678 Exprs[i] = exprs[i];
3679 }
3680 }
3681
findInCopyConstruct(const Expr * e)3682 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3683 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3684 e = ewc->getSubExpr();
3685 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3686 e = m->GetTemporaryExpr();
3687 e = cast<CXXConstructExpr>(e)->getArg(0);
3688 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3689 e = ice->getSubExpr();
3690 return cast<OpaqueValueExpr>(e);
3691 }
3692
Create(ASTContext & Context,EmptyShell sh,unsigned numSemanticExprs)3693 PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &Context, EmptyShell sh,
3694 unsigned numSemanticExprs) {
3695 void *buffer = Context.Allocate(sizeof(PseudoObjectExpr) +
3696 (1 + numSemanticExprs) * sizeof(Expr*),
3697 llvm::alignOf<PseudoObjectExpr>());
3698 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3699 }
3700
PseudoObjectExpr(EmptyShell shell,unsigned numSemanticExprs)3701 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3702 : Expr(PseudoObjectExprClass, shell) {
3703 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3704 }
3705
Create(ASTContext & C,Expr * syntax,ArrayRef<Expr * > semantics,unsigned resultIndex)3706 PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &C, Expr *syntax,
3707 ArrayRef<Expr*> semantics,
3708 unsigned resultIndex) {
3709 assert(syntax && "no syntactic expression!");
3710 assert(semantics.size() && "no semantic expressions!");
3711
3712 QualType type;
3713 ExprValueKind VK;
3714 if (resultIndex == NoResult) {
3715 type = C.VoidTy;
3716 VK = VK_RValue;
3717 } else {
3718 assert(resultIndex < semantics.size());
3719 type = semantics[resultIndex]->getType();
3720 VK = semantics[resultIndex]->getValueKind();
3721 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3722 }
3723
3724 void *buffer = C.Allocate(sizeof(PseudoObjectExpr) +
3725 (1 + semantics.size()) * sizeof(Expr*),
3726 llvm::alignOf<PseudoObjectExpr>());
3727 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3728 resultIndex);
3729 }
3730
PseudoObjectExpr(QualType type,ExprValueKind VK,Expr * syntax,ArrayRef<Expr * > semantics,unsigned resultIndex)3731 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3732 Expr *syntax, ArrayRef<Expr*> semantics,
3733 unsigned resultIndex)
3734 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3735 /*filled in at end of ctor*/ false, false, false, false) {
3736 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3737 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3738
3739 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3740 Expr *E = (i == 0 ? syntax : semantics[i-1]);
3741 getSubExprsBuffer()[i] = E;
3742
3743 if (E->isTypeDependent())
3744 ExprBits.TypeDependent = true;
3745 if (E->isValueDependent())
3746 ExprBits.ValueDependent = true;
3747 if (E->isInstantiationDependent())
3748 ExprBits.InstantiationDependent = true;
3749 if (E->containsUnexpandedParameterPack())
3750 ExprBits.ContainsUnexpandedParameterPack = true;
3751
3752 if (isa<OpaqueValueExpr>(E))
3753 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != 0 &&
3754 "opaque-value semantic expressions for pseudo-object "
3755 "operations must have sources");
3756 }
3757 }
3758
3759 //===----------------------------------------------------------------------===//
3760 // ExprIterator.
3761 //===----------------------------------------------------------------------===//
3762
operator [](size_t idx)3763 Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
operator *() const3764 Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
operator ->() const3765 Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
operator [](size_t idx) const3766 const Expr* ConstExprIterator::operator[](size_t idx) const {
3767 return cast<Expr>(I[idx]);
3768 }
operator *() const3769 const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
operator ->() const3770 const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
3771
3772 //===----------------------------------------------------------------------===//
3773 // Child Iterators for iterating over subexpressions/substatements
3774 //===----------------------------------------------------------------------===//
3775
3776 // UnaryExprOrTypeTraitExpr
children()3777 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
3778 // If this is of a type and the type is a VLA type (and not a typedef), the
3779 // size expression of the VLA needs to be treated as an executable expression.
3780 // Why isn't this weirdness documented better in StmtIterator?
3781 if (isArgumentType()) {
3782 if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
3783 getArgumentType().getTypePtr()))
3784 return child_range(child_iterator(T), child_iterator());
3785 return child_range();
3786 }
3787 return child_range(&Argument.Ex, &Argument.Ex + 1);
3788 }
3789
3790 // ObjCMessageExpr
children()3791 Stmt::child_range ObjCMessageExpr::children() {
3792 Stmt **begin;
3793 if (getReceiverKind() == Instance)
3794 begin = reinterpret_cast<Stmt **>(this + 1);
3795 else
3796 begin = reinterpret_cast<Stmt **>(getArgs());
3797 return child_range(begin,
3798 reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
3799 }
3800
ObjCArrayLiteral(llvm::ArrayRef<Expr * > Elements,QualType T,ObjCMethodDecl * Method,SourceRange SR)3801 ObjCArrayLiteral::ObjCArrayLiteral(llvm::ArrayRef<Expr *> Elements,
3802 QualType T, ObjCMethodDecl *Method,
3803 SourceRange SR)
3804 : Expr(ObjCArrayLiteralClass, T, VK_RValue, OK_Ordinary,
3805 false, false, false, false),
3806 NumElements(Elements.size()), Range(SR), ArrayWithObjectsMethod(Method)
3807 {
3808 Expr **SaveElements = getElements();
3809 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
3810 if (Elements[I]->isTypeDependent() || Elements[I]->isValueDependent())
3811 ExprBits.ValueDependent = true;
3812 if (Elements[I]->isInstantiationDependent())
3813 ExprBits.InstantiationDependent = true;
3814 if (Elements[I]->containsUnexpandedParameterPack())
3815 ExprBits.ContainsUnexpandedParameterPack = true;
3816
3817 SaveElements[I] = Elements[I];
3818 }
3819 }
3820
Create(ASTContext & C,llvm::ArrayRef<Expr * > Elements,QualType T,ObjCMethodDecl * Method,SourceRange SR)3821 ObjCArrayLiteral *ObjCArrayLiteral::Create(ASTContext &C,
3822 llvm::ArrayRef<Expr *> Elements,
3823 QualType T, ObjCMethodDecl * Method,
3824 SourceRange SR) {
3825 void *Mem = C.Allocate(sizeof(ObjCArrayLiteral)
3826 + Elements.size() * sizeof(Expr *));
3827 return new (Mem) ObjCArrayLiteral(Elements, T, Method, SR);
3828 }
3829
CreateEmpty(ASTContext & C,unsigned NumElements)3830 ObjCArrayLiteral *ObjCArrayLiteral::CreateEmpty(ASTContext &C,
3831 unsigned NumElements) {
3832
3833 void *Mem = C.Allocate(sizeof(ObjCArrayLiteral)
3834 + NumElements * sizeof(Expr *));
3835 return new (Mem) ObjCArrayLiteral(EmptyShell(), NumElements);
3836 }
3837
ObjCDictionaryLiteral(ArrayRef<ObjCDictionaryElement> VK,bool HasPackExpansions,QualType T,ObjCMethodDecl * method,SourceRange SR)3838 ObjCDictionaryLiteral::ObjCDictionaryLiteral(
3839 ArrayRef<ObjCDictionaryElement> VK,
3840 bool HasPackExpansions,
3841 QualType T, ObjCMethodDecl *method,
3842 SourceRange SR)
3843 : Expr(ObjCDictionaryLiteralClass, T, VK_RValue, OK_Ordinary, false, false,
3844 false, false),
3845 NumElements(VK.size()), HasPackExpansions(HasPackExpansions), Range(SR),
3846 DictWithObjectsMethod(method)
3847 {
3848 KeyValuePair *KeyValues = getKeyValues();
3849 ExpansionData *Expansions = getExpansionData();
3850 for (unsigned I = 0; I < NumElements; I++) {
3851 if (VK[I].Key->isTypeDependent() || VK[I].Key->isValueDependent() ||
3852 VK[I].Value->isTypeDependent() || VK[I].Value->isValueDependent())
3853 ExprBits.ValueDependent = true;
3854 if (VK[I].Key->isInstantiationDependent() ||
3855 VK[I].Value->isInstantiationDependent())
3856 ExprBits.InstantiationDependent = true;
3857 if (VK[I].EllipsisLoc.isInvalid() &&
3858 (VK[I].Key->containsUnexpandedParameterPack() ||
3859 VK[I].Value->containsUnexpandedParameterPack()))
3860 ExprBits.ContainsUnexpandedParameterPack = true;
3861
3862 KeyValues[I].Key = VK[I].Key;
3863 KeyValues[I].Value = VK[I].Value;
3864 if (Expansions) {
3865 Expansions[I].EllipsisLoc = VK[I].EllipsisLoc;
3866 if (VK[I].NumExpansions)
3867 Expansions[I].NumExpansionsPlusOne = *VK[I].NumExpansions + 1;
3868 else
3869 Expansions[I].NumExpansionsPlusOne = 0;
3870 }
3871 }
3872 }
3873
3874 ObjCDictionaryLiteral *
Create(ASTContext & C,ArrayRef<ObjCDictionaryElement> VK,bool HasPackExpansions,QualType T,ObjCMethodDecl * method,SourceRange SR)3875 ObjCDictionaryLiteral::Create(ASTContext &C,
3876 ArrayRef<ObjCDictionaryElement> VK,
3877 bool HasPackExpansions,
3878 QualType T, ObjCMethodDecl *method,
3879 SourceRange SR) {
3880 unsigned ExpansionsSize = 0;
3881 if (HasPackExpansions)
3882 ExpansionsSize = sizeof(ExpansionData) * VK.size();
3883
3884 void *Mem = C.Allocate(sizeof(ObjCDictionaryLiteral) +
3885 sizeof(KeyValuePair) * VK.size() + ExpansionsSize);
3886 return new (Mem) ObjCDictionaryLiteral(VK, HasPackExpansions, T, method, SR);
3887 }
3888
3889 ObjCDictionaryLiteral *
CreateEmpty(ASTContext & C,unsigned NumElements,bool HasPackExpansions)3890 ObjCDictionaryLiteral::CreateEmpty(ASTContext &C, unsigned NumElements,
3891 bool HasPackExpansions) {
3892 unsigned ExpansionsSize = 0;
3893 if (HasPackExpansions)
3894 ExpansionsSize = sizeof(ExpansionData) * NumElements;
3895 void *Mem = C.Allocate(sizeof(ObjCDictionaryLiteral) +
3896 sizeof(KeyValuePair) * NumElements + ExpansionsSize);
3897 return new (Mem) ObjCDictionaryLiteral(EmptyShell(), NumElements,
3898 HasPackExpansions);
3899 }
3900
Create(ASTContext & C,Expr * base,Expr * key,QualType T,ObjCMethodDecl * getMethod,ObjCMethodDecl * setMethod,SourceLocation RB)3901 ObjCSubscriptRefExpr *ObjCSubscriptRefExpr::Create(ASTContext &C,
3902 Expr *base,
3903 Expr *key, QualType T,
3904 ObjCMethodDecl *getMethod,
3905 ObjCMethodDecl *setMethod,
3906 SourceLocation RB) {
3907 void *Mem = C.Allocate(sizeof(ObjCSubscriptRefExpr));
3908 return new (Mem) ObjCSubscriptRefExpr(base, key, T, VK_LValue,
3909 OK_ObjCSubscript,
3910 getMethod, setMethod, RB);
3911 }
3912
AtomicExpr(SourceLocation BLoc,ArrayRef<Expr * > args,QualType t,AtomicOp op,SourceLocation RP)3913 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
3914 QualType t, AtomicOp op, SourceLocation RP)
3915 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3916 false, false, false, false),
3917 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
3918 {
3919 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
3920 for (unsigned i = 0; i != args.size(); i++) {
3921 if (args[i]->isTypeDependent())
3922 ExprBits.TypeDependent = true;
3923 if (args[i]->isValueDependent())
3924 ExprBits.ValueDependent = true;
3925 if (args[i]->isInstantiationDependent())
3926 ExprBits.InstantiationDependent = true;
3927 if (args[i]->containsUnexpandedParameterPack())
3928 ExprBits.ContainsUnexpandedParameterPack = true;
3929
3930 SubExprs[i] = args[i];
3931 }
3932 }
3933
getNumSubExprs(AtomicOp Op)3934 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
3935 switch (Op) {
3936 case AO__c11_atomic_init:
3937 case AO__c11_atomic_load:
3938 case AO__atomic_load_n:
3939 return 2;
3940
3941 case AO__c11_atomic_store:
3942 case AO__c11_atomic_exchange:
3943 case AO__atomic_load:
3944 case AO__atomic_store:
3945 case AO__atomic_store_n:
3946 case AO__atomic_exchange_n:
3947 case AO__c11_atomic_fetch_add:
3948 case AO__c11_atomic_fetch_sub:
3949 case AO__c11_atomic_fetch_and:
3950 case AO__c11_atomic_fetch_or:
3951 case AO__c11_atomic_fetch_xor:
3952 case AO__atomic_fetch_add:
3953 case AO__atomic_fetch_sub:
3954 case AO__atomic_fetch_and:
3955 case AO__atomic_fetch_or:
3956 case AO__atomic_fetch_xor:
3957 case AO__atomic_fetch_nand:
3958 case AO__atomic_add_fetch:
3959 case AO__atomic_sub_fetch:
3960 case AO__atomic_and_fetch:
3961 case AO__atomic_or_fetch:
3962 case AO__atomic_xor_fetch:
3963 case AO__atomic_nand_fetch:
3964 return 3;
3965
3966 case AO__atomic_exchange:
3967 return 4;
3968
3969 case AO__c11_atomic_compare_exchange_strong:
3970 case AO__c11_atomic_compare_exchange_weak:
3971 return 5;
3972
3973 case AO__atomic_compare_exchange:
3974 case AO__atomic_compare_exchange_n:
3975 return 6;
3976 }
3977 llvm_unreachable("unknown atomic op");
3978 }
3979