clang  10.0.0svn
Expr.cpp
Go to the documentation of this file.
1 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr class and subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/Expr.h"
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"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/Mangle.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/Basic/Builtins.h"
26 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Lexer.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 #include <cstring>
35 using namespace clang;
36 
38  const Expr *E = this;
39  while (true) {
40  E = E->ignoreParenBaseCasts();
41 
42  // Follow the RHS of a comma operator.
43  if (auto *BO = dyn_cast<BinaryOperator>(E)) {
44  if (BO->getOpcode() == BO_Comma) {
45  E = BO->getRHS();
46  continue;
47  }
48  }
49 
50  // Step into initializer for materialized temporaries.
51  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
52  E = MTE->GetTemporaryExpr();
53  continue;
54  }
55 
56  break;
57  }
58 
59  return E;
60 }
61 
63  const Expr *E = getBestDynamicClassTypeExpr();
64  QualType DerivedType = E->getType();
65  if (const PointerType *PTy = DerivedType->getAs<PointerType>())
66  DerivedType = PTy->getPointeeType();
67 
68  if (DerivedType->isDependentType())
69  return nullptr;
70 
71  const RecordType *Ty = DerivedType->castAs<RecordType>();
72  Decl *D = Ty->getDecl();
73  return cast<CXXRecordDecl>(D);
74 }
75 
78  SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
79  const Expr *E = this;
80  while (true) {
81  E = E->IgnoreParens();
82 
83  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
84  if ((CE->getCastKind() == CK_DerivedToBase ||
85  CE->getCastKind() == CK_UncheckedDerivedToBase) &&
86  E->getType()->isRecordType()) {
87  E = CE->getSubExpr();
88  CXXRecordDecl *Derived
89  = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
90  Adjustments.push_back(SubobjectAdjustment(CE, Derived));
91  continue;
92  }
93 
94  if (CE->getCastKind() == CK_NoOp) {
95  E = CE->getSubExpr();
96  continue;
97  }
98  } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
99  if (!ME->isArrow()) {
100  assert(ME->getBase()->getType()->isRecordType());
101  if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
102  if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
103  E = ME->getBase();
104  Adjustments.push_back(SubobjectAdjustment(Field));
105  continue;
106  }
107  }
108  }
109  } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
110  if (BO->getOpcode() == BO_PtrMemD) {
111  assert(BO->getRHS()->isRValue());
112  E = BO->getLHS();
113  const MemberPointerType *MPT =
114  BO->getRHS()->getType()->getAs<MemberPointerType>();
115  Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
116  continue;
117  } else if (BO->getOpcode() == BO_Comma) {
118  CommaLHSs.push_back(BO->getLHS());
119  E = BO->getRHS();
120  continue;
121  }
122  }
123 
124  // Nothing changed.
125  break;
126  }
127  return E;
128 }
129 
130 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
131 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
132 /// but also int expressions which are produced by things like comparisons in
133 /// C.
135  const Expr *E = IgnoreParens();
136 
137  // If this value has _Bool type, it is obvious 0/1.
138  if (E->getType()->isBooleanType()) return true;
139  // If this is a non-scalar-integer type, we don't care enough to try.
140  if (!E->getType()->isIntegralOrEnumerationType()) return false;
141 
142  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
143  switch (UO->getOpcode()) {
144  case UO_Plus:
145  return UO->getSubExpr()->isKnownToHaveBooleanValue();
146  case UO_LNot:
147  return true;
148  default:
149  return false;
150  }
151  }
152 
153  // Only look through implicit casts. If the user writes
154  // '(int) (a && b)' treat it as an arbitrary int.
155  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
156  return CE->getSubExpr()->isKnownToHaveBooleanValue();
157 
158  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
159  switch (BO->getOpcode()) {
160  default: return false;
161  case BO_LT: // Relational operators.
162  case BO_GT:
163  case BO_LE:
164  case BO_GE:
165  case BO_EQ: // Equality operators.
166  case BO_NE:
167  case BO_LAnd: // AND operator.
168  case BO_LOr: // Logical OR operator.
169  return true;
170 
171  case BO_And: // Bitwise AND operator.
172  case BO_Xor: // Bitwise XOR operator.
173  case BO_Or: // Bitwise OR operator.
174  // Handle things like (x==2)|(y==12).
175  return BO->getLHS()->isKnownToHaveBooleanValue() &&
176  BO->getRHS()->isKnownToHaveBooleanValue();
177 
178  case BO_Comma:
179  case BO_Assign:
180  return BO->getRHS()->isKnownToHaveBooleanValue();
181  }
182  }
183 
184  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
185  return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
186  CO->getFalseExpr()->isKnownToHaveBooleanValue();
187 
188  if (isa<ObjCBoolLiteralExpr>(E))
189  return true;
190 
191  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
192  return OVE->getSourceExpr()->isKnownToHaveBooleanValue();
193 
194  return false;
195 }
196 
197 // Amusing macro metaprogramming hack: check whether a class provides
198 // a more specific implementation of getExprLoc().
199 //
200 // See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
201 namespace {
202  /// This implementation is used when a class provides a custom
203  /// implementation of getExprLoc.
204  template <class E, class T>
205  SourceLocation getExprLocImpl(const Expr *expr,
206  SourceLocation (T::*v)() const) {
207  return static_cast<const E*>(expr)->getExprLoc();
208  }
209 
210  /// This implementation is used when a class doesn't provide
211  /// a custom implementation of getExprLoc. Overload resolution
212  /// should pick it over the implementation above because it's
213  /// more specialized according to function template partial ordering.
214  template <class E>
215  SourceLocation getExprLocImpl(const Expr *expr,
216  SourceLocation (Expr::*v)() const) {
217  return static_cast<const E *>(expr)->getBeginLoc();
218  }
219 }
220 
222  switch (getStmtClass()) {
223  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
224 #define ABSTRACT_STMT(type)
225 #define STMT(type, base) \
226  case Stmt::type##Class: break;
227 #define EXPR(type, base) \
228  case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
229 #include "clang/AST/StmtNodes.inc"
230  }
231  llvm_unreachable("unknown expression kind");
232 }
233 
234 //===----------------------------------------------------------------------===//
235 // Primary Expressions.
236 //===----------------------------------------------------------------------===//
237 
239  assert((Kind == ConstantExpr::RSK_APValue ||
240  Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&
241  "Invalid StorageKind Value");
242 }
243 
246  switch (Value.getKind()) {
247  case APValue::None:
249  return ConstantExpr::RSK_None;
250  case APValue::Int:
251  if (!Value.getInt().needsCleanup())
253  LLVM_FALLTHROUGH;
254  default:
256  }
257 }
258 
260 ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
261  if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
264 }
265 
266 void ConstantExpr::DefaultInit(ResultStorageKind StorageKind) {
267  ConstantExprBits.ResultKind = StorageKind;
268  ConstantExprBits.APValueKind = APValue::None;
269  ConstantExprBits.HasCleanup = false;
270  if (StorageKind == ConstantExpr::RSK_APValue)
271  ::new (getTrailingObjects<APValue>()) APValue();
272 }
273 
274 ConstantExpr::ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind)
275  : FullExpr(ConstantExprClass, subexpr) {
276  DefaultInit(StorageKind);
277 }
278 
280  ResultStorageKind StorageKind) {
281  assert(!isa<ConstantExpr>(E));
282  AssertResultStorageKind(StorageKind);
283  unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
284  StorageKind == ConstantExpr::RSK_APValue,
285  StorageKind == ConstantExpr::RSK_Int64);
286  void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
287  ConstantExpr *Self = new (Mem) ConstantExpr(E, StorageKind);
288  return Self;
289 }
290 
292  const APValue &Result) {
293  ResultStorageKind StorageKind = getStorageKind(Result);
294  ConstantExpr *Self = Create(Context, E, StorageKind);
295  Self->SetResult(Result, Context);
296  return Self;
297 }
298 
299 ConstantExpr::ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty)
300  : FullExpr(ConstantExprClass, Empty) {
301  DefaultInit(StorageKind);
302 }
303 
305  ResultStorageKind StorageKind,
306  EmptyShell Empty) {
307  AssertResultStorageKind(StorageKind);
308  unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
309  StorageKind == ConstantExpr::RSK_APValue,
310  StorageKind == ConstantExpr::RSK_Int64);
311  void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
312  ConstantExpr *Self = new (Mem) ConstantExpr(StorageKind, Empty);
313  return Self;
314 }
315 
317  assert(getStorageKind(Value) == ConstantExprBits.ResultKind &&
318  "Invalid storage for this value kind");
319  ConstantExprBits.APValueKind = Value.getKind();
320  switch (ConstantExprBits.ResultKind) {
321  case RSK_None:
322  return;
323  case RSK_Int64:
324  Int64Result() = *Value.getInt().getRawData();
325  ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
326  ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
327  return;
328  case RSK_APValue:
329  if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
330  ConstantExprBits.HasCleanup = true;
331  Context.addDestruction(&APValueResult());
332  }
333  APValueResult() = std::move(Value);
334  return;
335  }
336  llvm_unreachable("Invalid ResultKind Bits");
337 }
338 
340  switch (ConstantExprBits.ResultKind) {
342  return APValueResult().getInt();
344  return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
345  ConstantExprBits.IsUnsigned);
346  default:
347  llvm_unreachable("invalid Accessor");
348  }
349 }
350 
352  switch (ConstantExprBits.ResultKind) {
354  return APValueResult();
356  return APValue(
357  llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
358  ConstantExprBits.IsUnsigned));
360  return APValue();
361  }
362  llvm_unreachable("invalid ResultKind");
363 }
364 
365 /// Compute the type-, value-, and instantiation-dependence of a
366 /// declaration reference
367 /// based on the declaration being referenced.
368 static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
369  QualType T, bool &TypeDependent,
370  bool &ValueDependent,
371  bool &InstantiationDependent) {
372  TypeDependent = false;
373  ValueDependent = false;
374  InstantiationDependent = false;
375 
376  // (TD) C++ [temp.dep.expr]p3:
377  // An id-expression is type-dependent if it contains:
378  //
379  // and
380  //
381  // (VD) C++ [temp.dep.constexpr]p2:
382  // An identifier is value-dependent if it is:
383 
384  // (TD) - an identifier that was declared with dependent type
385  // (VD) - a name declared with a dependent type,
386  if (T->isDependentType()) {
387  TypeDependent = true;
388  ValueDependent = true;
389  InstantiationDependent = true;
390  return;
391  } else if (T->isInstantiationDependentType()) {
392  InstantiationDependent = true;
393  }
394 
395  // (TD) - a conversion-function-id that specifies a dependent type
396  if (D->getDeclName().getNameKind()
399  if (T->isDependentType()) {
400  TypeDependent = true;
401  ValueDependent = true;
402  InstantiationDependent = true;
403  return;
404  }
405 
407  InstantiationDependent = true;
408  }
409 
410  // (VD) - the name of a non-type template parameter,
411  if (isa<NonTypeTemplateParmDecl>(D)) {
412  ValueDependent = true;
413  InstantiationDependent = true;
414  return;
415  }
416 
417  // (VD) - a constant with integral or enumeration type and is
418  // initialized with an expression that is value-dependent.
419  // (VD) - a constant with literal type and is initialized with an
420  // expression that is value-dependent [C++11].
421  // (VD) - FIXME: Missing from the standard:
422  // - an entity with reference type and is initialized with an
423  // expression that is value-dependent [C++11]
424  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
425  if ((Ctx.getLangOpts().CPlusPlus11 ?
426  Var->getType()->isLiteralType(Ctx) :
427  Var->getType()->isIntegralOrEnumerationType()) &&
428  (Var->getType().isConstQualified() ||
429  Var->getType()->isReferenceType())) {
430  if (const Expr *Init = Var->getAnyInitializer())
431  if (Init->isValueDependent()) {
432  ValueDependent = true;
433  InstantiationDependent = true;
434  }
435  }
436 
437  // (VD) - FIXME: Missing from the standard:
438  // - a member function or a static data member of the current
439  // instantiation
440  if (Var->isStaticDataMember() &&
441  Var->getDeclContext()->isDependentContext()) {
442  ValueDependent = true;
443  InstantiationDependent = true;
444  TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
445  if (TInfo->getType()->isIncompleteArrayType())
446  TypeDependent = true;
447  }
448 
449  return;
450  }
451 
452  // (VD) - FIXME: Missing from the standard:
453  // - a member function or a static data member of the current
454  // instantiation
455  if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
456  ValueDependent = true;
457  InstantiationDependent = true;
458  }
459 }
460 
461 void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
462  bool TypeDependent = false;
463  bool ValueDependent = false;
464  bool InstantiationDependent = false;
465  computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
466  ValueDependent, InstantiationDependent);
467 
468  ExprBits.TypeDependent |= TypeDependent;
469  ExprBits.ValueDependent |= ValueDependent;
470  ExprBits.InstantiationDependent |= InstantiationDependent;
471 
472  // Is the declaration a parameter pack?
473  if (getDecl()->isParameterPack())
474  ExprBits.ContainsUnexpandedParameterPack = true;
475 }
476 
477 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
478  bool RefersToEnclosingVariableOrCapture, QualType T,
480  const DeclarationNameLoc &LocInfo,
481  NonOdrUseReason NOUR)
482  : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
483  D(D), DNLoc(LocInfo) {
484  DeclRefExprBits.HasQualifier = false;
485  DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
486  DeclRefExprBits.HasFoundDecl = false;
487  DeclRefExprBits.HadMultipleCandidates = false;
488  DeclRefExprBits.RefersToEnclosingVariableOrCapture =
489  RefersToEnclosingVariableOrCapture;
490  DeclRefExprBits.NonOdrUseReason = NOUR;
491  DeclRefExprBits.Loc = L;
492  computeDependence(Ctx);
493 }
494 
495 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
496  NestedNameSpecifierLoc QualifierLoc,
497  SourceLocation TemplateKWLoc, ValueDecl *D,
498  bool RefersToEnclosingVariableOrCapture,
499  const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
500  const TemplateArgumentListInfo *TemplateArgs,
502  : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
503  D(D), DNLoc(NameInfo.getInfo()) {
504  DeclRefExprBits.Loc = NameInfo.getLoc();
505  DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
506  if (QualifierLoc) {
507  new (getTrailingObjects<NestedNameSpecifierLoc>())
508  NestedNameSpecifierLoc(QualifierLoc);
509  auto *NNS = QualifierLoc.getNestedNameSpecifier();
510  if (NNS->isInstantiationDependent())
511  ExprBits.InstantiationDependent = true;
512  if (NNS->containsUnexpandedParameterPack())
513  ExprBits.ContainsUnexpandedParameterPack = true;
514  }
515  DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
516  if (FoundD)
517  *getTrailingObjects<NamedDecl *>() = FoundD;
518  DeclRefExprBits.HasTemplateKWAndArgsInfo
519  = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
520  DeclRefExprBits.RefersToEnclosingVariableOrCapture =
521  RefersToEnclosingVariableOrCapture;
522  DeclRefExprBits.NonOdrUseReason = NOUR;
523  if (TemplateArgs) {
524  bool Dependent = false;
525  bool InstantiationDependent = false;
526  bool ContainsUnexpandedParameterPack = false;
527  getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
528  TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
529  Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
530  assert(!Dependent && "built a DeclRefExpr with dependent template args");
531  ExprBits.InstantiationDependent |= InstantiationDependent;
532  ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
533  } else if (TemplateKWLoc.isValid()) {
534  getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
535  TemplateKWLoc);
536  }
537  DeclRefExprBits.HadMultipleCandidates = 0;
538 
539  computeDependence(Ctx);
540 }
541 
543  NestedNameSpecifierLoc QualifierLoc,
544  SourceLocation TemplateKWLoc, ValueDecl *D,
545  bool RefersToEnclosingVariableOrCapture,
546  SourceLocation NameLoc, QualType T,
547  ExprValueKind VK, NamedDecl *FoundD,
548  const TemplateArgumentListInfo *TemplateArgs,
549  NonOdrUseReason NOUR) {
550  return Create(Context, QualifierLoc, TemplateKWLoc, D,
551  RefersToEnclosingVariableOrCapture,
552  DeclarationNameInfo(D->getDeclName(), NameLoc),
553  T, VK, FoundD, TemplateArgs, NOUR);
554 }
555 
557  NestedNameSpecifierLoc QualifierLoc,
558  SourceLocation TemplateKWLoc, ValueDecl *D,
559  bool RefersToEnclosingVariableOrCapture,
560  const DeclarationNameInfo &NameInfo,
561  QualType T, ExprValueKind VK,
562  NamedDecl *FoundD,
563  const TemplateArgumentListInfo *TemplateArgs,
564  NonOdrUseReason NOUR) {
565  // Filter out cases where the found Decl is the same as the value refenenced.
566  if (D == FoundD)
567  FoundD = nullptr;
568 
569  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
570  std::size_t Size =
571  totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
573  QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
574  HasTemplateKWAndArgsInfo ? 1 : 0,
575  TemplateArgs ? TemplateArgs->size() : 0);
576 
577  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
578  return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
579  RefersToEnclosingVariableOrCapture, NameInfo,
580  FoundD, TemplateArgs, T, VK, NOUR);
581 }
582 
584  bool HasQualifier,
585  bool HasFoundDecl,
586  bool HasTemplateKWAndArgsInfo,
587  unsigned NumTemplateArgs) {
588  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
589  std::size_t Size =
590  totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
592  HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
593  NumTemplateArgs);
594  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
595  return new (Mem) DeclRefExpr(EmptyShell());
596 }
597 
599  if (hasQualifier())
600  return getQualifierLoc().getBeginLoc();
601  return getNameInfo().getBeginLoc();
602 }
605  return getRAngleLoc();
606  return getNameInfo().getEndLoc();
607 }
608 
609 PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
610  StringLiteral *SL)
611  : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
612  FNTy->isDependentType(), FNTy->isDependentType(),
614  /*ContainsUnexpandedParameterPack=*/false) {
615  PredefinedExprBits.Kind = IK;
616  assert((getIdentKind() == IK) &&
617  "IdentKind do not fit in PredefinedExprBitfields!");
618  bool HasFunctionName = SL != nullptr;
619  PredefinedExprBits.HasFunctionName = HasFunctionName;
620  PredefinedExprBits.Loc = L;
621  if (HasFunctionName)
622  setFunctionName(SL);
623 }
624 
625 PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
626  : Expr(PredefinedExprClass, Empty) {
627  PredefinedExprBits.HasFunctionName = HasFunctionName;
628 }
629 
631  QualType FNTy, IdentKind IK,
632  StringLiteral *SL) {
633  bool HasFunctionName = SL != nullptr;
634  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
635  alignof(PredefinedExpr));
636  return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
637 }
638 
640  bool HasFunctionName) {
641  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
642  alignof(PredefinedExpr));
643  return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
644 }
645 
647  switch (IK) {
648  case Func:
649  return "__func__";
650  case Function:
651  return "__FUNCTION__";
652  case FuncDName:
653  return "__FUNCDNAME__";
654  case LFunction:
655  return "L__FUNCTION__";
656  case PrettyFunction:
657  return "__PRETTY_FUNCTION__";
658  case FuncSig:
659  return "__FUNCSIG__";
660  case LFuncSig:
661  return "L__FUNCSIG__";
662  case PrettyFunctionNoVirtual:
663  break;
664  }
665  llvm_unreachable("Unknown ident kind for PredefinedExpr");
666 }
667 
668 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
669 // expr" policy instead.
670 std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
671  ASTContext &Context = CurrentDecl->getASTContext();
672 
673  if (IK == PredefinedExpr::FuncDName) {
674  if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
675  std::unique_ptr<MangleContext> MC;
676  MC.reset(Context.createMangleContext());
677 
678  if (MC->shouldMangleDeclName(ND)) {
679  SmallString<256> Buffer;
680  llvm::raw_svector_ostream Out(Buffer);
681  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
682  MC->mangleCXXCtor(CD, Ctor_Base, Out);
683  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
684  MC->mangleCXXDtor(DD, Dtor_Base, Out);
685  else
686  MC->mangleName(ND, Out);
687 
688  if (!Buffer.empty() && Buffer.front() == '\01')
689  return Buffer.substr(1);
690  return Buffer.str();
691  } else
692  return ND->getIdentifier()->getName();
693  }
694  return "";
695  }
696  if (isa<BlockDecl>(CurrentDecl)) {
697  // For blocks we only emit something if it is enclosed in a function
698  // For top-level block we'd like to include the name of variable, but we
699  // don't have it at this point.
700  auto DC = CurrentDecl->getDeclContext();
701  if (DC->isFileContext())
702  return "";
703 
704  SmallString<256> Buffer;
705  llvm::raw_svector_ostream Out(Buffer);
706  if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
707  // For nested blocks, propagate up to the parent.
708  Out << ComputeName(IK, DCBlock);
709  else if (auto *DCDecl = dyn_cast<Decl>(DC))
710  Out << ComputeName(IK, DCDecl) << "_block_invoke";
711  return Out.str();
712  }
713  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
714  if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
715  IK != FuncSig && IK != LFuncSig)
716  return FD->getNameAsString();
717 
718  SmallString<256> Name;
719  llvm::raw_svector_ostream Out(Name);
720 
721  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
722  if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
723  Out << "virtual ";
724  if (MD->isStatic())
725  Out << "static ";
726  }
727 
728  PrintingPolicy Policy(Context.getLangOpts());
729  std::string Proto;
730  llvm::raw_string_ostream POut(Proto);
731 
732  const FunctionDecl *Decl = FD;
733  if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
734  Decl = Pattern;
735  const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
736  const FunctionProtoType *FT = nullptr;
737  if (FD->hasWrittenPrototype())
738  FT = dyn_cast<FunctionProtoType>(AFT);
739 
740  if (IK == FuncSig || IK == LFuncSig) {
741  switch (AFT->getCallConv()) {
742  case CC_C: POut << "__cdecl "; break;
743  case CC_X86StdCall: POut << "__stdcall "; break;
744  case CC_X86FastCall: POut << "__fastcall "; break;
745  case CC_X86ThisCall: POut << "__thiscall "; break;
746  case CC_X86VectorCall: POut << "__vectorcall "; break;
747  case CC_X86RegCall: POut << "__regcall "; break;
748  // Only bother printing the conventions that MSVC knows about.
749  default: break;
750  }
751  }
752 
753  FD->printQualifiedName(POut, Policy);
754 
755  POut << "(";
756  if (FT) {
757  for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
758  if (i) POut << ", ";
759  POut << Decl->getParamDecl(i)->getType().stream(Policy);
760  }
761 
762  if (FT->isVariadic()) {
763  if (FD->getNumParams()) POut << ", ";
764  POut << "...";
765  } else if ((IK == FuncSig || IK == LFuncSig ||
766  !Context.getLangOpts().CPlusPlus) &&
767  !Decl->getNumParams()) {
768  POut << "void";
769  }
770  }
771  POut << ")";
772 
773  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
774  assert(FT && "We must have a written prototype in this case.");
775  if (FT->isConst())
776  POut << " const";
777  if (FT->isVolatile())
778  POut << " volatile";
779  RefQualifierKind Ref = MD->getRefQualifier();
780  if (Ref == RQ_LValue)
781  POut << " &";
782  else if (Ref == RQ_RValue)
783  POut << " &&";
784  }
785 
787  SpecsTy Specs;
788  const DeclContext *Ctx = FD->getDeclContext();
789  while (Ctx && isa<NamedDecl>(Ctx)) {
791  = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
792  if (Spec && !Spec->isExplicitSpecialization())
793  Specs.push_back(Spec);
794  Ctx = Ctx->getParent();
795  }
796 
797  std::string TemplateParams;
798  llvm::raw_string_ostream TOut(TemplateParams);
799  for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
800  I != E; ++I) {
801  const TemplateParameterList *Params
802  = (*I)->getSpecializedTemplate()->getTemplateParameters();
803  const TemplateArgumentList &Args = (*I)->getTemplateArgs();
804  assert(Params->size() == Args.size());
805  for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
806  StringRef Param = Params->getParam(i)->getName();
807  if (Param.empty()) continue;
808  TOut << Param << " = ";
809  Args.get(i).print(Policy, TOut);
810  TOut << ", ";
811  }
812  }
813 
815  = FD->getTemplateSpecializationInfo();
816  if (FSI && !FSI->isExplicitSpecialization()) {
817  const TemplateParameterList* Params
819  const TemplateArgumentList* Args = FSI->TemplateArguments;
820  assert(Params->size() == Args->size());
821  for (unsigned i = 0, e = Params->size(); i != e; ++i) {
822  StringRef Param = Params->getParam(i)->getName();
823  if (Param.empty()) continue;
824  TOut << Param << " = ";
825  Args->get(i).print(Policy, TOut);
826  TOut << ", ";
827  }
828  }
829 
830  TOut.flush();
831  if (!TemplateParams.empty()) {
832  // remove the trailing comma and space
833  TemplateParams.resize(TemplateParams.size() - 2);
834  POut << " [" << TemplateParams << "]";
835  }
836 
837  POut.flush();
838 
839  // Print "auto" for all deduced return types. This includes C++1y return
840  // type deduction and lambdas. For trailing return types resolve the
841  // decltype expression. Otherwise print the real type when this is
842  // not a constructor or destructor.
843  if (isa<CXXMethodDecl>(FD) &&
844  cast<CXXMethodDecl>(FD)->getParent()->isLambda())
845  Proto = "auto " + Proto;
846  else if (FT && FT->getReturnType()->getAs<DecltypeType>())
847  FT->getReturnType()
848  ->getAs<DecltypeType>()
850  .getAsStringInternal(Proto, Policy);
851  else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
852  AFT->getReturnType().getAsStringInternal(Proto, Policy);
853 
854  Out << Proto;
855 
856  return Name.str().str();
857  }
858  if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
859  for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
860  // Skip to its enclosing function or method, but not its enclosing
861  // CapturedDecl.
862  if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
863  const Decl *D = Decl::castFromDeclContext(DC);
864  return ComputeName(IK, D);
865  }
866  llvm_unreachable("CapturedDecl not inside a function or method");
867  }
868  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
869  SmallString<256> Name;
870  llvm::raw_svector_ostream Out(Name);
871  Out << (MD->isInstanceMethod() ? '-' : '+');
872  Out << '[';
873 
874  // For incorrect code, there might not be an ObjCInterfaceDecl. Do
875  // a null check to avoid a crash.
876  if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
877  Out << *ID;
878 
879  if (const ObjCCategoryImplDecl *CID =
880  dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
881  Out << '(' << *CID << ')';
882 
883  Out << ' ';
884  MD->getSelector().print(Out);
885  Out << ']';
886 
887  return Name.str().str();
888  }
889  if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
890  // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
891  return "top level";
892  }
893  return "";
894 }
895 
897  const llvm::APInt &Val) {
898  if (hasAllocation())
899  C.Deallocate(pVal);
900 
901  BitWidth = Val.getBitWidth();
902  unsigned NumWords = Val.getNumWords();
903  const uint64_t* Words = Val.getRawData();
904  if (NumWords > 1) {
905  pVal = new (C) uint64_t[NumWords];
906  std::copy(Words, Words + NumWords, pVal);
907  } else if (NumWords == 1)
908  VAL = Words[0];
909  else
910  VAL = 0;
911 }
912 
913 IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
915  : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
916  false, false),
917  Loc(l) {
918  assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
919  assert(V.getBitWidth() == C.getIntWidth(type) &&
920  "Integer type is not the correct size for constant.");
921  setValue(C, V);
922 }
923 
927  return new (C) IntegerLiteral(C, V, type, l);
928 }
929 
932  return new (C) IntegerLiteral(Empty);
933 }
934 
935 FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
937  unsigned Scale)
938  : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
939  false, false),
940  Loc(l), Scale(Scale) {
941  assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
942  assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
943  "Fixed point type is not the correct size for constant.");
944  setValue(C, V);
945 }
946 
948  const llvm::APInt &V,
949  QualType type,
950  SourceLocation l,
951  unsigned Scale) {
952  return new (C) FixedPointLiteral(C, V, type, l, Scale);
953 }
954 
955 std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
956  // Currently the longest decimal number that can be printed is the max for an
957  // unsigned long _Accum: 4294967295.99999999976716935634613037109375
958  // which is 43 characters.
959  SmallString<64> S;
961  S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
962  return S.str();
963 }
964 
965 FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
966  bool isexact, QualType Type, SourceLocation L)
967  : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
968  false, false), Loc(L) {
969  setSemantics(V.getSemantics());
970  FloatingLiteralBits.IsExact = isexact;
971  setValue(C, V);
972 }
973 
974 FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
975  : Expr(FloatingLiteralClass, Empty) {
976  setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
977  FloatingLiteralBits.IsExact = false;
978 }
979 
981 FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
982  bool isexact, QualType Type, SourceLocation L) {
983  return new (C) FloatingLiteral(C, V, isexact, Type, L);
984 }
985 
988  return new (C) FloatingLiteral(C, Empty);
989 }
990 
991 /// getValueAsApproximateDouble - This returns the value as an inaccurate
992 /// double. Note that this may cause loss of precision, but is useful for
993 /// debugging dumps, etc.
995  llvm::APFloat V = getValue();
996  bool ignored;
997  V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
998  &ignored);
999  return V.convertToDouble();
1000 }
1001 
1002 unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1003  StringKind SK) {
1004  unsigned CharByteWidth = 0;
1005  switch (SK) {
1006  case Ascii:
1007  case UTF8:
1008  CharByteWidth = Target.getCharWidth();
1009  break;
1010  case Wide:
1011  CharByteWidth = Target.getWCharWidth();
1012  break;
1013  case UTF16:
1014  CharByteWidth = Target.getChar16Width();
1015  break;
1016  case UTF32:
1017  CharByteWidth = Target.getChar32Width();
1018  break;
1019  }
1020  assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1021  CharByteWidth /= 8;
1022  assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1023  "The only supported character byte widths are 1,2 and 4!");
1024  return CharByteWidth;
1025 }
1026 
1027 StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1028  StringKind Kind, bool Pascal, QualType Ty,
1029  const SourceLocation *Loc,
1030  unsigned NumConcatenated)
1031  : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1032  false) {
1033  assert(Ctx.getAsConstantArrayType(Ty) &&
1034  "StringLiteral must be of constant array type!");
1035  unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1036  unsigned ByteLength = Str.size();
1037  assert((ByteLength % CharByteWidth == 0) &&
1038  "The size of the data must be a multiple of CharByteWidth!");
1039 
1040  // Avoid the expensive division. The compiler should be able to figure it
1041  // out by itself. However as of clang 7, even with the appropriate
1042  // llvm_unreachable added just here, it is not able to do so.
1043  unsigned Length;
1044  switch (CharByteWidth) {
1045  case 1:
1046  Length = ByteLength;
1047  break;
1048  case 2:
1049  Length = ByteLength / 2;
1050  break;
1051  case 4:
1052  Length = ByteLength / 4;
1053  break;
1054  default:
1055  llvm_unreachable("Unsupported character width!");
1056  }
1057 
1058  StringLiteralBits.Kind = Kind;
1059  StringLiteralBits.CharByteWidth = CharByteWidth;
1060  StringLiteralBits.IsPascal = Pascal;
1061  StringLiteralBits.NumConcatenated = NumConcatenated;
1062  *getTrailingObjects<unsigned>() = Length;
1063 
1064  // Initialize the trailing array of SourceLocation.
1065  // This is safe since SourceLocation is POD-like.
1066  std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1067  NumConcatenated * sizeof(SourceLocation));
1068 
1069  // Initialize the trailing array of char holding the string data.
1070  std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
1071 }
1072 
1073 StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1074  unsigned Length, unsigned CharByteWidth)
1075  : Expr(StringLiteralClass, Empty) {
1076  StringLiteralBits.CharByteWidth = CharByteWidth;
1077  StringLiteralBits.NumConcatenated = NumConcatenated;
1078  *getTrailingObjects<unsigned>() = Length;
1079 }
1080 
1082  StringKind Kind, bool Pascal, QualType Ty,
1083  const SourceLocation *Loc,
1084  unsigned NumConcatenated) {
1085  void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1086  1, NumConcatenated, Str.size()),
1087  alignof(StringLiteral));
1088  return new (Mem)
1089  StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1090 }
1091 
1093  unsigned NumConcatenated,
1094  unsigned Length,
1095  unsigned CharByteWidth) {
1096  void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1097  1, NumConcatenated, Length * CharByteWidth),
1098  alignof(StringLiteral));
1099  return new (Mem)
1100  StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1101 }
1102 
1103 void StringLiteral::outputString(raw_ostream &OS) const {
1104  switch (getKind()) {
1105  case Ascii: break; // no prefix.
1106  case Wide: OS << 'L'; break;
1107  case UTF8: OS << "u8"; break;
1108  case UTF16: OS << 'u'; break;
1109  case UTF32: OS << 'U'; break;
1110  }
1111  OS << '"';
1112  static const char Hex[] = "0123456789ABCDEF";
1113 
1114  unsigned LastSlashX = getLength();
1115  for (unsigned I = 0, N = getLength(); I != N; ++I) {
1116  switch (uint32_t Char = getCodeUnit(I)) {
1117  default:
1118  // FIXME: Convert UTF-8 back to codepoints before rendering.
1119 
1120  // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1121  // Leave invalid surrogates alone; we'll use \x for those.
1122  if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
1123  Char <= 0xdbff) {
1124  uint32_t Trail = getCodeUnit(I + 1);
1125  if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1126  Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1127  ++I;
1128  }
1129  }
1130 
1131  if (Char > 0xff) {
1132  // If this is a wide string, output characters over 0xff using \x
1133  // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1134  // codepoint: use \x escapes for invalid codepoints.
1135  if (getKind() == Wide ||
1136  (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1137  // FIXME: Is this the best way to print wchar_t?
1138  OS << "\\x";
1139  int Shift = 28;
1140  while ((Char >> Shift) == 0)
1141  Shift -= 4;
1142  for (/**/; Shift >= 0; Shift -= 4)
1143  OS << Hex[(Char >> Shift) & 15];
1144  LastSlashX = I;
1145  break;
1146  }
1147 
1148  if (Char > 0xffff)
1149  OS << "\\U00"
1150  << Hex[(Char >> 20) & 15]
1151  << Hex[(Char >> 16) & 15];
1152  else
1153  OS << "\\u";
1154  OS << Hex[(Char >> 12) & 15]
1155  << Hex[(Char >> 8) & 15]
1156  << Hex[(Char >> 4) & 15]
1157  << Hex[(Char >> 0) & 15];
1158  break;
1159  }
1160 
1161  // If we used \x... for the previous character, and this character is a
1162  // hexadecimal digit, prevent it being slurped as part of the \x.
1163  if (LastSlashX + 1 == I) {
1164  switch (Char) {
1165  case '0': case '1': case '2': case '3': case '4':
1166  case '5': case '6': case '7': case '8': case '9':
1167  case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1168  case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1169  OS << "\"\"";
1170  }
1171  }
1172 
1173  assert(Char <= 0xff &&
1174  "Characters above 0xff should already have been handled.");
1175 
1176  if (isPrintable(Char))
1177  OS << (char)Char;
1178  else // Output anything hard as an octal escape.
1179  OS << '\\'
1180  << (char)('0' + ((Char >> 6) & 7))
1181  << (char)('0' + ((Char >> 3) & 7))
1182  << (char)('0' + ((Char >> 0) & 7));
1183  break;
1184  // Handle some common non-printable cases to make dumps prettier.
1185  case '\\': OS << "\\\\"; break;
1186  case '"': OS << "\\\""; break;
1187  case '\a': OS << "\\a"; break;
1188  case '\b': OS << "\\b"; break;
1189  case '\f': OS << "\\f"; break;
1190  case '\n': OS << "\\n"; break;
1191  case '\r': OS << "\\r"; break;
1192  case '\t': OS << "\\t"; break;
1193  case '\v': OS << "\\v"; break;
1194  }
1195  }
1196  OS << '"';
1197 }
1198 
1199 /// getLocationOfByte - Return a source location that points to the specified
1200 /// byte of this string literal.
1201 ///
1202 /// Strings are amazingly complex. They can be formed from multiple tokens and
1203 /// can have escape sequences in them in addition to the usual trigraph and
1204 /// escaped newline business. This routine handles this complexity.
1205 ///
1206 /// The *StartToken sets the first token to be searched in this function and
1207 /// the *StartTokenByteOffset is the byte offset of the first token. Before
1208 /// returning, it updates the *StartToken to the TokNo of the token being found
1209 /// and sets *StartTokenByteOffset to the byte offset of the token in the
1210 /// string.
1211 /// Using these two parameters can reduce the time complexity from O(n^2) to
1212 /// O(n) if one wants to get the location of byte for all the tokens in a
1213 /// string.
1214 ///
1217  const LangOptions &Features,
1218  const TargetInfo &Target, unsigned *StartToken,
1219  unsigned *StartTokenByteOffset) const {
1220  assert((getKind() == StringLiteral::Ascii ||
1221  getKind() == StringLiteral::UTF8) &&
1222  "Only narrow string literals are currently supported");
1223 
1224  // Loop over all of the tokens in this string until we find the one that
1225  // contains the byte we're looking for.
1226  unsigned TokNo = 0;
1227  unsigned StringOffset = 0;
1228  if (StartToken)
1229  TokNo = *StartToken;
1230  if (StartTokenByteOffset) {
1231  StringOffset = *StartTokenByteOffset;
1232  ByteNo -= StringOffset;
1233  }
1234  while (1) {
1235  assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1236  SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1237 
1238  // Get the spelling of the string so that we can get the data that makes up
1239  // the string literal, not the identifier for the macro it is potentially
1240  // expanded through.
1241  SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1242 
1243  // Re-lex the token to get its length and original spelling.
1244  std::pair<FileID, unsigned> LocInfo =
1245  SM.getDecomposedLoc(StrTokSpellingLoc);
1246  bool Invalid = false;
1247  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1248  if (Invalid) {
1249  if (StartTokenByteOffset != nullptr)
1250  *StartTokenByteOffset = StringOffset;
1251  if (StartToken != nullptr)
1252  *StartToken = TokNo;
1253  return StrTokSpellingLoc;
1254  }
1255 
1256  const char *StrData = Buffer.data()+LocInfo.second;
1257 
1258  // Create a lexer starting at the beginning of this token.
1259  Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1260  Buffer.begin(), StrData, Buffer.end());
1261  Token TheTok;
1262  TheLexer.LexFromRawLexer(TheTok);
1263 
1264  // Use the StringLiteralParser to compute the length of the string in bytes.
1265  StringLiteralParser SLP(TheTok, SM, Features, Target);
1266  unsigned TokNumBytes = SLP.GetStringLength();
1267 
1268  // If the byte is in this token, return the location of the byte.
1269  if (ByteNo < TokNumBytes ||
1270  (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1271  unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1272 
1273  // Now that we know the offset of the token in the spelling, use the
1274  // preprocessor to get the offset in the original source.
1275  if (StartTokenByteOffset != nullptr)
1276  *StartTokenByteOffset = StringOffset;
1277  if (StartToken != nullptr)
1278  *StartToken = TokNo;
1279  return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1280  }
1281 
1282  // Move to the next string token.
1283  StringOffset += TokNumBytes;
1284  ++TokNo;
1285  ByteNo -= TokNumBytes;
1286  }
1287 }
1288 
1289 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1290 /// corresponds to, e.g. "sizeof" or "[pre]++".
1292  switch (Op) {
1293 #define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1294 #include "clang/AST/OperationKinds.def"
1295  }
1296  llvm_unreachable("Unknown unary operator");
1297 }
1298 
1301  switch (OO) {
1302  default: llvm_unreachable("No unary operator for overloaded function");
1303  case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1304  case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1305  case OO_Amp: return UO_AddrOf;
1306  case OO_Star: return UO_Deref;
1307  case OO_Plus: return UO_Plus;
1308  case OO_Minus: return UO_Minus;
1309  case OO_Tilde: return UO_Not;
1310  case OO_Exclaim: return UO_LNot;
1311  case OO_Coawait: return UO_Coawait;
1312  }
1313 }
1314 
1316  switch (Opc) {
1317  case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1318  case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1319  case UO_AddrOf: return OO_Amp;
1320  case UO_Deref: return OO_Star;
1321  case UO_Plus: return OO_Plus;
1322  case UO_Minus: return OO_Minus;
1323  case UO_Not: return OO_Tilde;
1324  case UO_LNot: return OO_Exclaim;
1325  case UO_Coawait: return OO_Coawait;
1326  default: return OO_None;
1327  }
1328 }
1329 
1330 
1331 //===----------------------------------------------------------------------===//
1332 // Postfix Operators.
1333 //===----------------------------------------------------------------------===//
1334 
1337  SourceLocation RParenLoc, unsigned MinNumArgs,
1338  ADLCallKind UsesADL)
1339  : Expr(SC, Ty, VK, OK_Ordinary, Fn->isTypeDependent(),
1342  RParenLoc(RParenLoc) {
1343  NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1344  unsigned NumPreArgs = PreArgs.size();
1345  CallExprBits.NumPreArgs = NumPreArgs;
1346  assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1347 
1348  unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1349  CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1350  assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1351  "OffsetToTrailingObjects overflow!");
1352 
1353  CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1354 
1355  setCallee(Fn);
1356  for (unsigned I = 0; I != NumPreArgs; ++I) {
1357  updateDependenciesFromArg(PreArgs[I]);
1358  setPreArg(I, PreArgs[I]);
1359  }
1360  for (unsigned I = 0; I != Args.size(); ++I) {
1361  updateDependenciesFromArg(Args[I]);
1362  setArg(I, Args[I]);
1363  }
1364  for (unsigned I = Args.size(); I != NumArgs; ++I) {
1365  setArg(I, nullptr);
1366  }
1367 }
1368 
1369 CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1370  EmptyShell Empty)
1371  : Expr(SC, Empty), NumArgs(NumArgs) {
1372  CallExprBits.NumPreArgs = NumPreArgs;
1373  assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1374 
1375  unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1376  CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1377  assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1378  "OffsetToTrailingObjects overflow!");
1379 }
1380 
1383  SourceLocation RParenLoc, unsigned MinNumArgs,
1384  ADLCallKind UsesADL) {
1385  unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1386  unsigned SizeOfTrailingObjects =
1387  CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1388  void *Mem =
1389  Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1390  return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1391  RParenLoc, MinNumArgs, UsesADL);
1392 }
1393 
1395  ExprValueKind VK, SourceLocation RParenLoc,
1396  ADLCallKind UsesADL) {
1397  assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1398  "Misaligned memory in CallExpr::CreateTemporary!");
1399  return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1400  VK, RParenLoc, /*MinNumArgs=*/0, UsesADL);
1401 }
1402 
1403 CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1404  EmptyShell Empty) {
1405  unsigned SizeOfTrailingObjects =
1406  CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1407  void *Mem =
1408  Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1409  return new (Mem) CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty);
1410 }
1411 
1412 unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1413  switch (SC) {
1414  case CallExprClass:
1415  return sizeof(CallExpr);
1416  case CXXOperatorCallExprClass:
1417  return sizeof(CXXOperatorCallExpr);
1418  case CXXMemberCallExprClass:
1419  return sizeof(CXXMemberCallExpr);
1420  case UserDefinedLiteralClass:
1421  return sizeof(UserDefinedLiteral);
1422  case CUDAKernelCallExprClass:
1423  return sizeof(CUDAKernelCallExpr);
1424  default:
1425  llvm_unreachable("unexpected class deriving from CallExpr!");
1426  }
1427 }
1428 
1429 void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1430  if (Arg->isTypeDependent())
1431  ExprBits.TypeDependent = true;
1432  if (Arg->isValueDependent())
1433  ExprBits.ValueDependent = true;
1434  if (Arg->isInstantiationDependent())
1435  ExprBits.InstantiationDependent = true;
1437  ExprBits.ContainsUnexpandedParameterPack = true;
1438 }
1439 
1441  Expr *CEE = IgnoreParenImpCasts();
1442 
1443  while (SubstNonTypeTemplateParmExpr *NTTP
1444  = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1445  CEE = NTTP->getReplacement()->IgnoreParenCasts();
1446  }
1447 
1448  // If we're calling a dereference, look at the pointer instead.
1449  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1450  if (BO->isPtrMemOp())
1451  CEE = BO->getRHS()->IgnoreParenCasts();
1452  } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1453  if (UO->getOpcode() == UO_Deref)
1454  CEE = UO->getSubExpr()->IgnoreParenCasts();
1455  }
1456  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
1457  return DRE->getDecl();
1458  if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1459  return ME->getMemberDecl();
1460  if (auto *BE = dyn_cast<BlockExpr>(CEE))
1461  return BE->getBlockDecl();
1462 
1463  return nullptr;
1464 }
1465 
1466 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
1467 /// not, return 0.
1468 unsigned CallExpr::getBuiltinCallee() const {
1469  // All simple function calls (e.g. func()) are implicitly cast to pointer to
1470  // function. As a result, we try and obtain the DeclRefExpr from the
1471  // ImplicitCastExpr.
1472  const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1473  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
1474  return 0;
1475 
1476  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1477  if (!DRE)
1478  return 0;
1479 
1480  const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1481  if (!FDecl)
1482  return 0;
1483 
1484  if (!FDecl->getIdentifier())
1485  return 0;
1486 
1487  return FDecl->getBuiltinID();
1488 }
1489 
1491  if (unsigned BI = getBuiltinCallee())
1492  return Ctx.BuiltinInfo.isUnevaluated(BI);
1493  return false;
1494 }
1495 
1497  const Expr *Callee = getCallee();
1498  QualType CalleeType = Callee->getType();
1499  if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1500  CalleeType = FnTypePtr->getPointeeType();
1501  } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1502  CalleeType = BPT->getPointeeType();
1503  } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1504  if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1505  return Ctx.VoidTy;
1506 
1507  // This should never be overloaded and so should never return null.
1508  CalleeType = Expr::findBoundMemberType(Callee);
1509  }
1510 
1511  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1512  return FnType->getReturnType();
1513 }
1514 
1516  // If the return type is a struct, union, or enum that is marked nodiscard,
1517  // then return the return type attribute.
1518  if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1519  if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1520  return A;
1521 
1522  // Otherwise, see if the callee is marked nodiscard and return that attribute
1523  // instead.
1524  const Decl *D = getCalleeDecl();
1525  return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1526 }
1527 
1529  if (isa<CXXOperatorCallExpr>(this))
1530  return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
1531 
1532  SourceLocation begin = getCallee()->getBeginLoc();
1533  if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1534  begin = getArg(0)->getBeginLoc();
1535  return begin;
1536 }
1538  if (isa<CXXOperatorCallExpr>(this))
1539  return cast<CXXOperatorCallExpr>(this)->getEndLoc();
1540 
1541  SourceLocation end = getRParenLoc();
1542  if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1543  end = getArg(getNumArgs() - 1)->getEndLoc();
1544  return end;
1545 }
1546 
1548  SourceLocation OperatorLoc,
1549  TypeSourceInfo *tsi,
1550  ArrayRef<OffsetOfNode> comps,
1551  ArrayRef<Expr*> exprs,
1552  SourceLocation RParenLoc) {
1553  void *Mem = C.Allocate(
1554  totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1555 
1556  return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1557  RParenLoc);
1558 }
1559 
1561  unsigned numComps, unsigned numExprs) {
1562  void *Mem =
1563  C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1564  return new (Mem) OffsetOfExpr(numComps, numExprs);
1565 }
1566 
1567 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1568  SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1570  SourceLocation RParenLoc)
1571  : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1572  /*TypeDependent=*/false,
1573  /*ValueDependent=*/tsi->getType()->isDependentType(),
1576  OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1577  NumComps(comps.size()), NumExprs(exprs.size())
1578 {
1579  for (unsigned i = 0; i != comps.size(); ++i) {
1580  setComponent(i, comps[i]);
1581  }
1582 
1583  for (unsigned i = 0; i != exprs.size(); ++i) {
1584  if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
1585  ExprBits.ValueDependent = true;
1586  if (exprs[i]->containsUnexpandedParameterPack())
1587  ExprBits.ContainsUnexpandedParameterPack = true;
1588 
1589  setIndexExpr(i, exprs[i]);
1590  }
1591 }
1592 
1594  assert(getKind() == Field || getKind() == Identifier);
1595  if (getKind() == Field)
1596  return getField()->getIdentifier();
1597 
1598  return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1599 }
1600 
1602  UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1604  : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1605  false, // Never type-dependent (C++ [temp.dep.expr]p3).
1606  // Value-dependent if the argument is type-dependent.
1609  OpLoc(op), RParenLoc(rp) {
1610  UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1611  UnaryExprOrTypeTraitExprBits.IsType = false;
1612  Argument.Ex = E;
1613 
1614  // Check to see if we are in the situation where alignof(decl) should be
1615  // dependent because decl's alignment is dependent.
1616  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
1618  E = E->IgnoreParens();
1619 
1620  const ValueDecl *D = nullptr;
1621  if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1622  D = DRE->getDecl();
1623  else if (const auto *ME = dyn_cast<MemberExpr>(E))
1624  D = ME->getMemberDecl();
1625 
1626  if (D) {
1627  for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1628  if (I->isAlignmentDependent()) {
1629  setValueDependent(true);
1631  break;
1632  }
1633  }
1634  }
1635  }
1636  }
1637 }
1638 
1639 MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1640  ValueDecl *MemberDecl,
1641  const DeclarationNameInfo &NameInfo, QualType T,
1643  NonOdrUseReason NOUR)
1644  : Expr(MemberExprClass, T, VK, OK, Base->isTypeDependent(),
1645  Base->isValueDependent(), Base->isInstantiationDependent(),
1647  Base(Base), MemberDecl(MemberDecl), MemberDNLoc(NameInfo.getInfo()),
1648  MemberLoc(NameInfo.getLoc()) {
1649  assert(!NameInfo.getName() ||
1650  MemberDecl->getDeclName() == NameInfo.getName());
1651  MemberExprBits.IsArrow = IsArrow;
1652  MemberExprBits.HasQualifierOrFoundDecl = false;
1653  MemberExprBits.HasTemplateKWAndArgsInfo = false;
1654  MemberExprBits.HadMultipleCandidates = false;
1655  MemberExprBits.NonOdrUseReason = NOUR;
1656  MemberExprBits.OperatorLoc = OperatorLoc;
1657 }
1658 
1660  const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1661  NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1662  ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1663  DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1665  bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1666  FoundDecl.getAccess() != MemberDecl->getAccess();
1667  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1668  std::size_t Size =
1671  HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1672  TemplateArgs ? TemplateArgs->size() : 0);
1673 
1674  void *Mem = C.Allocate(Size, alignof(MemberExpr));
1675  MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1676  NameInfo, T, VK, OK, NOUR);
1677 
1678  if (HasQualOrFound) {
1679  // FIXME: Wrong. We should be looking at the member declaration we found.
1680  if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1681  E->setValueDependent(true);
1682  E->setTypeDependent(true);
1683  E->setInstantiationDependent(true);
1684  }
1685  else if (QualifierLoc &&
1687  E->setInstantiationDependent(true);
1688 
1689  E->MemberExprBits.HasQualifierOrFoundDecl = true;
1690 
1691  MemberExprNameQualifier *NQ =
1692  E->getTrailingObjects<MemberExprNameQualifier>();
1693  NQ->QualifierLoc = QualifierLoc;
1694  NQ->FoundDecl = FoundDecl;
1695  }
1696 
1697  E->MemberExprBits.HasTemplateKWAndArgsInfo =
1698  TemplateArgs || TemplateKWLoc.isValid();
1699 
1700  if (TemplateArgs) {
1701  bool Dependent = false;
1702  bool InstantiationDependent = false;
1703  bool ContainsUnexpandedParameterPack = false;
1704  E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1705  TemplateKWLoc, *TemplateArgs,
1706  E->getTrailingObjects<TemplateArgumentLoc>(), Dependent,
1707  InstantiationDependent, ContainsUnexpandedParameterPack);
1708  if (InstantiationDependent)
1709  E->setInstantiationDependent(true);
1710  } else if (TemplateKWLoc.isValid()) {
1711  E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1712  TemplateKWLoc);
1713  }
1714 
1715  return E;
1716 }
1717 
1719  bool HasQualifier, bool HasFoundDecl,
1720  bool HasTemplateKWAndArgsInfo,
1721  unsigned NumTemplateArgs) {
1722  assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1723  "template args but no template arg info?");
1724  bool HasQualOrFound = HasQualifier || HasFoundDecl;
1725  std::size_t Size =
1727  TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1728  HasTemplateKWAndArgsInfo ? 1 : 0,
1729  NumTemplateArgs);
1730  void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1731  return new (Mem) MemberExpr(EmptyShell());
1732 }
1733 
1735  if (isImplicitAccess()) {
1736  if (hasQualifier())
1737  return getQualifierLoc().getBeginLoc();
1738  return MemberLoc;
1739  }
1740 
1741  // FIXME: We don't want this to happen. Rather, we should be able to
1742  // detect all kinds of implicit accesses more cleanly.
1743  SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1744  if (BaseStartLoc.isValid())
1745  return BaseStartLoc;
1746  return MemberLoc;
1747 }
1749  SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1750  if (hasExplicitTemplateArgs())
1751  EndLoc = getRAngleLoc();
1752  else if (EndLoc.isInvalid())
1753  EndLoc = getBase()->getEndLoc();
1754  return EndLoc;
1755 }
1756 
1757 bool CastExpr::CastConsistency() const {
1758  switch (getCastKind()) {
1759  case CK_DerivedToBase:
1760  case CK_UncheckedDerivedToBase:
1761  case CK_DerivedToBaseMemberPointer:
1762  case CK_BaseToDerived:
1763  case CK_BaseToDerivedMemberPointer:
1764  assert(!path_empty() && "Cast kind should have a base path!");
1765  break;
1766 
1767  case CK_CPointerToObjCPointerCast:
1768  assert(getType()->isObjCObjectPointerType());
1769  assert(getSubExpr()->getType()->isPointerType());
1770  goto CheckNoBasePath;
1771 
1772  case CK_BlockPointerToObjCPointerCast:
1773  assert(getType()->isObjCObjectPointerType());
1774  assert(getSubExpr()->getType()->isBlockPointerType());
1775  goto CheckNoBasePath;
1776 
1777  case CK_ReinterpretMemberPointer:
1778  assert(getType()->isMemberPointerType());
1779  assert(getSubExpr()->getType()->isMemberPointerType());
1780  goto CheckNoBasePath;
1781 
1782  case CK_BitCast:
1783  // Arbitrary casts to C pointer types count as bitcasts.
1784  // Otherwise, we should only have block and ObjC pointer casts
1785  // here if they stay within the type kind.
1786  if (!getType()->isPointerType()) {
1787  assert(getType()->isObjCObjectPointerType() ==
1788  getSubExpr()->getType()->isObjCObjectPointerType());
1789  assert(getType()->isBlockPointerType() ==
1790  getSubExpr()->getType()->isBlockPointerType());
1791  }
1792  goto CheckNoBasePath;
1793 
1794  case CK_AnyPointerToBlockPointerCast:
1795  assert(getType()->isBlockPointerType());
1796  assert(getSubExpr()->getType()->isAnyPointerType() &&
1797  !getSubExpr()->getType()->isBlockPointerType());
1798  goto CheckNoBasePath;
1799 
1800  case CK_CopyAndAutoreleaseBlockObject:
1801  assert(getType()->isBlockPointerType());
1802  assert(getSubExpr()->getType()->isBlockPointerType());
1803  goto CheckNoBasePath;
1804 
1805  case CK_FunctionToPointerDecay:
1806  assert(getType()->isPointerType());
1807  assert(getSubExpr()->getType()->isFunctionType());
1808  goto CheckNoBasePath;
1809 
1810  case CK_AddressSpaceConversion: {
1811  auto Ty = getType();
1812  auto SETy = getSubExpr()->getType();
1813  assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1814  if (/*isRValue()*/ !Ty->getPointeeType().isNull()) {
1815  Ty = Ty->getPointeeType();
1816  SETy = SETy->getPointeeType();
1817  }
1818  assert(!Ty.isNull() && !SETy.isNull() &&
1819  Ty.getAddressSpace() != SETy.getAddressSpace());
1820  goto CheckNoBasePath;
1821  }
1822  // These should not have an inheritance path.
1823  case CK_Dynamic:
1824  case CK_ToUnion:
1825  case CK_ArrayToPointerDecay:
1826  case CK_NullToMemberPointer:
1827  case CK_NullToPointer:
1828  case CK_ConstructorConversion:
1829  case CK_IntegralToPointer:
1830  case CK_PointerToIntegral:
1831  case CK_ToVoid:
1832  case CK_VectorSplat:
1833  case CK_IntegralCast:
1834  case CK_BooleanToSignedIntegral:
1835  case CK_IntegralToFloating:
1836  case CK_FloatingToIntegral:
1837  case CK_FloatingCast:
1838  case CK_ObjCObjectLValueCast:
1839  case CK_FloatingRealToComplex:
1840  case CK_FloatingComplexToReal:
1841  case CK_FloatingComplexCast:
1842  case CK_FloatingComplexToIntegralComplex:
1843  case CK_IntegralRealToComplex:
1844  case CK_IntegralComplexToReal:
1845  case CK_IntegralComplexCast:
1846  case CK_IntegralComplexToFloatingComplex:
1847  case CK_ARCProduceObject:
1848  case CK_ARCConsumeObject:
1849  case CK_ARCReclaimReturnedObject:
1850  case CK_ARCExtendBlockObject:
1851  case CK_ZeroToOCLOpaqueType:
1852  case CK_IntToOCLSampler:
1853  case CK_FixedPointCast:
1854  case CK_FixedPointToIntegral:
1855  case CK_IntegralToFixedPoint:
1856  assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1857  goto CheckNoBasePath;
1858 
1859  case CK_Dependent:
1860  case CK_LValueToRValue:
1861  case CK_NoOp:
1862  case CK_AtomicToNonAtomic:
1863  case CK_NonAtomicToAtomic:
1864  case CK_PointerToBoolean:
1865  case CK_IntegralToBoolean:
1866  case CK_FloatingToBoolean:
1867  case CK_MemberPointerToBoolean:
1868  case CK_FloatingComplexToBoolean:
1869  case CK_IntegralComplexToBoolean:
1870  case CK_LValueBitCast: // -> bool&
1871  case CK_LValueToRValueBitCast:
1872  case CK_UserDefinedConversion: // operator bool()
1873  case CK_BuiltinFnToFnPtr:
1874  case CK_FixedPointToBoolean:
1875  CheckNoBasePath:
1876  assert(path_empty() && "Cast kind should not have a base path!");
1877  break;
1878  }
1879  return true;
1880 }
1881 
1883  switch (CK) {
1884 #define CAST_OPERATION(Name) case CK_##Name: return #Name;
1885 #include "clang/AST/OperationKinds.def"
1886  }
1887  llvm_unreachable("Unhandled cast kind!");
1888 }
1889 
1890 namespace {
1891  const Expr *skipImplicitTemporary(const Expr *E) {
1892  // Skip through reference binding to temporary.
1893  if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1894  E = Materialize->GetTemporaryExpr();
1895 
1896  // Skip any temporary bindings; they're implicit.
1897  if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1898  E = Binder->getSubExpr();
1899 
1900  return E;
1901  }
1902 }
1903 
1905  const Expr *SubExpr = nullptr;
1906  const CastExpr *E = this;
1907  do {
1908  SubExpr = skipImplicitTemporary(E->getSubExpr());
1909 
1910  // Conversions by constructor and conversion functions have a
1911  // subexpression describing the call; strip it off.
1912  if (E->getCastKind() == CK_ConstructorConversion)
1913  SubExpr =
1914  skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
1915  else if (E->getCastKind() == CK_UserDefinedConversion) {
1916  assert((isa<CXXMemberCallExpr>(SubExpr) ||
1917  isa<BlockExpr>(SubExpr)) &&
1918  "Unexpected SubExpr for CK_UserDefinedConversion.");
1919  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1920  SubExpr = MCE->getImplicitObjectArgument();
1921  }
1922 
1923  // If the subexpression we're left with is an implicit cast, look
1924  // through that, too.
1925  } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1926 
1927  return const_cast<Expr*>(SubExpr);
1928 }
1929 
1931  const Expr *SubExpr = nullptr;
1932 
1933  for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1934  SubExpr = skipImplicitTemporary(E->getSubExpr());
1935 
1936  if (E->getCastKind() == CK_ConstructorConversion)
1937  return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1938 
1939  if (E->getCastKind() == CK_UserDefinedConversion) {
1940  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1941  return MCE->getMethodDecl();
1942  }
1943  }
1944 
1945  return nullptr;
1946 }
1947 
1948 CXXBaseSpecifier **CastExpr::path_buffer() {
1949  switch (getStmtClass()) {
1950 #define ABSTRACT_STMT(x)
1951 #define CASTEXPR(Type, Base) \
1952  case Stmt::Type##Class: \
1953  return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1954 #define STMT(Type, Base)
1955 #include "clang/AST/StmtNodes.inc"
1956  default:
1957  llvm_unreachable("non-cast expressions not possible here");
1958  }
1959 }
1960 
1962  QualType opType) {
1963  auto RD = unionType->castAs<RecordType>()->getDecl();
1964  return getTargetFieldForToUnionCast(RD, opType);
1965 }
1966 
1968  QualType OpType) {
1969  auto &Ctx = RD->getASTContext();
1970  RecordDecl::field_iterator Field, FieldEnd;
1971  for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1972  Field != FieldEnd; ++Field) {
1973  if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1974  !Field->isUnnamedBitfield()) {
1975  return *Field;
1976  }
1977  }
1978  return nullptr;
1979 }
1980 
1982  CastKind Kind, Expr *Operand,
1983  const CXXCastPath *BasePath,
1984  ExprValueKind VK) {
1985  unsigned PathSize = (BasePath ? BasePath->size() : 0);
1986  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1987  // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
1988  // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
1989  assert((Kind != CK_LValueToRValue ||
1990  !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
1991  "invalid type for lvalue-to-rvalue conversion");
1992  ImplicitCastExpr *E =
1993  new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1994  if (PathSize)
1995  std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1996  E->getTrailingObjects<CXXBaseSpecifier *>());
1997  return E;
1998 }
1999 
2001  unsigned PathSize) {
2002  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
2003  return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
2004 }
2005 
2006 
2008  ExprValueKind VK, CastKind K, Expr *Op,
2009  const CXXCastPath *BasePath,
2010  TypeSourceInfo *WrittenTy,
2012  unsigned PathSize = (BasePath ? BasePath->size() : 0);
2013  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
2014  CStyleCastExpr *E =
2015  new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
2016  if (PathSize)
2017  std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2018  E->getTrailingObjects<CXXBaseSpecifier *>());
2019  return E;
2020 }
2021 
2023  unsigned PathSize) {
2024  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
2025  return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
2026 }
2027 
2028 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2029 /// corresponds to, e.g. "<<=".
2031  switch (Op) {
2032 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2033 #include "clang/AST/OperationKinds.def"
2034  }
2035  llvm_unreachable("Invalid OpCode!");
2036 }
2037 
2040  switch (OO) {
2041  default: llvm_unreachable("Not an overloadable binary operator");
2042  case OO_Plus: return BO_Add;
2043  case OO_Minus: return BO_Sub;
2044  case OO_Star: return BO_Mul;
2045  case OO_Slash: return BO_Div;
2046  case OO_Percent: return BO_Rem;
2047  case OO_Caret: return BO_Xor;
2048  case OO_Amp: return BO_And;
2049  case OO_Pipe: return BO_Or;
2050  case OO_Equal: return BO_Assign;
2051  case OO_Spaceship: return BO_Cmp;
2052  case OO_Less: return BO_LT;
2053  case OO_Greater: return BO_GT;
2054  case OO_PlusEqual: return BO_AddAssign;
2055  case OO_MinusEqual: return BO_SubAssign;
2056  case OO_StarEqual: return BO_MulAssign;
2057  case OO_SlashEqual: return BO_DivAssign;
2058  case OO_PercentEqual: return BO_RemAssign;
2059  case OO_CaretEqual: return BO_XorAssign;
2060  case OO_AmpEqual: return BO_AndAssign;
2061  case OO_PipeEqual: return BO_OrAssign;
2062  case OO_LessLess: return BO_Shl;
2063  case OO_GreaterGreater: return BO_Shr;
2064  case OO_LessLessEqual: return BO_ShlAssign;
2065  case OO_GreaterGreaterEqual: return BO_ShrAssign;
2066  case OO_EqualEqual: return BO_EQ;
2067  case OO_ExclaimEqual: return BO_NE;
2068  case OO_LessEqual: return BO_LE;
2069  case OO_GreaterEqual: return BO_GE;
2070  case OO_AmpAmp: return BO_LAnd;
2071  case OO_PipePipe: return BO_LOr;
2072  case OO_Comma: return BO_Comma;
2073  case OO_ArrowStar: return BO_PtrMemI;
2074  }
2075 }
2076 
2078  static const OverloadedOperatorKind OverOps[] = {
2079  /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2080  OO_Star, OO_Slash, OO_Percent,
2081  OO_Plus, OO_Minus,
2082  OO_LessLess, OO_GreaterGreater,
2083  OO_Spaceship,
2084  OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2085  OO_EqualEqual, OO_ExclaimEqual,
2086  OO_Amp,
2087  OO_Caret,
2088  OO_Pipe,
2089  OO_AmpAmp,
2090  OO_PipePipe,
2091  OO_Equal, OO_StarEqual,
2092  OO_SlashEqual, OO_PercentEqual,
2093  OO_PlusEqual, OO_MinusEqual,
2094  OO_LessLessEqual, OO_GreaterGreaterEqual,
2095  OO_AmpEqual, OO_CaretEqual,
2096  OO_PipeEqual,
2097  OO_Comma
2098  };
2099  return OverOps[Opc];
2100 }
2101 
2103  Opcode Opc,
2104  Expr *LHS, Expr *RHS) {
2105  if (Opc != BO_Add)
2106  return false;
2107 
2108  // Check that we have one pointer and one integer operand.
2109  Expr *PExp;
2110  if (LHS->getType()->isPointerType()) {
2111  if (!RHS->getType()->isIntegerType())
2112  return false;
2113  PExp = LHS;
2114  } else if (RHS->getType()->isPointerType()) {
2115  if (!LHS->getType()->isIntegerType())
2116  return false;
2117  PExp = RHS;
2118  } else {
2119  return false;
2120  }
2121 
2122  // Check that the pointer is a nullptr.
2123  if (!PExp->IgnoreParenCasts()
2125  return false;
2126 
2127  // Check that the pointee type is char-sized.
2128  const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2129  if (!PTy || !PTy->getPointeeType()->isCharType())
2130  return false;
2131 
2132  return true;
2133 }
2134 
2137  switch (Kind) {
2138  case SourceLocExpr::File:
2139  case SourceLocExpr::Function: {
2140  QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2141  return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2142  }
2143  case SourceLocExpr::Line:
2144  case SourceLocExpr::Column:
2145  return Ctx.UnsignedIntTy;
2146  }
2147  llvm_unreachable("unhandled case");
2148 }
2149 
2151  SourceLocation BLoc, SourceLocation RParenLoc,
2152  DeclContext *ParentContext)
2153  : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2155  BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2156  SourceLocExprBits.Kind = Kind;
2157 }
2158 
2159 StringRef SourceLocExpr::getBuiltinStr() const {
2160  switch (getIdentKind()) {
2161  case File:
2162  return "__builtin_FILE";
2163  case Function:
2164  return "__builtin_FUNCTION";
2165  case Line:
2166  return "__builtin_LINE";
2167  case Column:
2168  return "__builtin_COLUMN";
2169  }
2170  llvm_unreachable("unexpected IdentKind!");
2171 }
2172 
2174  const Expr *DefaultExpr) const {
2175  SourceLocation Loc;
2176  const DeclContext *Context;
2177 
2178  std::tie(Loc,
2179  Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2180  if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2181  return {DIE->getUsedLocation(), DIE->getUsedContext()};
2182  if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2183  return {DAE->getUsedLocation(), DAE->getUsedContext()};
2184  return {this->getLocation(), this->getParentContext()};
2185  }();
2186 
2189 
2190  auto MakeStringLiteral = [&](StringRef Tmp) {
2191  using LValuePathEntry = APValue::LValuePathEntry;
2193  // Decay the string to a pointer to the first character.
2194  LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2195  return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2196  };
2197 
2198  switch (getIdentKind()) {
2199  case SourceLocExpr::File:
2200  return MakeStringLiteral(PLoc.getFilename());
2201  case SourceLocExpr::Function: {
2202  const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2203  return MakeStringLiteral(
2205  : std::string(""));
2206  }
2207  case SourceLocExpr::Line:
2208  case SourceLocExpr::Column: {
2209  llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2210  /*isUnsigned=*/true);
2211  IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2212  : PLoc.getColumn();
2213  return APValue(IntVal);
2214  }
2215  }
2216  llvm_unreachable("unhandled case");
2217 }
2218 
2220  ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
2221  : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
2222  false, false),
2223  InitExprs(C, initExprs.size()),
2224  LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
2225 {
2226  sawArrayRangeDesignator(false);
2227  for (unsigned I = 0; I != initExprs.size(); ++I) {
2228  if (initExprs[I]->isTypeDependent())
2229  ExprBits.TypeDependent = true;
2230  if (initExprs[I]->isValueDependent())
2231  ExprBits.ValueDependent = true;
2232  if (initExprs[I]->isInstantiationDependent())
2233  ExprBits.InstantiationDependent = true;
2234  if (initExprs[I]->containsUnexpandedParameterPack())
2235  ExprBits.ContainsUnexpandedParameterPack = true;
2236  }
2237 
2238  InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2239 }
2240 
2241 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2242  if (NumInits > InitExprs.size())
2243  InitExprs.reserve(C, NumInits);
2244 }
2245 
2246 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2247  InitExprs.resize(C, NumInits, nullptr);
2248 }
2249 
2250 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2251  if (Init >= InitExprs.size()) {
2252  InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2253  setInit(Init, expr);
2254  return nullptr;
2255  }
2256 
2257  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2258  setInit(Init, expr);
2259  return Result;
2260 }
2261 
2263  assert(!hasArrayFiller() && "Filler already set!");
2264  ArrayFillerOrUnionFieldInit = filler;
2265  // Fill out any "holes" in the array due to designated initializers.
2266  Expr **inits = getInits();
2267  for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2268  if (inits[i] == nullptr)
2269  inits[i] = filler;
2270 }
2271 
2273  if (getNumInits() != 1)
2274  return false;
2275  const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2276  if (!AT || !AT->getElementType()->isIntegerType())
2277  return false;
2278  // It is possible for getInit() to return null.
2279  const Expr *Init = getInit(0);
2280  if (!Init)
2281  return false;
2282  Init = Init->IgnoreParens();
2283  return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2284 }
2285 
2287  assert(isSemanticForm() && "syntactic form never semantically transparent");
2288 
2289  // A glvalue InitListExpr is always just sugar.
2290  if (isGLValue()) {
2291  assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2292  return true;
2293  }
2294 
2295  // Otherwise, we're sugar if and only if we have exactly one initializer that
2296  // is of the same type.
2297  if (getNumInits() != 1 || !getInit(0))
2298  return false;
2299 
2300  // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2301  // transparent struct copy.
2302  if (!getInit(0)->isRValue() && getType()->isRecordType())
2303  return false;
2304 
2305  return getType().getCanonicalType() ==
2307 }
2308 
2310  assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2311 
2312  if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2313  return false;
2314  }
2315 
2316  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2317  return Lit && Lit->getValue() == 0;
2318 }
2319 
2321  if (InitListExpr *SyntacticForm = getSyntacticForm())
2322  return SyntacticForm->getBeginLoc();
2323  SourceLocation Beg = LBraceLoc;
2324  if (Beg.isInvalid()) {
2325  // Find the first non-null initializer.
2326  for (InitExprsTy::const_iterator I = InitExprs.begin(),
2327  E = InitExprs.end();
2328  I != E; ++I) {
2329  if (Stmt *S = *I) {
2330  Beg = S->getBeginLoc();
2331  break;
2332  }
2333  }
2334  }
2335  return Beg;
2336 }
2337 
2339  if (InitListExpr *SyntacticForm = getSyntacticForm())
2340  return SyntacticForm->getEndLoc();
2341  SourceLocation End = RBraceLoc;
2342  if (End.isInvalid()) {
2343  // Find the first non-null initializer from the end.
2344  for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
2345  E = InitExprs.rend();
2346  I != E; ++I) {
2347  if (Stmt *S = *I) {
2348  End = S->getEndLoc();
2349  break;
2350  }
2351  }
2352  }
2353  return End;
2354 }
2355 
2356 /// getFunctionType - Return the underlying function type for this block.
2357 ///
2359  // The block pointer is never sugared, but the function type might be.
2360  return cast<BlockPointerType>(getType())
2361  ->getPointeeType()->castAs<FunctionProtoType>();
2362 }
2363 
2365  return TheBlock->getCaretLocation();
2366 }
2367 const Stmt *BlockExpr::getBody() const {
2368  return TheBlock->getBody();
2369 }
2371  return TheBlock->getBody();
2372 }
2373 
2374 
2375 //===----------------------------------------------------------------------===//
2376 // Generic Expression Routines
2377 //===----------------------------------------------------------------------===//
2378 
2379 /// isUnusedResultAWarning - Return true if this immediate expression should
2380 /// be warned about if the result is unused. If so, fill in Loc and Ranges
2381 /// with location to warn on and the source range[s] to report with the
2382 /// warning.
2384  SourceRange &R1, SourceRange &R2,
2385  ASTContext &Ctx) const {
2386  // Don't warn if the expr is type dependent. The type could end up
2387  // instantiating to void.
2388  if (isTypeDependent())
2389  return false;
2390 
2391  switch (getStmtClass()) {
2392  default:
2393  if (getType()->isVoidType())
2394  return false;
2395  WarnE = this;
2396  Loc = getExprLoc();
2397  R1 = getSourceRange();
2398  return true;
2399  case ParenExprClass:
2400  return cast<ParenExpr>(this)->getSubExpr()->
2401  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2402  case GenericSelectionExprClass:
2403  return cast<GenericSelectionExpr>(this)->getResultExpr()->
2404  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2405  case CoawaitExprClass:
2406  case CoyieldExprClass:
2407  return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2408  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2409  case ChooseExprClass:
2410  return cast<ChooseExpr>(this)->getChosenSubExpr()->
2411  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2412  case UnaryOperatorClass: {
2413  const UnaryOperator *UO = cast<UnaryOperator>(this);
2414 
2415  switch (UO->getOpcode()) {
2416  case UO_Plus:
2417  case UO_Minus:
2418  case UO_AddrOf:
2419  case UO_Not:
2420  case UO_LNot:
2421  case UO_Deref:
2422  break;
2423  case UO_Coawait:
2424  // This is just the 'operator co_await' call inside the guts of a
2425  // dependent co_await call.
2426  case UO_PostInc:
2427  case UO_PostDec:
2428  case UO_PreInc:
2429  case UO_PreDec: // ++/--
2430  return false; // Not a warning.
2431  case UO_Real:
2432  case UO_Imag:
2433  // accessing a piece of a volatile complex is a side-effect.
2434  if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2435  .isVolatileQualified())
2436  return false;
2437  break;
2438  case UO_Extension:
2439  return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2440  }
2441  WarnE = this;
2442  Loc = UO->getOperatorLoc();
2443  R1 = UO->getSubExpr()->getSourceRange();
2444  return true;
2445  }
2446  case BinaryOperatorClass: {
2447  const BinaryOperator *BO = cast<BinaryOperator>(this);
2448  switch (BO->getOpcode()) {
2449  default:
2450  break;
2451  // Consider the RHS of comma for side effects. LHS was checked by
2452  // Sema::CheckCommaOperands.
2453  case BO_Comma:
2454  // ((foo = <blah>), 0) is an idiom for hiding the result (and
2455  // lvalue-ness) of an assignment written in a macro.
2456  if (IntegerLiteral *IE =
2457  dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2458  if (IE->getValue() == 0)
2459  return false;
2460  return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2461  // Consider '||', '&&' to have side effects if the LHS or RHS does.
2462  case BO_LAnd:
2463  case BO_LOr:
2464  if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2465  !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2466  return false;
2467  break;
2468  }
2469  if (BO->isAssignmentOp())
2470  return false;
2471  WarnE = this;
2472  Loc = BO->getOperatorLoc();
2473  R1 = BO->getLHS()->getSourceRange();
2474  R2 = BO->getRHS()->getSourceRange();
2475  return true;
2476  }
2477  case CompoundAssignOperatorClass:
2478  case VAArgExprClass:
2479  case AtomicExprClass:
2480  return false;
2481 
2482  case ConditionalOperatorClass: {
2483  // If only one of the LHS or RHS is a warning, the operator might
2484  // be being used for control flow. Only warn if both the LHS and
2485  // RHS are warnings.
2486  const auto *Exp = cast<ConditionalOperator>(this);
2487  return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2488  Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2489  }
2490  case BinaryConditionalOperatorClass: {
2491  const auto *Exp = cast<BinaryConditionalOperator>(this);
2492  return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2493  }
2494 
2495  case MemberExprClass:
2496  WarnE = this;
2497  Loc = cast<MemberExpr>(this)->getMemberLoc();
2498  R1 = SourceRange(Loc, Loc);
2499  R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2500  return true;
2501 
2502  case ArraySubscriptExprClass:
2503  WarnE = this;
2504  Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2505  R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2506  R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2507  return true;
2508 
2509  case CXXOperatorCallExprClass: {
2510  // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2511  // overloads as there is no reasonable way to define these such that they
2512  // have non-trivial, desirable side-effects. See the -Wunused-comparison
2513  // warning: operators == and != are commonly typo'ed, and so warning on them
2514  // provides additional value as well. If this list is updated,
2515  // DiagnoseUnusedComparison should be as well.
2516  const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2517  switch (Op->getOperator()) {
2518  default:
2519  break;
2520  case OO_EqualEqual:
2521  case OO_ExclaimEqual:
2522  case OO_Less:
2523  case OO_Greater:
2524  case OO_GreaterEqual:
2525  case OO_LessEqual:
2526  if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2527  Op->getCallReturnType(Ctx)->isVoidType())
2528  break;
2529  WarnE = this;
2530  Loc = Op->getOperatorLoc();
2531  R1 = Op->getSourceRange();
2532  return true;
2533  }
2534 
2535  // Fallthrough for generic call handling.
2536  LLVM_FALLTHROUGH;
2537  }
2538  case CallExprClass:
2539  case CXXMemberCallExprClass:
2540  case UserDefinedLiteralClass: {
2541  // If this is a direct call, get the callee.
2542  const CallExpr *CE = cast<CallExpr>(this);
2543  if (const Decl *FD = CE->getCalleeDecl()) {
2544  // If the callee has attribute pure, const, or warn_unused_result, warn
2545  // about it. void foo() { strlen("bar"); } should warn.
2546  //
2547  // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2548  // updated to match for QoI.
2549  if (CE->hasUnusedResultAttr(Ctx) ||
2550  FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2551  WarnE = this;
2552  Loc = CE->getCallee()->getBeginLoc();
2553  R1 = CE->getCallee()->getSourceRange();
2554 
2555  if (unsigned NumArgs = CE->getNumArgs())
2556  R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2557  CE->getArg(NumArgs - 1)->getEndLoc());
2558  return true;
2559  }
2560  }
2561  return false;
2562  }
2563 
2564  // If we don't know precisely what we're looking at, let's not warn.
2565  case UnresolvedLookupExprClass:
2566  case CXXUnresolvedConstructExprClass:
2567  return false;
2568 
2569  case CXXTemporaryObjectExprClass:
2570  case CXXConstructExprClass: {
2571  if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2572  const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2573  if (Type->hasAttr<WarnUnusedAttr>() ||
2574  (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2575  WarnE = this;
2576  Loc = getBeginLoc();
2577  R1 = getSourceRange();
2578  return true;
2579  }
2580  }
2581 
2582  const auto *CE = cast<CXXConstructExpr>(this);
2583  if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2584  const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2585  if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2586  WarnE = this;
2587  Loc = getBeginLoc();
2588  R1 = getSourceRange();
2589 
2590  if (unsigned NumArgs = CE->getNumArgs())
2591  R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2592  CE->getArg(NumArgs - 1)->getEndLoc());
2593  return true;
2594  }
2595  }
2596 
2597  return false;
2598  }
2599 
2600  case ObjCMessageExprClass: {
2601  const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2602  if (Ctx.getLangOpts().ObjCAutoRefCount &&
2603  ME->isInstanceMessage() &&
2604  !ME->getType()->isVoidType() &&
2605  ME->getMethodFamily() == OMF_init) {
2606  WarnE = this;
2607  Loc = getExprLoc();
2608  R1 = ME->getSourceRange();
2609  return true;
2610  }
2611 
2612  if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2613  if (MD->hasAttr<WarnUnusedResultAttr>()) {
2614  WarnE = this;
2615  Loc = getExprLoc();
2616  return true;
2617  }
2618 
2619  return false;
2620  }
2621 
2622  case ObjCPropertyRefExprClass:
2623  WarnE = this;
2624  Loc = getExprLoc();
2625  R1 = getSourceRange();
2626  return true;
2627 
2628  case PseudoObjectExprClass: {
2629  const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2630 
2631  // Only complain about things that have the form of a getter.
2632  if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2633  isa<BinaryOperator>(PO->getSyntacticForm()))
2634  return false;
2635 
2636  WarnE = this;
2637  Loc = getExprLoc();
2638  R1 = getSourceRange();
2639  return true;
2640  }
2641 
2642  case StmtExprClass: {
2643  // Statement exprs don't logically have side effects themselves, but are
2644  // sometimes used in macros in ways that give them a type that is unused.
2645  // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2646  // however, if the result of the stmt expr is dead, we don't want to emit a
2647  // warning.
2648  const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2649  if (!CS->body_empty()) {
2650  if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2651  return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2652  if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2653  if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2654  return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2655  }
2656 
2657  if (getType()->isVoidType())
2658  return false;
2659  WarnE = this;
2660  Loc = cast<StmtExpr>(this)->getLParenLoc();
2661  R1 = getSourceRange();
2662  return true;
2663  }
2664  case CXXFunctionalCastExprClass:
2665  case CStyleCastExprClass: {
2666  // Ignore an explicit cast to void unless the operand is a non-trivial
2667  // volatile lvalue.
2668  const CastExpr *CE = cast<CastExpr>(this);
2669  if (CE->getCastKind() == CK_ToVoid) {
2670  if (CE->getSubExpr()->isGLValue() &&
2671  CE->getSubExpr()->getType().isVolatileQualified()) {
2672  const DeclRefExpr *DRE =
2673  dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2674  if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2675  cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2676  !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
2677  return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2678  R1, R2, Ctx);
2679  }
2680  }
2681  return false;
2682  }
2683 
2684  // If this is a cast to a constructor conversion, check the operand.
2685  // Otherwise, the result of the cast is unused.
2686  if (CE->getCastKind() == CK_ConstructorConversion)
2687  return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2688 
2689  WarnE = this;
2690  if (const CXXFunctionalCastExpr *CXXCE =
2691  dyn_cast<CXXFunctionalCastExpr>(this)) {
2692  Loc = CXXCE->getBeginLoc();
2693  R1 = CXXCE->getSubExpr()->getSourceRange();
2694  } else {
2695  const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2696  Loc = CStyleCE->getLParenLoc();
2697  R1 = CStyleCE->getSubExpr()->getSourceRange();
2698  }
2699  return true;
2700  }
2701  case ImplicitCastExprClass: {
2702  const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2703 
2704  // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2705  if (ICE->getCastKind() == CK_LValueToRValue &&
2707  return false;
2708 
2709  return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2710  }
2711  case CXXDefaultArgExprClass:
2712  return (cast<CXXDefaultArgExpr>(this)
2713  ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2714  case CXXDefaultInitExprClass:
2715  return (cast<CXXDefaultInitExpr>(this)
2716  ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2717 
2718  case CXXNewExprClass:
2719  // FIXME: In theory, there might be new expressions that don't have side
2720  // effects (e.g. a placement new with an uninitialized POD).
2721  case CXXDeleteExprClass:
2722  return false;
2723  case MaterializeTemporaryExprClass:
2724  return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2725  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2726  case CXXBindTemporaryExprClass:
2727  return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2728  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2729  case ExprWithCleanupsClass:
2730  return cast<ExprWithCleanups>(this)->getSubExpr()
2731  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2732  }
2733 }
2734 
2735 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2736 /// returns true, if it is; false otherwise.
2738  const Expr *E = IgnoreParens();
2739  switch (E->getStmtClass()) {
2740  default:
2741  return false;
2742  case ObjCIvarRefExprClass:
2743  return true;
2744  case Expr::UnaryOperatorClass:
2745  return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2746  case ImplicitCastExprClass:
2747  return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2748  case MaterializeTemporaryExprClass:
2749  return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2750  ->isOBJCGCCandidate(Ctx);
2751  case CStyleCastExprClass:
2752  return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2753  case DeclRefExprClass: {
2754  const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2755 
2756  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2757  if (VD->hasGlobalStorage())
2758  return true;
2759  QualType T = VD->getType();
2760  // dereferencing to a pointer is always a gc'able candidate,
2761  // unless it is __weak.
2762  return T->isPointerType() &&
2763  (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2764  }
2765  return false;
2766  }
2767  case MemberExprClass: {
2768  const MemberExpr *M = cast<MemberExpr>(E);
2769  return M->getBase()->isOBJCGCCandidate(Ctx);
2770  }
2771  case ArraySubscriptExprClass:
2772  return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2773  }
2774 }
2775 
2777  if (isTypeDependent())
2778  return false;
2779  return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2780 }
2781 
2783  assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2784 
2785  // Bound member expressions are always one of these possibilities:
2786  // x->m x.m x->*y x.*y
2787  // (possibly parenthesized)
2788 
2789  expr = expr->IgnoreParens();
2790  if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2791  assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2792  return mem->getMemberDecl()->getType();
2793  }
2794 
2795  if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2796  QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2797  ->getPointeeType();
2798  assert(type->isFunctionType());
2799  return type;
2800  }
2801 
2802  assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
2803  return QualType();
2804 }
2805 
2807  if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2808  return ICE->getSubExpr();
2809 
2810  if (auto *FE = dyn_cast<FullExpr>(E))
2811  return FE->getSubExpr();
2812 
2813  return E;
2814 }
2815 
2817  // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2818  // addition to what IgnoreImpCasts() skips to account for the current
2819  // behaviour of IgnoreParenImpCasts().
2820  Expr *SubE = IgnoreImpCastsSingleStep(E);
2821  if (SubE != E)
2822  return SubE;
2823 
2824  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2825  return MTE->GetTemporaryExpr();
2826 
2827  if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2828  return NTTP->getReplacement();
2829 
2830  return E;
2831 }
2832 
2834  if (auto *CE = dyn_cast<CastExpr>(E))
2835  return CE->getSubExpr();
2836 
2837  if (auto *FE = dyn_cast<FullExpr>(E))
2838  return FE->getSubExpr();
2839 
2840  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2841  return MTE->GetTemporaryExpr();
2842 
2843  if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2844  return NTTP->getReplacement();
2845 
2846  return E;
2847 }
2848 
2850  // Skip what IgnoreCastsSingleStep skips, except that only
2851  // lvalue-to-rvalue casts are skipped.
2852  if (auto *CE = dyn_cast<CastExpr>(E))
2853  if (CE->getCastKind() != CK_LValueToRValue)
2854  return E;
2855 
2856  return IgnoreCastsSingleStep(E);
2857 }
2858 
2860  if (auto *CE = dyn_cast<CastExpr>(E))
2861  if (CE->getCastKind() == CK_DerivedToBase ||
2862  CE->getCastKind() == CK_UncheckedDerivedToBase ||
2863  CE->getCastKind() == CK_NoOp)
2864  return CE->getSubExpr();
2865 
2866  return E;
2867 }
2868 
2870  Expr *SubE = IgnoreImpCastsSingleStep(E);
2871  if (SubE != E)
2872  return SubE;
2873 
2874  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2875  return MTE->GetTemporaryExpr();
2876 
2877  if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2878  return BTE->getSubExpr();
2879 
2880  return E;
2881 }
2882 
2884  if (auto *PE = dyn_cast<ParenExpr>(E))
2885  return PE->getSubExpr();
2886 
2887  if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2888  if (UO->getOpcode() == UO_Extension)
2889  return UO->getSubExpr();
2890  }
2891 
2892  else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2893  if (!GSE->isResultDependent())
2894  return GSE->getResultExpr();
2895  }
2896 
2897  else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2898  if (!CE->isConditionDependent())
2899  return CE->getChosenSubExpr();
2900  }
2901 
2902  else if (auto *CE = dyn_cast<ConstantExpr>(E))
2903  return CE->getSubExpr();
2904 
2905  return E;
2906 }
2907 
2909  if (auto *CE = dyn_cast<CastExpr>(E)) {
2910  // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2911  // ptr<->int casts of the same width. We also ignore all identity casts.
2912  Expr *SubExpr = CE->getSubExpr();
2913  bool IsIdentityCast =
2914  Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2915  bool IsSameWidthCast =
2916  (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2917  (SubExpr->getType()->isPointerType() ||
2918  SubExpr->getType()->isIntegralType(Ctx)) &&
2919  (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2920 
2921  if (IsIdentityCast || IsSameWidthCast)
2922  return SubExpr;
2923  }
2924 
2925  else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2926  return NTTP->getReplacement();
2927 
2928  return E;
2929 }
2930 
2931 static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2932 template <typename FnTy, typename... FnTys>
2933 static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2934  return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2935 }
2936 
2937 /// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2938 /// Recursively apply each of the functions to E until reaching a fixed point.
2939 /// Note that a null E is valid; in this case nothing is done.
2940 template <typename... FnTys>
2941 static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
2942  Expr *LastE = nullptr;
2943  while (E != LastE) {
2944  LastE = E;
2945  E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
2946  }
2947  return E;
2948 }
2949 
2952 }
2953 
2955  return IgnoreExprNodes(this, IgnoreCastsSingleStep);
2956 }
2957 
2960 }
2961 
2964 }
2965 
2969 }
2970 
2973 }
2974 
2976  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2977  if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2978  return MCE->getImplicitObjectArgument();
2979  }
2980  return this;
2981 }
2982 
2986 }
2987 
2991 }
2992 
2994  return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
2995  return IgnoreNoopCastsSingleStep(Ctx, E);
2996  });
2997 }
2998 
3000  const Expr *E = this;
3001  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3002  E = M->GetTemporaryExpr();
3003 
3004  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3005  E = ICE->getSubExprAsWritten();
3006 
3007  return isa<CXXDefaultArgExpr>(E);
3008 }
3009 
3010 /// Skip over any no-op casts and any temporary-binding
3011 /// expressions.
3013  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3014  E = M->GetTemporaryExpr();
3015 
3016  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3017  if (ICE->getCastKind() == CK_NoOp)
3018  E = ICE->getSubExpr();
3019  else
3020  break;
3021  }
3022 
3023  while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3024  E = BE->getSubExpr();
3025 
3026  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3027  if (ICE->getCastKind() == CK_NoOp)
3028  E = ICE->getSubExpr();
3029  else
3030  break;
3031  }
3032 
3033  return E->IgnoreParens();
3034 }
3035 
3036 /// isTemporaryObject - Determines if this expression produces a
3037 /// temporary of the given class type.
3038 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3039  if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3040  return false;
3041 
3043 
3044  // Temporaries are by definition pr-values of class type.
3045  if (!E->Classify(C).isPRValue()) {
3046  // In this context, property reference is a message call and is pr-value.
3047  if (!isa<ObjCPropertyRefExpr>(E))
3048  return false;
3049  }
3050 
3051  // Black-list a few cases which yield pr-values of class type that don't
3052  // refer to temporaries of that type:
3053 
3054  // - implicit derived-to-base conversions
3055  if (isa<ImplicitCastExpr>(E)) {
3056  switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3057  case CK_DerivedToBase:
3058  case CK_UncheckedDerivedToBase:
3059  return false;
3060  default:
3061  break;
3062  }
3063  }
3064 
3065  // - member expressions (all)
3066  if (isa<MemberExpr>(E))
3067  return false;
3068 
3069  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3070  if (BO->isPtrMemOp())
3071  return false;
3072 
3073  // - opaque values (all)
3074  if (isa<OpaqueValueExpr>(E))
3075  return false;
3076 
3077  return true;
3078 }
3079 
3081  const Expr *E = this;
3082 
3083  // Strip away parentheses and casts we don't care about.
3084  while (true) {
3085  if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3086  E = Paren->getSubExpr();
3087  continue;
3088  }
3089 
3090  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3091  if (ICE->getCastKind() == CK_NoOp ||
3092  ICE->getCastKind() == CK_LValueToRValue ||
3093  ICE->getCastKind() == CK_DerivedToBase ||
3094  ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3095  E = ICE->getSubExpr();
3096  continue;
3097  }
3098  }
3099 
3100  if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3101  if (UnOp->getOpcode() == UO_Extension) {
3102  E = UnOp->getSubExpr();
3103  continue;
3104  }
3105  }
3106 
3107  if (const MaterializeTemporaryExpr *M
3108  = dyn_cast<MaterializeTemporaryExpr>(E)) {
3109  E = M->GetTemporaryExpr();
3110  continue;
3111  }
3112 
3113  break;
3114  }
3115 
3116  if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3117  return This->isImplicit();
3118 
3119  return false;
3120 }
3121 
3122 /// hasAnyTypeDependentArguments - Determines if any of the expressions
3123 /// in Exprs is type-dependent.
3125  for (unsigned I = 0; I < Exprs.size(); ++I)
3126  if (Exprs[I]->isTypeDependent())
3127  return true;
3128 
3129  return false;
3130 }
3131 
3132 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3133  const Expr **Culprit) const {
3134  assert(!isValueDependent() &&
3135  "Expression evaluator can't be called on a dependent expression.");
3136 
3137  // This function is attempting whether an expression is an initializer
3138  // which can be evaluated at compile-time. It very closely parallels
3139  // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3140  // will lead to unexpected results. Like ConstExprEmitter, it falls back
3141  // to isEvaluatable most of the time.
3142  //
3143  // If we ever capture reference-binding directly in the AST, we can
3144  // kill the second parameter.
3145 
3146  if (IsForRef) {
3148  if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3149  return true;
3150  if (Culprit)
3151  *Culprit = this;
3152  return false;
3153  }
3154 
3155  switch (getStmtClass()) {
3156  default: break;
3157  case StringLiteralClass:
3158  case ObjCEncodeExprClass:
3159  return true;
3160  case CXXTemporaryObjectExprClass:
3161  case CXXConstructExprClass: {
3162  const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3163 
3164  if (CE->getConstructor()->isTrivial() &&
3166  // Trivial default constructor
3167  if (!CE->getNumArgs()) return true;
3168 
3169  // Trivial copy constructor
3170  assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3171  return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3172  }
3173 
3174  break;
3175  }
3176  case ConstantExprClass: {
3177  // FIXME: We should be able to return "true" here, but it can lead to extra
3178  // error messages. E.g. in Sema/array-init.c.
3179  const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3180  return Exp->isConstantInitializer(Ctx, false, Culprit);
3181  }
3182  case CompoundLiteralExprClass: {
3183  // This handles gcc's extension that allows global initializers like
3184  // "struct x {int x;} x = (struct x) {};".
3185  // FIXME: This accepts other cases it shouldn't!
3186  const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3187  return Exp->isConstantInitializer(Ctx, false, Culprit);
3188  }
3189  case DesignatedInitUpdateExprClass: {
3190  const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3191  return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3192  DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3193  }
3194  case InitListExprClass: {
3195  const InitListExpr *ILE = cast<InitListExpr>(this);
3196  assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3197  if (ILE->getType()->isArrayType()) {
3198  unsigned numInits = ILE->getNumInits();
3199  for (unsigned i = 0; i < numInits; i++) {
3200  if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3201  return false;
3202  }
3203  return true;
3204  }
3205 
3206  if (ILE->getType()->isRecordType()) {
3207  unsigned ElementNo = 0;
3208  RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
3209  for (const auto *Field : RD->fields()) {
3210  // If this is a union, skip all the fields that aren't being initialized.
3211  if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3212  continue;
3213 
3214  // Don't emit anonymous bitfields, they just affect layout.
3215  if (Field->isUnnamedBitfield())
3216  continue;
3217 
3218  if (ElementNo < ILE->getNumInits()) {
3219  const Expr *Elt = ILE->getInit(ElementNo++);
3220  if (Field->isBitField()) {
3221  // Bitfields have to evaluate to an integer.
3223  if (!Elt->EvaluateAsInt(Result, Ctx)) {
3224  if (Culprit)
3225  *Culprit = Elt;
3226  return false;
3227  }
3228  } else {
3229  bool RefType = Field->getType()->isReferenceType();
3230  if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3231  return false;
3232  }
3233  }
3234  }
3235  return true;
3236  }
3237 
3238  break;
3239  }
3240  case ImplicitValueInitExprClass:
3241  case NoInitExprClass:
3242  return true;
3243  case ParenExprClass:
3244  return cast<ParenExpr>(this)->getSubExpr()
3245  ->isConstantInitializer(Ctx, IsForRef, Culprit);
3246  case GenericSelectionExprClass:
3247  return cast<GenericSelectionExpr>(this)->getResultExpr()
3248  ->isConstantInitializer(Ctx, IsForRef, Culprit);
3249  case ChooseExprClass:
3250  if (cast<ChooseExpr>(this)->isConditionDependent()) {
3251  if (Culprit)
3252  *Culprit = this;
3253  return false;
3254  }
3255  return cast<ChooseExpr>(this)->getChosenSubExpr()
3256  ->isConstantInitializer(Ctx, IsForRef, Culprit);
3257  case UnaryOperatorClass: {
3258  const UnaryOperator* Exp = cast<UnaryOperator>(this);
3259  if (Exp->getOpcode() == UO_Extension)
3260  return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3261  break;
3262  }
3263  case CXXFunctionalCastExprClass:
3264  case CXXStaticCastExprClass:
3265  case ImplicitCastExprClass:
3266  case CStyleCastExprClass:
3267  case ObjCBridgedCastExprClass:
3268  case CXXDynamicCastExprClass:
3269  case CXXReinterpretCastExprClass:
3270  case CXXConstCastExprClass: {
3271  const CastExpr *CE = cast<CastExpr>(this);
3272 
3273  // Handle misc casts we want to ignore.
3274  if (CE->getCastKind() == CK_NoOp ||
3275  CE->getCastKind() == CK_LValueToRValue ||
3276  CE->getCastKind() == CK_ToUnion ||
3277  CE->getCastKind() == CK_ConstructorConversion ||
3278  CE->getCastKind() == CK_NonAtomicToAtomic ||
3279  CE->getCastKind() == CK_AtomicToNonAtomic ||
3280  CE->getCastKind() == CK_IntToOCLSampler)
3281  return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3282 
3283  break;
3284  }
3285  case MaterializeTemporaryExprClass:
3286  return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
3287  ->isConstantInitializer(Ctx, false, Culprit);
3288 
3289  case SubstNonTypeTemplateParmExprClass:
3290  return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3291  ->isConstantInitializer(Ctx, false, Culprit);
3292  case CXXDefaultArgExprClass:
3293  return cast<CXXDefaultArgExpr>(this)->getExpr()
3294  ->isConstantInitializer(Ctx, false, Culprit);
3295  case CXXDefaultInitExprClass:
3296  return cast<CXXDefaultInitExpr>(this)->getExpr()
3297  ->isConstantInitializer(Ctx, false, Culprit);
3298  }
3299  // Allow certain forms of UB in constant initializers: signed integer
3300  // overflow and floating-point division by zero. We'll give a warning on
3301  // these, but they're common enough that we have to accept them.
3303  return true;
3304  if (Culprit)
3305  *Culprit = this;
3306  return false;
3307 }
3308 
3310  const FunctionDecl* FD = getDirectCallee();
3311  if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3312  FD->getBuiltinID() != Builtin::BI__builtin_assume))
3313  return false;
3314 
3315  const Expr* Arg = getArg(0);
3316  bool ArgVal;
3317  return !Arg->isValueDependent() &&
3318  Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3319 }
3320 
3321 namespace {
3322  /// Look for any side effects within a Stmt.
3323  class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3325  const bool IncludePossibleEffects;
3326  bool HasSideEffects;
3327 
3328  public:
3329  explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3330  : Inherited(Context),
3331  IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3332 
3333  bool hasSideEffects() const { return HasSideEffects; }
3334 
3335  void VisitExpr(const Expr *E) {
3336  if (!HasSideEffects &&
3337  E->HasSideEffects(Context, IncludePossibleEffects))
3338  HasSideEffects = true;
3339  }
3340  };
3341 }
3342 
3344  bool IncludePossibleEffects) const {
3345  // In circumstances where we care about definite side effects instead of
3346  // potential side effects, we want to ignore expressions that are part of a
3347  // macro expansion as a potential side effect.
3348  if (!IncludePossibleEffects && getExprLoc().isMacroID())
3349  return false;
3350 
3352  return IncludePossibleEffects;
3353 
3354  switch (getStmtClass()) {
3355  case NoStmtClass:
3356  #define ABSTRACT_STMT(Type)
3357  #define STMT(Type, Base) case Type##Class:
3358  #define EXPR(Type, Base)
3359  #include "clang/AST/StmtNodes.inc"
3360  llvm_unreachable("unexpected Expr kind");
3361 
3362  case DependentScopeDeclRefExprClass:
3363  case CXXUnresolvedConstructExprClass:
3364  case CXXDependentScopeMemberExprClass:
3365  case UnresolvedLookupExprClass:
3366  case UnresolvedMemberExprClass:
3367  case PackExpansionExprClass:
3368  case SubstNonTypeTemplateParmPackExprClass:
3369  case FunctionParmPackExprClass:
3370  case TypoExprClass:
3371  case CXXFoldExprClass:
3372  llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3373 
3374  case DeclRefExprClass:
3375  case ObjCIvarRefExprClass:
3376  case PredefinedExprClass:
3377  case IntegerLiteralClass:
3378  case FixedPointLiteralClass:
3379  case FloatingLiteralClass:
3380  case ImaginaryLiteralClass:
3381  case StringLiteralClass:
3382  case CharacterLiteralClass:
3383  case OffsetOfExprClass:
3384  case ImplicitValueInitExprClass:
3385  case UnaryExprOrTypeTraitExprClass:
3386  case AddrLabelExprClass:
3387  case GNUNullExprClass:
3388  case ArrayInitIndexExprClass:
3389  case NoInitExprClass:
3390  case CXXBoolLiteralExprClass:
3391  case CXXNullPtrLiteralExprClass:
3392  case CXXThisExprClass:
3393  case CXXScalarValueInitExprClass:
3394  case TypeTraitExprClass:
3395  case ArrayTypeTraitExprClass:
3396  case ExpressionTraitExprClass:
3397  case CXXNoexceptExprClass:
3398  case SizeOfPackExprClass:
3399  case ObjCStringLiteralClass:
3400  case ObjCEncodeExprClass:
3401  case ObjCBoolLiteralExprClass:
3402  case ObjCAvailabilityCheckExprClass:
3403  case CXXUuidofExprClass:
3404  case OpaqueValueExprClass:
3405  case SourceLocExprClass:
3406  // These never have a side-effect.
3407  return false;
3408 
3409  case ConstantExprClass:
3410  // FIXME: Move this into the "return false;" block above.
3411  return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3412  Ctx, IncludePossibleEffects);
3413 
3414  case CallExprClass:
3415  case CXXOperatorCallExprClass:
3416  case CXXMemberCallExprClass:
3417  case CUDAKernelCallExprClass:
3418  case UserDefinedLiteralClass: {
3419  // We don't know a call definitely has side effects, except for calls
3420  // to pure/const functions that definitely don't.
3421  // If the call itself is considered side-effect free, check the operands.
3422  const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3423  bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3424  if (IsPure || !IncludePossibleEffects)
3425  break;
3426  return true;
3427  }
3428 
3429  case BlockExprClass:
3430  case CXXBindTemporaryExprClass:
3431  if (!IncludePossibleEffects)
3432  break;
3433  return true;
3434 
3435  case MSPropertyRefExprClass:
3436  case MSPropertySubscriptExprClass:
3437  case CompoundAssignOperatorClass:
3438  case VAArgExprClass:
3439  case AtomicExprClass:
3440  case CXXThrowExprClass:
3441  case CXXNewExprClass:
3442  case CXXDeleteExprClass:
3443  case CoawaitExprClass:
3444  case DependentCoawaitExprClass:
3445  case CoyieldExprClass:
3446  // These always have a side-effect.
3447  return true;
3448 
3449  case StmtExprClass: {
3450  // StmtExprs have a side-effect if any substatement does.
3451  SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3452  Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3453  return Finder.hasSideEffects();
3454  }
3455 
3456  case ExprWithCleanupsClass:
3457  if (IncludePossibleEffects)
3458  if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3459  return true;
3460  break;
3461 
3462  case ParenExprClass:
3463  case ArraySubscriptExprClass:
3464  case OMPArraySectionExprClass:
3465  case MemberExprClass:
3466  case ConditionalOperatorClass:
3467  case BinaryConditionalOperatorClass:
3468  case CompoundLiteralExprClass:
3469  case ExtVectorElementExprClass:
3470  case DesignatedInitExprClass:
3471  case DesignatedInitUpdateExprClass:
3472  case ArrayInitLoopExprClass:
3473  case ParenListExprClass:
3474  case CXXPseudoDestructorExprClass:
3475  case CXXStdInitializerListExprClass:
3476  case SubstNonTypeTemplateParmExprClass:
3477  case MaterializeTemporaryExprClass:
3478  case ShuffleVectorExprClass:
3479  case ConvertVectorExprClass:
3480  case AsTypeExprClass:
3481  // These have a side-effect if any subexpression does.
3482  break;
3483 
3484  case UnaryOperatorClass:
3485  if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3486  return true;
3487  break;
3488 
3489  case BinaryOperatorClass:
3490  if (cast<BinaryOperator>(this)->isAssignmentOp())
3491  return true;
3492  break;
3493 
3494  case InitListExprClass:
3495  // FIXME: The children for an InitListExpr doesn't include the array filler.
3496  if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3497  if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3498  return true;
3499  break;
3500 
3501  case GenericSelectionExprClass:
3502  return cast<GenericSelectionExpr>(this)->getResultExpr()->
3503  HasSideEffects(Ctx, IncludePossibleEffects);
3504 
3505  case ChooseExprClass:
3506  return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3507  Ctx, IncludePossibleEffects);
3508 
3509  case CXXDefaultArgExprClass:
3510  return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3511  Ctx, IncludePossibleEffects);
3512 
3513  case CXXDefaultInitExprClass: {
3514  const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3515  if (const Expr *E = FD->getInClassInitializer())
3516  return E->HasSideEffects(Ctx, IncludePossibleEffects);
3517  // If we've not yet parsed the initializer, assume it has side-effects.
3518  return true;
3519  }
3520 
3521  case CXXDynamicCastExprClass: {
3522  // A dynamic_cast expression has side-effects if it can throw.
3523  const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3524  if (DCE->getTypeAsWritten()->isReferenceType() &&
3525  DCE->getCastKind() == CK_Dynamic)
3526  return true;
3527  }
3528  LLVM_FALLTHROUGH;
3529  case ImplicitCastExprClass:
3530  case CStyleCastExprClass:
3531  case CXXStaticCastExprClass:
3532  case CXXReinterpretCastExprClass:
3533  case CXXConstCastExprClass:
3534  case CXXFunctionalCastExprClass:
3535  case BuiltinBitCastExprClass: {
3536  // While volatile reads are side-effecting in both C and C++, we treat them
3537  // as having possible (not definite) side-effects. This allows idiomatic
3538  // code to behave without warning, such as sizeof(*v) for a volatile-
3539  // qualified pointer.
3540  if (!IncludePossibleEffects)
3541  break;
3542 
3543  const CastExpr *CE = cast<CastExpr>(this);
3544  if (CE->getCastKind() == CK_LValueToRValue &&
3546  return true;
3547  break;
3548  }
3549 
3550  case CXXTypeidExprClass:
3551  // typeid might throw if its subexpression is potentially-evaluated, so has
3552  // side-effects in that case whether or not its subexpression does.
3553  return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3554 
3555  case CXXConstructExprClass:
3556  case CXXTemporaryObjectExprClass: {
3557  const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3558  if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3559  return true;
3560  // A trivial constructor does not add any side-effects of its own. Just look
3561  // at its arguments.
3562  break;
3563  }
3564 
3565  case CXXInheritedCtorInitExprClass: {
3566  const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3567  if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3568  return true;
3569  break;
3570  }
3571 
3572  case LambdaExprClass: {
3573  const LambdaExpr *LE = cast<LambdaExpr>(this);
3574  for (Expr *E : LE->capture_inits())
3575  if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3576  return true;
3577  return false;
3578  }
3579 
3580  case PseudoObjectExprClass: {
3581  // Only look for side-effects in the semantic form, and look past
3582  // OpaqueValueExpr bindings in that form.
3583  const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3585  E = PO->semantics_end();
3586  I != E; ++I) {
3587  const Expr *Subexpr = *I;
3588  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3589  Subexpr = OVE->getSourceExpr();
3590  if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3591  return true;
3592  }
3593  return false;
3594  }
3595 
3596  case ObjCBoxedExprClass:
3597  case ObjCArrayLiteralClass:
3598  case ObjCDictionaryLiteralClass:
3599  case ObjCSelectorExprClass:
3600  case ObjCProtocolExprClass:
3601  case ObjCIsaExprClass:
3602  case ObjCIndirectCopyRestoreExprClass:
3603  case ObjCSubscriptRefExprClass:
3604  case ObjCBridgedCastExprClass:
3605  case ObjCMessageExprClass:
3606  case ObjCPropertyRefExprClass:
3607  // FIXME: Classify these cases better.
3608  if (IncludePossibleEffects)
3609  return true;
3610  break;
3611  }
3612 
3613  // Recurse to children.
3614  for (const Stmt *SubStmt : children())
3615  if (SubStmt &&
3616  cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3617  return true;
3618 
3619  return false;
3620 }
3621 
3622 namespace {
3623  /// Look for a call to a non-trivial function within an expression.
3624  class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3625  {
3627 
3628  bool NonTrivial;
3629 
3630  public:
3631  explicit NonTrivialCallFinder(const ASTContext &Context)
3632  : Inherited(Context), NonTrivial(false) { }
3633 
3634  bool hasNonTrivialCall() const { return NonTrivial; }
3635 
3636  void VisitCallExpr(const CallExpr *E) {
3637  if (const CXXMethodDecl *Method
3638  = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3639  if (Method->isTrivial()) {
3640  // Recurse to children of the call.
3641  Inherited::VisitStmt(E);
3642  return;
3643  }
3644  }
3645 
3646  NonTrivial = true;
3647  }
3648 
3649  void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3650  if (E->getConstructor()->isTrivial()) {
3651  // Recurse to children of the call.
3652  Inherited::VisitStmt(E);
3653  return;
3654  }
3655 
3656  NonTrivial = true;
3657  }
3658 
3659  void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3660  if (E->getTemporary()->getDestructor()->isTrivial()) {
3661  Inherited::VisitStmt(E);
3662  return;
3663  }
3664 
3665  NonTrivial = true;
3666  }
3667  };
3668 }
3669 
3670 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3671  NonTrivialCallFinder Finder(Ctx);
3672  Finder.Visit(this);
3673  return Finder.hasNonTrivialCall();
3674 }
3675 
3676 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3677 /// pointer constant or not, as well as the specific kind of constant detected.
3678 /// Null pointer constants can be integer constant expressions with the
3679 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3680 /// (a GNU extension).
3684  if (isValueDependent() &&
3685  (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3686  switch (NPC) {
3688  llvm_unreachable("Unexpected value dependent expression!");
3690  if (isTypeDependent() || getType()->isIntegralType(Ctx))
3691  return NPCK_ZeroExpression;
3692  else
3693  return NPCK_NotNull;
3694 
3696  return NPCK_NotNull;
3697  }
3698  }
3699 
3700  // Strip off a cast to void*, if it exists. Except in C++.
3701  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3702  if (!Ctx.getLangOpts().CPlusPlus) {
3703  // Check that it is a cast to void*.
3704  if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3705  QualType Pointee = PT->getPointeeType();
3706  Qualifiers Qs = Pointee.getQualifiers();
3707  // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3708  // has non-default address space it is not treated as nullptr.
3709  // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3710  // since it cannot be assigned to a pointer to constant address space.
3711  if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
3712  Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3713  (Ctx.getLangOpts().OpenCL &&
3714  Ctx.getLangOpts().OpenCLVersion < 200 &&
3716  Qs.removeAddressSpace();
3717 
3718  if (Pointee->isVoidType() && Qs.empty() && // to void*
3719  CE->getSubExpr()->getType()->isIntegerType()) // from int
3720  return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3721  }
3722  }
3723  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3724  // Ignore the ImplicitCastExpr type entirely.
3725  return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3726  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3727  // Accept ((void*)0) as a null pointer constant, as many other
3728  // implementations do.
3729  return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3730  } else if (const GenericSelectionExpr *GE =
3731  dyn_cast<GenericSelectionExpr>(this)) {
3732  if (GE->isResultDependent())
3733  return NPCK_NotNull;
3734  return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3735  } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3736  if (CE->isConditionDependent())
3737  return NPCK_NotNull;
3738  return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3739  } else if (const CXXDefaultArgExpr *DefaultArg
3740  = dyn_cast<CXXDefaultArgExpr>(this)) {
3741  // See through default argument expressions.
3742  return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3743  } else if (const CXXDefaultInitExpr *DefaultInit
3744  = dyn_cast<CXXDefaultInitExpr>(this)) {
3745  // See through default initializer expressions.
3746  return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3747  } else if (isa<GNUNullExpr>(this)) {
3748  // The GNU __null extension is always a null pointer constant.
3749  return NPCK_GNUNull;
3750  } else if (const MaterializeTemporaryExpr *M
3751  = dyn_cast<MaterializeTemporaryExpr>(this)) {
3752  return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
3753  } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3754  if (const Expr *Source = OVE->getSourceExpr())
3755  return Source->isNullPointerConstant(Ctx, NPC);
3756  }
3757 
3758  // C++11 nullptr_t is always a null pointer constant.
3759  if (getType()->isNullPtrType())
3760  return NPCK_CXX11_nullptr;
3761 
3762  if (const RecordType *UT = getType()->getAsUnionType())
3763  if (!Ctx.getLangOpts().CPlusPlus11 &&
3764  UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3765  if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3766  const Expr *InitExpr = CLE->getInitializer();
3767  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3768  return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3769  }
3770  // This expression must be an integer type.
3771  if (!getType()->isIntegerType() ||
3772  (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3773  return NPCK_NotNull;
3774 
3775  if (Ctx.getLangOpts().CPlusPlus11) {
3776  // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3777  // value zero or a prvalue of type std::nullptr_t.
3778  // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3779  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3780  if (Lit && !Lit->getValue())
3781  return NPCK_ZeroLiteral;
3782  else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3783  return NPCK_NotNull;
3784  } else {
3785  // If we have an integer constant expression, we need to *evaluate* it and
3786  // test for the value 0.
3787  if (!isIntegerConstantExpr(Ctx))
3788  return NPCK_NotNull;
3789  }
3790 
3791  if (EvaluateKnownConstInt(Ctx) != 0)
3792  return NPCK_NotNull;
3793 
3794  if (isa<IntegerLiteral>(this))
3795  return NPCK_ZeroLiteral;
3796  return NPCK_ZeroExpression;
3797 }
3798 
3799 /// If this expression is an l-value for an Objective C
3800 /// property, find the underlying property reference expression.
3802  const Expr *E = this;
3803  while (true) {
3804  assert((E->getValueKind() == VK_LValue &&
3805  E->getObjectKind() == OK_ObjCProperty) &&
3806  "expression is not a property reference");
3807  E = E->IgnoreParenCasts();
3808  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3809  if (BO->getOpcode() == BO_Comma) {
3810  E = BO->getRHS();
3811  continue;
3812  }
3813  }
3814 
3815  break;
3816  }
3817 
3818  return cast<ObjCPropertyRefExpr>(E);
3819 }
3820 
3821 bool Expr::isObjCSelfExpr() const {
3822  const Expr *E = IgnoreParenImpCasts();
3823 
3824  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3825  if (!DRE)
3826  return false;
3827 
3828  const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3829  if (!Param)
3830  return false;
3831 
3832  const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3833  if (!M)
3834  return false;
3835 
3836  return M->getSelfDecl() == Param;
3837 }
3838 
3840  Expr *E = this->IgnoreParens();
3841 
3842  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3843  if (ICE->getCastKind() == CK_LValueToRValue ||
3844  (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
3845  E = ICE->getSubExpr()->IgnoreParens();
3846  else
3847  break;
3848  }
3849 
3850  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3851  if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3852  if (Field->isBitField())
3853  return Field;
3854 
3855  if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3856  FieldDecl *Ivar = IvarRef->getDecl();
3857  if (Ivar->isBitField())
3858  return Ivar;
3859  }
3860 
3861  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3862  if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3863  if (Field->isBitField())
3864  return Field;
3865 
3866  if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3867  if (Expr *E = BD->getBinding())
3868  return E->getSourceBitField();
3869  }
3870 
3871  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3872  if (BinOp->isAssignmentOp() && BinOp->getLHS())
3873  return BinOp->getLHS()->getSourceBitField();
3874 
3875  if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3876  return BinOp->getRHS()->getSourceBitField();
3877  }
3878 
3879  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3880  if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3881  return UnOp->getSubExpr()->getSourceBitField();
3882 
3883  return nullptr;
3884 }
3885 
3887  // FIXME: Why do we not just look at the ObjectKind here?
3888  const Expr *E = this->IgnoreParens();
3889 
3890  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3891  if (ICE->getValueKind() != VK_RValue &&
3892  ICE->getCastKind() == CK_NoOp)
3893  E = ICE->getSubExpr()->IgnoreParens();
3894  else
3895  break;
3896  }
3897 
3898  if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3899  return ASE->getBase()->getType()->isVectorType();
3900 
3901  if (isa<ExtVectorElementExpr>(E))
3902  return true;
3903 
3904  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3905  if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3906  if (auto *E = BD->getBinding())
3907  return E->refersToVectorElement();
3908 
3909  return false;
3910 }
3911 
3913  const Expr *E = this->IgnoreParenImpCasts();
3914 
3915  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3916  if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3917  if (VD->getStorageClass() == SC_Register &&
3918  VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3919  return true;
3920 
3921  return false;
3922 }
3923 
3924 bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
3925  E1 = E1->IgnoreParens();
3926  E2 = E2->IgnoreParens();
3927 
3928  if (E1->getStmtClass() != E2->getStmtClass())
3929  return false;
3930 
3931  switch (E1->getStmtClass()) {
3932  default:
3933  return false;
3934  case CXXThisExprClass:
3935  return true;
3936  case DeclRefExprClass: {
3937  // DeclRefExpr without an ImplicitCastExpr can happen for integral
3938  // template parameters.
3939  const auto *DRE1 = cast<DeclRefExpr>(E1);
3940  const auto *DRE2 = cast<DeclRefExpr>(E2);
3941  return DRE1->isRValue() && DRE2->isRValue() &&
3942  DRE1->getDecl() == DRE2->getDecl();
3943  }
3944  case ImplicitCastExprClass: {
3945  // Peel off implicit casts.
3946  while (true) {
3947  const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
3948  const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
3949  if (!ICE1 || !ICE2)
3950  return false;
3951  if (ICE1->getCastKind() != ICE2->getCastKind())
3952  return false;
3953  E1 = ICE1->getSubExpr()->IgnoreParens();
3954  E2 = ICE2->getSubExpr()->IgnoreParens();
3955  // The final cast must be one of these types.
3956  if (ICE1->getCastKind() == CK_LValueToRValue ||
3957  ICE1->getCastKind() == CK_ArrayToPointerDecay ||
3958  ICE1->getCastKind() == CK_FunctionToPointerDecay) {
3959  break;
3960  }
3961  }
3962 
3963  const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
3964  const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
3965  if (DRE1 && DRE2)
3966  return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
3967 
3968  const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
3969  const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
3970  if (Ivar1 && Ivar2) {
3971  return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
3972  declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
3973  }
3974 
3975  const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
3976  const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
3977  if (Array1 && Array2) {
3978  if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
3979  return false;
3980 
3981  auto Idx1 = Array1->getIdx();
3982  auto Idx2 = Array2->getIdx();
3983  const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
3984  const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
3985  if (Integer1 && Integer2) {
3986  if (!llvm::APInt::isSameValue(Integer1->getValue(),
3987  Integer2->getValue()))
3988  return false;
3989  } else {
3990  if (!isSameComparisonOperand(Idx1, Idx2))
3991  return false;
3992  }
3993 
3994  return true;
3995  }
3996 
3997  // Walk the MemberExpr chain.
3998  while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
3999  const auto *ME1 = cast<MemberExpr>(E1);
4000  const auto *ME2 = cast<MemberExpr>(E2);
4001  if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4002  return false;
4003  if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4004  if (D->isStaticDataMember())
4005  return true;
4006  E1 = ME1->getBase()->IgnoreParenImpCasts();
4007  E2 = ME2->getBase()->IgnoreParenImpCasts();
4008  }
4009 
4010  if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4011  return true;
4012 
4013  // A static member variable can end the MemberExpr chain with either
4014  // a MemberExpr or a DeclRefExpr.
4015  auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4016  if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4017  return DRE->getDecl();
4018  if (const auto *ME = dyn_cast<MemberExpr>(E))
4019  return ME->getMemberDecl();
4020  return nullptr;
4021  };
4022 
4023  const ValueDecl *VD1 = getAnyDecl(E1);
4024  const ValueDecl *VD2 = getAnyDecl(E2);
4025  return declaresSameEntity(VD1, VD2);
4026  }
4027  }
4028 }
4029 
4030 /// isArrow - Return true if the base expression is a pointer to vector,
4031 /// return false if the base expression is a vector.
4033  return getBase()->getType()->isPointerType();
4034 }
4035 
4037  if (const VectorType *VT = getType()->getAs<VectorType>())
4038  return VT->getNumElements();
4039  return 1;
4040 }
4041 
4042 /// containsDuplicateElements - Return true if any element access is repeated.
4044  // FIXME: Refactor this code to an accessor on the AST node which returns the
4045  // "type" of component access, and share with code below and in Sema.
4046  StringRef Comp = Accessor->getName();
4047 
4048  // Halving swizzles do not contain duplicate elements.
4049  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4050  return false;
4051 
4052  // Advance past s-char prefix on hex swizzles.
4053  if (Comp[0] == 's' || Comp[0] == 'S')
4054  Comp = Comp.substr(1);
4055 
4056  for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4057  if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
4058  return true;
4059 
4060  return false;
4061 }
4062 
4063 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4065  SmallVectorImpl<uint32_t> &Elts) const {
4066  StringRef Comp = Accessor->getName();
4067  bool isNumericAccessor = false;
4068  if (Comp[0] == 's' || Comp[0] == 'S') {
4069  Comp = Comp.substr(1);
4070  isNumericAccessor = true;
4071  }
4072 
4073  bool isHi = Comp == "hi";
4074  bool isLo = Comp == "lo";
4075  bool isEven = Comp == "even";
4076  bool isOdd = Comp == "odd";
4077 
4078  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4079  uint64_t Index;
4080 
4081  if (isHi)
4082  Index = e + i;
4083  else if (isLo)
4084  Index = i;
4085  else if (isEven)
4086  Index = 2 * i;
4087  else if (isOdd)
4088  Index = 2 * i + 1;
4089  else
4090  Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4091 
4092  Elts.push_back(Index);
4093  }
4094 }
4095 
4097  QualType Type, SourceLocation BLoc,
4098  SourceLocation RP)
4099  : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
4100  Type->isDependentType(), Type->isDependentType(),
4101  Type->isInstantiationDependentType(),
4103  BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
4104 {
4105  SubExprs = new (C) Stmt*[args.size()];
4106  for (unsigned i = 0; i != args.size(); i++) {
4107  if (args[i]->isTypeDependent())
4108  ExprBits.TypeDependent = true;
4109  if (args[i]->isValueDependent())
4110  ExprBits.ValueDependent = true;
4111  if (args[i]->isInstantiationDependent())
4112  ExprBits.InstantiationDependent = true;
4113  if (args[i]->containsUnexpandedParameterPack())
4114  ExprBits.ContainsUnexpandedParameterPack = true;
4115 
4116  SubExprs[i] = args[i];
4117  }
4118 }
4119 
4121  if (SubExprs) C.Deallocate(SubExprs);
4122 
4123  this->NumExprs = Exprs.size();
4124  SubExprs = new (C) Stmt*[NumExprs];
4125  memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4126 }
4127 
4128 GenericSelectionExpr::GenericSelectionExpr(
4129  const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4130  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4131  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4132  bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4133  : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4134  AssocExprs[ResultIndex]->getValueKind(),
4135  AssocExprs[ResultIndex]->getObjectKind(),
4136  AssocExprs[ResultIndex]->isTypeDependent(),
4137  AssocExprs[ResultIndex]->isValueDependent(),
4138  AssocExprs[ResultIndex]->isInstantiationDependent(),
4139  ContainsUnexpandedParameterPack),
4140  NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4141  DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4142  assert(AssocTypes.size() == AssocExprs.size() &&
4143  "Must have the same number of association expressions"
4144  " and TypeSourceInfo!");
4145  assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4146 
4147  GenericSelectionExprBits.GenericLoc = GenericLoc;
4148  getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4149  std::copy(AssocExprs.begin(), AssocExprs.end(),
4150  getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4151  std::copy(AssocTypes.begin(), AssocTypes.end(),
4152  getTrailingObjects<TypeSourceInfo *>());
4153 }
4154 
4155 GenericSelectionExpr::GenericSelectionExpr(
4156  const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4157  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4158  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4159  bool ContainsUnexpandedParameterPack)
4160  : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
4161  OK_Ordinary,
4162  /*isTypeDependent=*/true,
4163  /*isValueDependent=*/true,
4164  /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack),
4165  NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4166  DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4167  assert(AssocTypes.size() == AssocExprs.size() &&
4168  "Must have the same number of association expressions"
4169  " and TypeSourceInfo!");
4170 
4171  GenericSelectionExprBits.GenericLoc = GenericLoc;
4172  getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4173  std::copy(AssocExprs.begin(), AssocExprs.end(),
4174  getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4175  std::copy(AssocTypes.begin(), AssocTypes.end(),
4176  getTrailingObjects<TypeSourceInfo *>());
4177 }
4178 
4179 GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4180  : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4181 
4183  const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4184  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4185  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4186  bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4187  unsigned NumAssocs = AssocExprs.size();
4188  void *Mem = Context.Allocate(
4189  totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4190  alignof(GenericSelectionExpr));
4191  return new (Mem) GenericSelectionExpr(
4192  Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4193  RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4194 }
4195 
4197  const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4198  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4199  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4200  bool ContainsUnexpandedParameterPack) {
4201  unsigned NumAssocs = AssocExprs.size();
4202  void *Mem = Context.Allocate(
4203  totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4204  alignof(GenericSelectionExpr));
4205  return new (Mem) GenericSelectionExpr(
4206  Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4207  RParenLoc, ContainsUnexpandedParameterPack);
4208 }
4209 
4212  unsigned NumAssocs) {
4213  void *Mem = Context.Allocate(
4214  totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4215  alignof(GenericSelectionExpr));
4216  return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4217 }
4218 
4219 //===----------------------------------------------------------------------===//
4220 // DesignatedInitExpr
4221 //===----------------------------------------------------------------------===//
4222 
4224  assert(Kind == FieldDesignator && "Only valid on a field designator");
4225  if (Field.NameOrField & 0x01)
4226  return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
4227  else
4228  return getField()->getIdentifier();
4229 }
4230 
4231 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4232  llvm::ArrayRef<Designator> Designators,
4233  SourceLocation EqualOrColonLoc,
4234  bool GNUSyntax,
4235  ArrayRef<Expr*> IndexExprs,
4236  Expr *Init)
4237  : Expr(DesignatedInitExprClass, Ty,
4238  Init->getValueKind(), Init->getObjectKind(),
4239  Init->isTypeDependent(), Init->isValueDependent(),
4240  Init->isInstantiationDependent(),
4242  EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4243  NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4244  this->Designators = new (C) Designator[NumDesignators];
4245 
4246  // Record the initializer itself.
4247  child_iterator Child = child_begin();
4248  *Child++ = Init;
4249 
4250  // Copy the designators and their subexpressions, computing
4251  // value-dependence along the way.
4252  unsigned IndexIdx = 0;
4253  for (unsigned I = 0; I != NumDesignators; ++I) {
4254  this->Designators[I] = Designators[I];
4255 
4256  if (this->Designators[I].isArrayDesignator()) {
4257  // Compute type- and value-dependence.
4258  Expr *Index = IndexExprs[IndexIdx];
4259  if (Index->isTypeDependent() || Index->isValueDependent())
4260  ExprBits.TypeDependent = ExprBits.ValueDependent = true;
4261  if (Index->isInstantiationDependent())
4262  ExprBits.InstantiationDependent = true;
4263  // Propagate unexpanded parameter packs.
4265  ExprBits.ContainsUnexpandedParameterPack = true;
4266 
4267  // Copy the index expressions into permanent storage.
4268  *Child++ = IndexExprs[IndexIdx++];
4269  } else if (this->Designators[I].isArrayRangeDesignator()) {
4270  // Compute type- and value-dependence.
4271  Expr *Start = IndexExprs[IndexIdx];
4272  Expr *End = IndexExprs[IndexIdx + 1];
4273  if (Start->isTypeDependent() || Start->isValueDependent() ||
4274  End->isTypeDependent() || End->isValueDependent()) {
4275  ExprBits.TypeDependent = ExprBits.ValueDependent = true;
4276  ExprBits.InstantiationDependent = true;
4277  } else if (Start->isInstantiationDependent() ||
4278  End->isInstantiationDependent()) {
4279  ExprBits.InstantiationDependent = true;
4280  }
4281 
4282  // Propagate unexpanded parameter packs.
4283  if (Start->containsUnexpandedParameterPack() ||
4285  ExprBits.ContainsUnexpandedParameterPack = true;
4286 
4287  // Copy the start/end expressions into permanent storage.
4288  *Child++ = IndexExprs[IndexIdx++];
4289  *Child++ = IndexExprs[IndexIdx++];
4290  }
4291  }
4292 
4293  assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4294 }
4295 
4298  llvm::ArrayRef<Designator> Designators,
4299  ArrayRef<Expr*> IndexExprs,
4300  SourceLocation ColonOrEqualLoc,
4301  bool UsesColonSyntax, Expr *Init) {
4302  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4303  alignof(DesignatedInitExpr));
4304  return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4305  ColonOrEqualLoc, UsesColonSyntax,
4306  IndexExprs, Init);
4307 }
4308 
4310  unsigned NumIndexExprs) {
4311  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4312  alignof(DesignatedInitExpr));
4313  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4314 }
4315 
4317  const Designator *Desigs,
4318  unsigned NumDesigs) {
4319  Designators = new (C) Designator[NumDesigs];
4320  NumDesignators = NumDesigs;
4321  for (unsigned I = 0; I != NumDesigs; ++I)
4322  Designators[I] = Desigs[I];
4323 }
4324 
4326  DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4327  if (size() == 1)
4328  return DIE->getDesignator(0)->getSourceRange();
4329  return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4330  DIE->getDesignator(size() - 1)->getEndLoc());
4331 }
4332 
4334  SourceLocation StartLoc;
4335  auto *DIE = const_cast<DesignatedInitExpr *>(this);
4336  Designator &First = *DIE->getDesignator(0);
4337  if (First.isFieldDesignator()) {
4338  if (GNUSyntax)
4340  else
4342  } else
4343  StartLoc =
4345  return StartLoc;
4346 }
4347 
4349  return getInit()->getEndLoc();
4350 }
4351 
4353  assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
4354  return getSubExpr(D.ArrayOrRange.Index + 1);
4355 }
4356 
4358  assert(D.Kind == Designator::ArrayRangeDesignator &&
4359  "Requires array range designator");
4360  return getSubExpr(D.ArrayOrRange.Index + 1);
4361 }
4362 
4364  assert(D.Kind == Designator::ArrayRangeDesignator &&
4365  "Requires array range designator");
4366  return getSubExpr(D.ArrayOrRange.Index + 2);
4367 }
4368 
4369 /// Replaces the designator at index @p Idx with the series
4370 /// of designators in [First, Last).
4372  const Designator *First,
4373  const Designator *Last) {
4374  unsigned NumNewDesignators = Last - First;
4375  if (NumNewDesignators == 0) {
4376  std::copy_backward(Designators + Idx + 1,
4377  Designators + NumDesignators,
4378  Designators + Idx);
4379  --NumNewDesignators;
4380  return;
4381  } else if (NumNewDesignators == 1) {
4382  Designators[Idx] = *First;
4383  return;
4384  }
4385 
4386  Designator *NewDesignators
4387  = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4388  std::copy(Designators, Designators + Idx, NewDesignators);
4389  std::copy(First, Last, NewDesignators + Idx);
4390  std::copy(Designators + Idx + 1, Designators + NumDesignators,
4391  NewDesignators + Idx + NumNewDesignators);
4392  Designators = NewDesignators;
4393  NumDesignators = NumDesignators - 1 + NumNewDesignators;
4394 }
4395 
4397  SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
4398  : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4400  BaseAndUpdaterExprs[0] = baseExpr;
4401 
4402  InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4403  ILE->setType(baseExpr->getType());
4404  BaseAndUpdaterExprs[1] = ILE;
4405 }
4406 
4408  return getBase()->getBeginLoc();
4409 }
4410 
4412  return getBase()->getEndLoc();
4413 }
4414 
4415 ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4416  SourceLocation RParenLoc)
4417  : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4418  false, false),
4419  LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4420  ParenListExprBits.NumExprs = Exprs.size();
4421 
4422  for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4423  if (Exprs[I]->isTypeDependent())
4424  ExprBits.TypeDependent = true;
4425  if (Exprs[I]->isValueDependent())
4426  ExprBits.ValueDependent = true;
4427  if (Exprs[I]->isInstantiationDependent())
4428  ExprBits.InstantiationDependent = true;
4429  if (Exprs[I]->containsUnexpandedParameterPack())
4430  ExprBits.ContainsUnexpandedParameterPack = true;
4431 
4432  getTrailingObjects<Stmt *>()[I] = Exprs[I];
4433  }
4434 }
4435 
4436 ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4437  : Expr(ParenListExprClass, Empty) {
4438  ParenListExprBits.NumExprs = NumExprs;
4439 }
4440 
4442  SourceLocation LParenLoc,
4443  ArrayRef<Expr *> Exprs,
4444  SourceLocation RParenLoc) {
4445  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4446  alignof(ParenListExpr));
4447  return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4448 }
4449 
4451  unsigned NumExprs) {
4452  void *Mem =
4453  Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4454  return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4455 }
4456 
4458  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4459  e = ewc->getSubExpr();
4460  if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4461  e = m->GetTemporaryExpr();
4462  e = cast<CXXConstructExpr>(e)->getArg(0);
4463  while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4464  e = ice->getSubExpr();
4465  return cast<OpaqueValueExpr>(e);
4466 }
4467 
4469  EmptyShell sh,
4470  unsigned numSemanticExprs) {
4471  void *buffer =
4472  Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4473  alignof(PseudoObjectExpr));
4474  return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4475 }
4476 
4477 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4478  : Expr(PseudoObjectExprClass, shell) {
4479  PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4480 }
4481 
4483  ArrayRef<Expr*> semantics,
4484  unsigned resultIndex) {
4485  assert(syntax && "no syntactic expression!");
4486  assert(semantics.size() && "no semantic expressions!");
4487 
4488  QualType type;
4489  ExprValueKind VK;
4490  if (resultIndex == NoResult) {
4491  type = C.VoidTy;
4492  VK = VK_RValue;
4493  } else {
4494  assert(resultIndex < semantics.size());
4495  type = semantics[resultIndex]->getType();
4496  VK = semantics[resultIndex]->getValueKind();
4497  assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4498  }
4499 
4500  void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4501  alignof(PseudoObjectExpr));
4502  return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4503  resultIndex);
4504 }
4505 
4506 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4507  Expr *syntax, ArrayRef<Expr*> semantics,
4508  unsigned resultIndex)
4509  : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4510  /*filled in at end of ctor*/ false, false, false, false) {
4511  PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4512  PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4513 
4514  for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4515  Expr *E = (i == 0 ? syntax : semantics[i-1]);
4516  getSubExprsBuffer()[i] = E;
4517 
4518  if (E->isTypeDependent())
4519  ExprBits.TypeDependent = true;
4520  if (E->isValueDependent())
4521  ExprBits.ValueDependent = true;
4523  ExprBits.InstantiationDependent = true;
4525  ExprBits.ContainsUnexpandedParameterPack = true;
4526 
4527  if (isa<OpaqueValueExpr>(E))
4528  assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
4529  "opaque-value semantic expressions for pseudo-object "
4530  "operations must have sources");
4531  }
4532 }
4533 
4534 //===----------------------------------------------------------------------===//
4535 // Child Iterators for iterating over subexpressions/substatements
4536 //===----------------------------------------------------------------------===//
4537 
4538 // UnaryExprOrTypeTraitExpr
4540  const_child_range CCR =
4541  const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4542  return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4543 }
4544 
4546  // If this is of a type and the type is a VLA type (and not a typedef), the
4547  // size expression of the VLA needs to be treated as an executable expression.
4548  // Why isn't this weirdness documented better in StmtIterator?
4549  if (isArgumentType()) {
4550  if (const VariableArrayType *T =
4551  dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4554  }
4555  return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4556 }
4557 
4559  QualType t, AtomicOp op, SourceLocation RP)
4560  : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4561  false, false, false, false),
4562  NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4563 {
4564  assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4565  for (unsigned i = 0; i != args.size(); i++) {
4566  if (args[i]->isTypeDependent())
4567  ExprBits.TypeDependent = true;
4568  if (args[i]->isValueDependent())
4569  ExprBits.ValueDependent = true;
4570  if (args[i]->isInstantiationDependent())
4571  ExprBits.InstantiationDependent = true;
4572  if (args[i]->containsUnexpandedParameterPack())
4573  ExprBits.ContainsUnexpandedParameterPack = true;
4574 
4575  SubExprs[i] = args[i];
4576  }
4577 }
4578 
4580  switch (Op) {
4581  case AO__c11_atomic_init:
4582  case AO__opencl_atomic_init:
4583  case AO__c11_atomic_load:
4584  case AO__atomic_load_n:
4585  return 2;
4586 
4587  case AO__opencl_atomic_load:
4588  case AO__c11_atomic_store:
4589  case AO__c11_atomic_exchange:
4590  case AO__atomic_load:
4591  case AO__atomic_store:
4592  case AO__atomic_store_n:
4593  case AO__atomic_exchange_n:
4594  case AO__c11_atomic_fetch_add:
4595  case AO__c11_atomic_fetch_sub:
4596  case AO__c11_atomic_fetch_and:
4597  case AO__c11_atomic_fetch_or:
4598  case AO__c11_atomic_fetch_xor:
4599  case AO__atomic_fetch_add:
4600  case AO__atomic_fetch_sub:
4601  case AO__atomic_fetch_and:
4602  case AO__atomic_fetch_or:
4603  case AO__atomic_fetch_xor:
4604  case AO__atomic_fetch_nand:
4605  case AO__atomic_add_fetch:
4606  case AO__atomic_sub_fetch:
4607  case AO__atomic_and_fetch:
4608  case AO__atomic_or_fetch:
4609  case AO__atomic_xor_fetch:
4610  case AO__atomic_nand_fetch:
4611  case AO__atomic_fetch_min:
4612  case AO__atomic_fetch_max:
4613  return 3;
4614 
4615  case AO__opencl_atomic_store:
4616  case AO__opencl_atomic_exchange:
4617  case AO__opencl_atomic_fetch_add:
4618  case AO__opencl_atomic_fetch_sub:
4619  case AO__opencl_atomic_fetch_and:
4620  case AO__opencl_atomic_fetch_or:
4621  case AO__opencl_atomic_fetch_xor:
4622  case AO__opencl_atomic_fetch_min:
4623  case AO__opencl_atomic_fetch_max:
4624  case AO__atomic_exchange:
4625  return 4;
4626 
4627  case AO__c11_atomic_compare_exchange_strong:
4628  case AO__c11_atomic_compare_exchange_weak:
4629  return 5;
4630 
4631  case AO__opencl_atomic_compare_exchange_strong:
4632  case AO__opencl_atomic_compare_exchange_weak:
4633  case AO__atomic_compare_exchange:
4634  case AO__atomic_compare_exchange_n:
4635  return 6;
4636  }
4637  llvm_unreachable("unknown atomic op");
4638 }
4639 
4641  auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4642  if (auto AT = T->getAs<AtomicType>())
4643  return AT->getValueType();
4644  return T;
4645 }
4646 
4648  unsigned ArraySectionCount = 0;
4649  while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4650  Base = OASE->getBase();
4651  ++ArraySectionCount;
4652  }
4653  while (auto *ASE =
4654  dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4655  Base = ASE->getBase();
4656  ++ArraySectionCount;
4657  }
4658  Base = Base->IgnoreParenImpCasts();
4659  auto OriginalTy = Base->getType();
4660  if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4661  if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4662  OriginalTy = PVD->getOriginalType().getNonReferenceType();
4663 
4664  for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4665  if (OriginalTy->isAnyPointerType())
4666  OriginalTy = OriginalTy->getPointeeType();
4667  else {
4668  assert (OriginalTy->isArrayType());
4669  OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4670  }
4671  }
4672  return OriginalTy;
4673 }
child_iterator child_begin()
Definition: Stmt.h:1168
CallExpr(StmtClass SC, Expr *Fn, ArrayRef< Expr *> PreArgs, ArrayRef< Expr *> Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, unsigned MinNumArgs, ADLCallKind UsesADL)
Build a call expression, assuming that appropriate storage has been allocated for the trailing object...
Definition: Expr.cpp:1335
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:614
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:77
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:4479
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
Represents a single C99 designator.
Definition: Expr.h:4686
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setValueDependent(bool VD)
Set whether this expression is value-dependent or not.
Definition: Expr.h:161
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Defines the clang::ASTContext interface.
ConstantExprBitfields ConstantExprBits
Definition: Stmt.h:960
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:598
static Expr * IgnoreImpCastsExtraSingleStep(Expr *E)
Definition: Expr.cpp:2816
static Expr * IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E)
Definition: Expr.cpp:2908
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1261
Represents a function declaration or definition.
Definition: Decl.h:1756
Expr * getArrayIndex(const Designator &D) const
Definition: Expr.cpp:4352
Stmt * body_back()
Definition: Stmt.h:1348
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:571
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition: Type.cpp:1666
static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, QualType T, bool &TypeDependent, bool &ValueDependent, bool &InstantiationDependent)
Compute the type-, value-, and instantiation-dependence of a declaration reference based on the decla...
Definition: Expr.cpp:368
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:6696
StringRef Identifier
Definition: Format.cpp:1763
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
Definition: Expr.h:5717
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:76
SourceLocation getRParenLoc() const
Definition: Expr.h:2764
void setArrayFiller(Expr *filler)
Definition: Expr.cpp:2262
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition: Expr.cpp:2358
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2575
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:4333
QualType getPointeeType() const
Definition: Type.h:2588
A (possibly-)qualified type.
Definition: Type.h:643
unsigned getOffsetOfStringByte(const Token &TheTok, unsigned ByteNo) const
getOffsetOfStringByte - This function returns the offset of the specified byte of the string data rep...
ResultStorageKind
Describes the kind of result that can be trail-allocated.
Definition: Expr.h:962
bool isArrayType() const
Definition: Type.h:6446
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2677
const DeclarationNameLoc & getInfo() const
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:858
unsigned FieldLoc
The location of the field name in the designated initializer.
Definition: Expr.h:4663
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4423
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value...
Definition: Expr.h:4307
static ResultStorageKind getStorageKind(const APValue &Value)
Definition: Expr.cpp:245
Stmt - This represents one statement.
Definition: Stmt.h:66
DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, Expr *baseExprs, SourceLocation rBraceLoc)
Definition: Expr.cpp:4396
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2664
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3393
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition: Expr.cpp:1216
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:518
static CallExpr * CreateTemporary(void *Mem, Expr *Fn, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, ADLCallKind UsesADL=NotADL)
Create a temporary call expression with no arguments in the memory pointed to by Mem.
Definition: Expr.cpp:1394
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:481
Defines the SourceManager interface.
bool hasNonTrivialCall(const ASTContext &Ctx) const
Determine whether this expression involves a call to any function that is not trivial.
Definition: Expr.cpp:3670
bool isRecordType() const
Definition: Type.h:6470
reverse_iterator rbegin()
Definition: ASTVector.h:103
Expr * getBase() const
Definition: Expr.h:2888
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:274
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:6636
static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs)
Return the size in bytes needed for the trailing objects.
Definition: Expr.h:2585
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
FloatingLiteralBitfields FloatingLiteralBits
Definition: Stmt.h:963
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition: Expr.cpp:4064
void setType(QualType t)
Definition: Expr.h:138
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic, and whose semantics are that of the sole contained initializer)?
Definition: Expr.cpp:2286
Defines the C++ template declaration subclasses.
Opcode getOpcode() const
Definition: Expr.h:3444
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:386
iterator insert(const ASTContext &C, iterator I, const T &Elt)
Definition: ASTVector.h:219
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1969
NamedDecl * getDecl() const
The base class of the type hierarchy.
Definition: Type.h:1436
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
bool isSemanticForm() const
Definition: Expr.h:4527
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list...
Definition: Expr.h:1303
llvm::iterator_range< child_iterator > child_range
Definition: Stmt.h:1158
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2850
DeclRefExprBitfields DeclRefExprBits
Definition: Stmt.h:962
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1331
SourceLocation getEndLoc() const LLVM_READONLY
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:404
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:132
SourceLocation getLParenLoc() const
Definition: Expr.h:3372
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:703
A container of type source information.
Definition: Decl.h:86
SourceLocation getLocation() const
Definition: Expr.h:4310
bool containsDuplicateElements() const
containsDuplicateElements - Return true if any element access is repeated.
Definition: Expr.cpp:4043
unsigned getCharWidth() const
Definition: TargetInfo.h:382
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2529
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4325
const Attr * getUnusedResultAttr(const ASTContext &Ctx) const
Returns the WarnUnusedResultAttr that is either declared on the called function, or its return type d...
Definition: Expr.cpp:1515
Expr * ignoreParenBaseCasts() LLVM_READONLY
Skip past any parentheses and derived-to-base casts until reaching a fixed point. ...
Definition: Expr.cpp:2988
QualType getElementType() const
Definition: Type.h:2885
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:603
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
static OffsetOfExpr * CreateEmpty(const ASTContext &C, unsigned NumComps, unsigned NumExprs)
Definition: Expr.cpp:1560
static const OpaqueValueExpr * findInCopyConstruct(const Expr *expr)
Given an expression which invokes a copy constructor — i.e.
Definition: Expr.cpp:4457
Represents a variable declaration or definition.
Definition: Decl.h:812
const ObjCPropertyRefExpr * getObjCProperty() const
If this expression is an l-value for an Objective C property, find the underlying property reference ...
Definition: Expr.cpp:3801
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3052
bool isEnumeralType() const
Definition: Type.h:6474
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6857
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:830
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type...
Definition: Type.h:6931
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition: Expr.cpp:2246
void setInit(unsigned Init, Expr *expr)
Definition: Expr.h:4433
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
static PredefinedExpr * CreateEmpty(const ASTContext &Ctx, bool HasFunctionName)
Create an empty PredefinedExpr.
Definition: Expr.cpp:639
size_type size() const
Definition: ASTVector.h:109
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition: Expr.cpp:2309
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:67
static DeclRefExpr * CreateEmpty(const ASTContext &Context, bool HasQualifier, bool HasFoundDecl, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs)
Construct an empty declaration reference expression.
Definition: Expr.cpp:583
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:37
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Definition: ExprCXX.h:3212
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3535
static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind)
Definition: Expr.cpp:238
Defines the clang::Expr interface and subclasses for C++ expressions.
The collection of all-type qualifiers we support.
Definition: Type.h:137
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:3839
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
LabelStmt - Represents a label, which has a substatement.
Definition: Stmt.h:1710
Represents a struct/union/class.
Definition: Decl.h:3634
Represents a C99 designated initializer expression.
Definition: Expr.h:4611
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:297
One of these records is kept for each identifier that is lexed.
Represents a class template specialization, which refers to a class template with a given set of temp...
unsigned GetStringLength() const
const Expr * getBestDynamicClassTypeExpr() const
Get the inner expression that determines the best dynamic class.
Definition: Expr.cpp:37
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:259
StmtIterator cast_away_const(const ConstStmtIterator &RHS)
Definition: StmtIterator.h:151
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:160
A C++ nested-name-specifier augmented with source location information.
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
static constexpr ADLCallKind UsesADL
Definition: Expr.h:2570
Used for GCC&#39;s __alignof.
Definition: TypeTraits.h:106
unsigned getChar32Width() const
getChar32Width/Align - Return the size of &#39;char32_t&#39; for this target, in bits.
Definition: TargetInfo.h:570
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:925
bool isCharType() const
Definition: Type.cpp:1831
field_range fields() const
Definition: Decl.h:3849
static SourceLocation getFromRawEncoding(unsigned Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:274
NameKind getNameKind() const
Determine what kind of name this is.
Represents a member of a struct/union/class.
Definition: Decl.h:2615
static DesignatedInitExpr * Create(const ASTContext &C, llvm::ArrayRef< Designator > Designators, ArrayRef< Expr *> IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition: Expr.cpp:4297
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:96
static Expr * IgnoreLValueCastsSingleStep(Expr *E)
Definition: Expr.cpp:2849
bool isReferenceType() const
Definition: Type.h:6402
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2687
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
Definition: opencl-c-base.h:40
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:52
Expr * getSubExpr()
Definition: Expr.h:3177
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition: Expr.cpp:4032
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:49
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6753
NestedNameSpecifierLoc QualifierLoc
The nested-name-specifier that qualifies the name, including source-location information.
Definition: Expr.h:2802
bool GE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:255
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:125
struct FieldDesignator Field
A field designator, e.g., ".x".
Definition: Expr.h:4696
const Expr *const * const_semantics_iterator
Definition: Expr.h:5740
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
ShuffleVectorExpr(const ASTContext &C, ArrayRef< Expr *> args, QualType Type, SourceLocation BLoc, SourceLocation RP)
Definition: Expr.cpp:4096
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:512
StringRef getOpcodeStr() const
Definition: Expr.h:3465
bool isGLValue() const
Definition: Expr.h:261
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr *> Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4441
Describes an C or C++ initializer list.
Definition: Expr.h:4375
const TemplateArgumentList * TemplateArguments
The template arguments used to produce the function template specialization from the function templat...
Definition: DeclTemplate.h:529
void setValue(const ASTContext &C, const llvm::APInt &Val)
Definition: Expr.h:1406
BinaryOperatorKind
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:947
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2693
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:4348
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1392
Base object ctor.
Definition: ABI.h:26
A convenient class for passing around template argument information.
Definition: TemplateBase.h:554
static Expr * IgnoreCastsSingleStep(Expr *E)
Definition: Expr.cpp:2833
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
Expr * getPtr() const
Definition: Expr.h:5839
static QualType getDecayedSourceLocExprType(const ASTContext &Ctx, SourceLocExpr::IdentKind Kind)
Definition: Expr.cpp:2135
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:6908
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:414
NullPointerConstantValueDependence
Enumeration used to describe how isNullPointerConstant() should cope with value-dependent expressions...
Definition: Expr.h:727
unsigned getNumPreArgs() const
Definition: Expr.h:2602
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1862
static bool isRecordType(QualType T)
semantics_iterator semantics_end()
Definition: Expr.h:5747
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3409
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6218
SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc, SourceLocation RParenLoc, DeclContext *Context)
Definition: Expr.cpp:2150
child_range children()
Definition: Expr.h:4560
bool isBoundMemberFunction(ASTContext &Ctx) const
Returns true if this expression is a bound member function.
Definition: Expr.cpp:2776
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2971
StringKind
StringLiteral is followed by several trailing objects.
Definition: Expr.h:1708
field_iterator field_begin() const
Definition: Decl.cpp:4317
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1166
SourceLocation getCaretLocation() const
Definition: Expr.cpp:2364
IdentKind getIdentKind() const
Definition: Expr.h:4288
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token...
Definition: Lexer.h:363
static bool isBooleanType(QualType Ty)
An adjustment to be made to the temporary created when emitting a reference binding, which accesses a particular subobject of that temporary.
Definition: Expr.h:63
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3125
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1282
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1301
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1727
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1446
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:925
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name, with source-location information.
Definition: Expr.h:1241
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:176
bool needsCleanup() const
Returns whether the object performed allocations.
Definition: APValue.cpp:321
An ordinary object is located at an address in memory.
Definition: Specifiers.h:141
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4116
Represents an ObjC class declaration.
Definition: DeclObjC.h:1171
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2055
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3093
Expression is a GNU-style __null constant.
Definition: Expr.h:722
StmtClass
Definition: Stmt.h:68
const Stmt * getBody() const
Definition: Expr.cpp:2367
A binding in a decomposition declaration.
Definition: DeclCXX.h:3880
bool isUnevaluated(unsigned ID) const
Returns true if this builtin does not perform the side-effects of its arguments.
Definition: Builtins.h:127
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition: Expr.cpp:316
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1111
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix)
Retrieve the unary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:1300
void setIntValue(const ASTContext &C, const llvm::APInt &Val)
Definition: Expr.cpp:896
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2950
bool isObjCSelfExpr() const
Check if this expression is the ObjC &#39;self&#39; implicit parameter.
Definition: Expr.cpp:3821
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition: Expr.cpp:1659
Represents the this expression in C++.
Definition: ExprCXX.h:1006
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, Expr *LHS, Expr *RHS)
Definition: Expr.cpp:2102
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:650
PredefinedExprBitfields PredefinedExprBits
Definition: Stmt.h:961
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3335
bool isInstantiationDependent() const
Whether this nested name specifier involves a template parameter.
void print(const PrintingPolicy &Policy, raw_ostream &Out) const
Print this template argument to the given output stream.
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition: Expr.cpp:1490
bool hasAttr() const
Definition: DeclBase.h:542
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3707
Expr()=delete
llvm::iterator_range< const_child_iterator > const_child_range
Definition: Stmt.h:1159
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1310
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1649
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3725
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1403
CastKind
CastKind - The kind of operation required for a conversion.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1981
Specifies that the expression should never be value-dependent.
Definition: Expr.h:729
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
StringRef getBuiltinStr() const
Return a string representing the name of the specific builtin function.
Definition: Expr.cpp:2159
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:2347
iterator end()
Definition: ASTVector.h:99
InitListExpr * getUpdater() const
Definition: Expr.h:4967
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:953
void outputString(raw_ostream &OS) const
Definition: Expr.cpp:1103
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
ConstStmtIterator const_child_iterator
Definition: Stmt.h:1156
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr&#39;s will refer to the same value as a comparison operand.
Definition: Expr.cpp:3924
unsigned Offset
Definition: Format.cpp:1758
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3343
Exposes information about the current target.
Definition: TargetInfo.h:161
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:151
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:436
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1081
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr *> Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1381
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function)...
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:636
This represents one expression.
Definition: Expr.h:108
void setDesignators(const ASTContext &C, const Designator *Desigs, unsigned NumDesigs)
Definition: Expr.cpp:4316
SourceLocation End
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:122
void setCallee(Expr *F)
Definition: Expr.h:2640
A non-discriminated union of a base, field, or array index.
Definition: APValue.h:151
static Expr * IgnoreExprNodesImpl(Expr *E)
Definition: Expr.cpp:2931
std::string Label
IdentifierInfo * getFieldName() const
For a field or identifier offsetof node, returns the name of the field.
Definition: Expr.cpp:1593
static Expr * IgnoreImpCastsSingleStep(Expr *E)
Definition: Expr.cpp:2806
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:1748
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6922
unsigned getLine() const
Return the presumed line number of this location.
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
void setTypeDependent(bool TD)
Set whether this expression is type-dependent or not.
Definition: Expr.h:179
#define V(N, I)
Definition: ASTContext.h:2915
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
Definition: opencl-c-base.h:62
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2793
Expr * getCallee()
Definition: Expr.h:2638
unsigned getNumInits() const
Definition: Expr.h:4405
bool isNullPtrType() const
Definition: Type.h:6674
const Expr * skipRValueSubobjectAdjustments() const
Definition: Expr.h:903
field_iterator field_end() const
Definition: Decl.h:3852
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:291
DeclContext * getDeclContext()
Definition: DeclBase.h:438
ExprBitfields ExprBits
Definition: Stmt.h:959
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier, e.g., N::foo.
Definition: Expr.h:1237
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode. ...
Definition: Expr.cpp:1315
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:981
Represents the type decltype(expr) (C++11).
Definition: Type.h:4320
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
ArrayRef< Expr * > inits()
Definition: Expr.h:4415
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:733
Extra data stored in some MemberExpr objects.
Definition: Expr.h:2799
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type...
Definition: Expr.cpp:3038
llvm::APSInt getResultAsAPSInt() const
Definition: Expr.cpp:339
Base object dtor.
Definition: ABI.h:36
QualType getType() const
Definition: Expr.h:137
void addDestruction(T *Ptr) const
If T isn&#39;t trivially destructible, calls AddDeallocation to register it for destruction.
Definition: ASTContext.h:2766
StringLiteralBitfields StringLiteralBits
Definition: Stmt.h:964
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1779
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, IdentKind IK, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:630
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:950
Represents an unpacked "presumed" location which can be presented to the user.
InitListExpr(const ASTContext &C, SourceLocation lbraceloc, ArrayRef< Expr *> initExprs, SourceLocation rbraceloc)
Definition: Expr.cpp:2219
Expr * getSubExprAsWritten()
Retrieve the cast subexpression as it was written in the source code, looking through any implicit ca...
Definition: Expr.cpp:1904
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:2021
unsigned Index
Location of the first index expression within the designated initializer expression&#39;s list of subexpr...
Definition: Expr.h:4670
Represents a GCC generic vector type.
Definition: Type.h:3206
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:4787
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4115
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1089
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition: Expr.h:607
ValueDecl * getDecl()
Definition: Expr.h:1222
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1399
The result type of a method or function.
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2048
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr.cast]), which uses the syntax (Type)expr.
Definition: Expr.h:3346
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:708
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:413
reverse_iterator rend()
Definition: ASTVector.h:105
do v
Definition: arm_acle.h:64
const SourceManager & SM
Definition: Format.cpp:1616
SourceRange getSourceRange() const
Definition: ExprCXX.h:140
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:287
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:421
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1468
APValue getAPValueResult() const
Definition: Expr.cpp:351
unsigned getWCharWidth() const
getWCharWidth/Align - Return the size of &#39;wchar_t&#39; for this target, in bits.
Definition: TargetInfo.h:560
RecordDecl * getDecl() const
Definition: Type.h:4454
const char * getFilename() const
Return the presumed filename of this location.
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:128
Expr * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:2954
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2039
Expr * IgnoreConversionOperator() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:2975
AtomicExpr(SourceLocation BLoc, ArrayRef< Expr *> args, QualType t, AtomicOp op, SourceLocation RP)
Definition: Expr.cpp:4558
unsigned DotLoc
The location of the &#39;.&#39; in the designated initializer.
Definition: Expr.h:4660