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