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