clang  9.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;
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_UserDefinedConversion: // operator bool()
1866  case CK_BuiltinFnToFnPtr:
1867  case CK_FixedPointToBoolean:
1868  CheckNoBasePath:
1869  assert(path_empty() && "Cast kind should not have a base path!");
1870  break;
1871  }
1872  return true;
1873 }
1874 
1876  switch (CK) {
1877 #define CAST_OPERATION(Name) case CK_##Name: return #Name;
1878 #include "clang/AST/OperationKinds.def"
1879  }
1880  llvm_unreachable("Unhandled cast kind!");
1881 }
1882 
1883 namespace {
1884  const Expr *skipImplicitTemporary(const Expr *E) {
1885  // Skip through reference binding to temporary.
1886  if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1887  E = Materialize->GetTemporaryExpr();
1888 
1889  // Skip any temporary bindings; they're implicit.
1890  if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1891  E = Binder->getSubExpr();
1892 
1893  return E;
1894  }
1895 }
1896 
1898  const Expr *SubExpr = nullptr;
1899  const CastExpr *E = this;
1900  do {
1901  SubExpr = skipImplicitTemporary(E->getSubExpr());
1902 
1903  // Conversions by constructor and conversion functions have a
1904  // subexpression describing the call; strip it off.
1905  if (E->getCastKind() == CK_ConstructorConversion)
1906  SubExpr =
1907  skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
1908  else if (E->getCastKind() == CK_UserDefinedConversion) {
1909  assert((isa<CXXMemberCallExpr>(SubExpr) ||
1910  isa<BlockExpr>(SubExpr)) &&
1911  "Unexpected SubExpr for CK_UserDefinedConversion.");
1912  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1913  SubExpr = MCE->getImplicitObjectArgument();
1914  }
1915 
1916  // If the subexpression we're left with is an implicit cast, look
1917  // through that, too.
1918  } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1919 
1920  return const_cast<Expr*>(SubExpr);
1921 }
1922 
1924  const Expr *SubExpr = nullptr;
1925 
1926  for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1927  SubExpr = skipImplicitTemporary(E->getSubExpr());
1928 
1929  if (E->getCastKind() == CK_ConstructorConversion)
1930  return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1931 
1932  if (E->getCastKind() == CK_UserDefinedConversion) {
1933  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1934  return MCE->getMethodDecl();
1935  }
1936  }
1937 
1938  return nullptr;
1939 }
1940 
1941 CXXBaseSpecifier **CastExpr::path_buffer() {
1942  switch (getStmtClass()) {
1943 #define ABSTRACT_STMT(x)
1944 #define CASTEXPR(Type, Base) \
1945  case Stmt::Type##Class: \
1946  return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1947 #define STMT(Type, Base)
1948 #include "clang/AST/StmtNodes.inc"
1949  default:
1950  llvm_unreachable("non-cast expressions not possible here");
1951  }
1952 }
1953 
1955  QualType opType) {
1956  auto RD = unionType->castAs<RecordType>()->getDecl();
1957  return getTargetFieldForToUnionCast(RD, opType);
1958 }
1959 
1961  QualType OpType) {
1962  auto &Ctx = RD->getASTContext();
1963  RecordDecl::field_iterator Field, FieldEnd;
1964  for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1965  Field != FieldEnd; ++Field) {
1966  if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1967  !Field->isUnnamedBitfield()) {
1968  return *Field;
1969  }
1970  }
1971  return nullptr;
1972 }
1973 
1975  CastKind Kind, Expr *Operand,
1976  const CXXCastPath *BasePath,
1977  ExprValueKind VK) {
1978  unsigned PathSize = (BasePath ? BasePath->size() : 0);
1979  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1980  // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
1981  // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
1982  assert((Kind != CK_LValueToRValue ||
1983  !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
1984  "invalid type for lvalue-to-rvalue conversion");
1985  ImplicitCastExpr *E =
1986  new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1987  if (PathSize)
1988  std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1989  E->getTrailingObjects<CXXBaseSpecifier *>());
1990  return E;
1991 }
1992 
1994  unsigned PathSize) {
1995  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1996  return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1997 }
1998 
1999 
2001  ExprValueKind VK, CastKind K, Expr *Op,
2002  const CXXCastPath *BasePath,
2003  TypeSourceInfo *WrittenTy,
2005  unsigned PathSize = (BasePath ? BasePath->size() : 0);
2006  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
2007  CStyleCastExpr *E =
2008  new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
2009  if (PathSize)
2010  std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2011  E->getTrailingObjects<CXXBaseSpecifier *>());
2012  return E;
2013 }
2014 
2016  unsigned PathSize) {
2017  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
2018  return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
2019 }
2020 
2021 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2022 /// corresponds to, e.g. "<<=".
2024  switch (Op) {
2025 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2026 #include "clang/AST/OperationKinds.def"
2027  }
2028  llvm_unreachable("Invalid OpCode!");
2029 }
2030 
2033  switch (OO) {
2034  default: llvm_unreachable("Not an overloadable binary operator");
2035  case OO_Plus: return BO_Add;
2036  case OO_Minus: return BO_Sub;
2037  case OO_Star: return BO_Mul;
2038  case OO_Slash: return BO_Div;
2039  case OO_Percent: return BO_Rem;
2040  case OO_Caret: return BO_Xor;
2041  case OO_Amp: return BO_And;
2042  case OO_Pipe: return BO_Or;
2043  case OO_Equal: return BO_Assign;
2044  case OO_Spaceship: return BO_Cmp;
2045  case OO_Less: return BO_LT;
2046  case OO_Greater: return BO_GT;
2047  case OO_PlusEqual: return BO_AddAssign;
2048  case OO_MinusEqual: return BO_SubAssign;
2049  case OO_StarEqual: return BO_MulAssign;
2050  case OO_SlashEqual: return BO_DivAssign;
2051  case OO_PercentEqual: return BO_RemAssign;
2052  case OO_CaretEqual: return BO_XorAssign;
2053  case OO_AmpEqual: return BO_AndAssign;
2054  case OO_PipeEqual: return BO_OrAssign;
2055  case OO_LessLess: return BO_Shl;
2056  case OO_GreaterGreater: return BO_Shr;
2057  case OO_LessLessEqual: return BO_ShlAssign;
2058  case OO_GreaterGreaterEqual: return BO_ShrAssign;
2059  case OO_EqualEqual: return BO_EQ;
2060  case OO_ExclaimEqual: return BO_NE;
2061  case OO_LessEqual: return BO_LE;
2062  case OO_GreaterEqual: return BO_GE;
2063  case OO_AmpAmp: return BO_LAnd;
2064  case OO_PipePipe: return BO_LOr;
2065  case OO_Comma: return BO_Comma;
2066  case OO_ArrowStar: return BO_PtrMemI;
2067  }
2068 }
2069 
2071  static const OverloadedOperatorKind OverOps[] = {
2072  /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2073  OO_Star, OO_Slash, OO_Percent,
2074  OO_Plus, OO_Minus,
2075  OO_LessLess, OO_GreaterGreater,
2076  OO_Spaceship,
2077  OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2078  OO_EqualEqual, OO_ExclaimEqual,
2079  OO_Amp,
2080  OO_Caret,
2081  OO_Pipe,
2082  OO_AmpAmp,
2083  OO_PipePipe,
2084  OO_Equal, OO_StarEqual,
2085  OO_SlashEqual, OO_PercentEqual,
2086  OO_PlusEqual, OO_MinusEqual,
2087  OO_LessLessEqual, OO_GreaterGreaterEqual,
2088  OO_AmpEqual, OO_CaretEqual,
2089  OO_PipeEqual,
2090  OO_Comma
2091  };
2092  return OverOps[Opc];
2093 }
2094 
2096  Opcode Opc,
2097  Expr *LHS, Expr *RHS) {
2098  if (Opc != BO_Add)
2099  return false;
2100 
2101  // Check that we have one pointer and one integer operand.
2102  Expr *PExp;
2103  if (LHS->getType()->isPointerType()) {
2104  if (!RHS->getType()->isIntegerType())
2105  return false;
2106  PExp = LHS;
2107  } else if (RHS->getType()->isPointerType()) {
2108  if (!LHS->getType()->isIntegerType())
2109  return false;
2110  PExp = RHS;
2111  } else {
2112  return false;
2113  }
2114 
2115  // Check that the pointer is a nullptr.
2116  if (!PExp->IgnoreParenCasts()
2118  return false;
2119 
2120  // Check that the pointee type is char-sized.
2121  const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2122  if (!PTy || !PTy->getPointeeType()->isCharType())
2123  return false;
2124 
2125  return true;
2126 }
2127 
2130  switch (Kind) {
2131  case SourceLocExpr::File:
2132  case SourceLocExpr::Function: {
2133  QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2134  return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2135  }
2136  case SourceLocExpr::Line:
2137  case SourceLocExpr::Column:
2138  return Ctx.UnsignedIntTy;
2139  }
2140  llvm_unreachable("unhandled case");
2141 }
2142 
2144  SourceLocation BLoc, SourceLocation RParenLoc,
2145  DeclContext *ParentContext)
2146  : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2148  BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2149  SourceLocExprBits.Kind = Kind;
2150 }
2151 
2152 StringRef SourceLocExpr::getBuiltinStr() const {
2153  switch (getIdentKind()) {
2154  case File:
2155  return "__builtin_FILE";
2156  case Function:
2157  return "__builtin_FUNCTION";
2158  case Line:
2159  return "__builtin_LINE";
2160  case Column:
2161  return "__builtin_COLUMN";
2162  }
2163  llvm_unreachable("unexpected IdentKind!");
2164 }
2165 
2167  const Expr *DefaultExpr) const {
2168  SourceLocation Loc;
2169  const DeclContext *Context;
2170 
2171  std::tie(Loc,
2172  Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2173  if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2174  return {DIE->getUsedLocation(), DIE->getUsedContext()};
2175  if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2176  return {DAE->getUsedLocation(), DAE->getUsedContext()};
2177  return {this->getLocation(), this->getParentContext()};
2178  }();
2179 
2182 
2183  auto MakeStringLiteral = [&](StringRef Tmp) {
2184  using LValuePathEntry = APValue::LValuePathEntry;
2186  // Decay the string to a pointer to the first character.
2187  LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2188  return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2189  };
2190 
2191  switch (getIdentKind()) {
2192  case SourceLocExpr::File:
2193  return MakeStringLiteral(PLoc.getFilename());
2194  case SourceLocExpr::Function: {
2195  const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2196  return MakeStringLiteral(
2198  : std::string(""));
2199  }
2200  case SourceLocExpr::Line:
2201  case SourceLocExpr::Column: {
2202  llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2203  /*IsUnsigned=*/true);
2204  IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2205  : PLoc.getColumn();
2206  return APValue(IntVal);
2207  }
2208  }
2209  llvm_unreachable("unhandled case");
2210 }
2211 
2213  ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
2214  : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
2215  false, false),
2216  InitExprs(C, initExprs.size()),
2217  LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
2218 {
2219  sawArrayRangeDesignator(false);
2220  for (unsigned I = 0; I != initExprs.size(); ++I) {
2221  if (initExprs[I]->isTypeDependent())
2222  ExprBits.TypeDependent = true;
2223  if (initExprs[I]->isValueDependent())
2224  ExprBits.ValueDependent = true;
2225  if (initExprs[I]->isInstantiationDependent())
2226  ExprBits.InstantiationDependent = true;
2227  if (initExprs[I]->containsUnexpandedParameterPack())
2228  ExprBits.ContainsUnexpandedParameterPack = true;
2229  }
2230 
2231  InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2232 }
2233 
2234 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2235  if (NumInits > InitExprs.size())
2236  InitExprs.reserve(C, NumInits);
2237 }
2238 
2239 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2240  InitExprs.resize(C, NumInits, nullptr);
2241 }
2242 
2243 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2244  if (Init >= InitExprs.size()) {
2245  InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2246  setInit(Init, expr);
2247  return nullptr;
2248  }
2249 
2250  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2251  setInit(Init, expr);
2252  return Result;
2253 }
2254 
2256  assert(!hasArrayFiller() && "Filler already set!");
2257  ArrayFillerOrUnionFieldInit = filler;
2258  // Fill out any "holes" in the array due to designated initializers.
2259  Expr **inits = getInits();
2260  for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2261  if (inits[i] == nullptr)
2262  inits[i] = filler;
2263 }
2264 
2266  if (getNumInits() != 1)
2267  return false;
2268  const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2269  if (!AT || !AT->getElementType()->isIntegerType())
2270  return false;
2271  // It is possible for getInit() to return null.
2272  const Expr *Init = getInit(0);
2273  if (!Init)
2274  return false;
2275  Init = Init->IgnoreParens();
2276  return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2277 }
2278 
2280  assert(isSemanticForm() && "syntactic form never semantically transparent");
2281 
2282  // A glvalue InitListExpr is always just sugar.
2283  if (isGLValue()) {
2284  assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2285  return true;
2286  }
2287 
2288  // Otherwise, we're sugar if and only if we have exactly one initializer that
2289  // is of the same type.
2290  if (getNumInits() != 1 || !getInit(0))
2291  return false;
2292 
2293  // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2294  // transparent struct copy.
2295  if (!getInit(0)->isRValue() && getType()->isRecordType())
2296  return false;
2297 
2298  return getType().getCanonicalType() ==
2300 }
2301 
2303  assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2304 
2305  if (LangOpts.CPlusPlus || getNumInits() != 1) {
2306  return false;
2307  }
2308 
2309  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
2310  return Lit && Lit->getValue() == 0;
2311 }
2312 
2314  if (InitListExpr *SyntacticForm = getSyntacticForm())
2315  return SyntacticForm->getBeginLoc();
2316  SourceLocation Beg = LBraceLoc;
2317  if (Beg.isInvalid()) {
2318  // Find the first non-null initializer.
2319  for (InitExprsTy::const_iterator I = InitExprs.begin(),
2320  E = InitExprs.end();
2321  I != E; ++I) {
2322  if (Stmt *S = *I) {
2323  Beg = S->getBeginLoc();
2324  break;
2325  }
2326  }
2327  }
2328  return Beg;
2329 }
2330 
2332  if (InitListExpr *SyntacticForm = getSyntacticForm())
2333  return SyntacticForm->getEndLoc();
2334  SourceLocation End = RBraceLoc;
2335  if (End.isInvalid()) {
2336  // Find the first non-null initializer from the end.
2337  for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
2338  E = InitExprs.rend();
2339  I != E; ++I) {
2340  if (Stmt *S = *I) {
2341  End = S->getEndLoc();
2342  break;
2343  }
2344  }
2345  }
2346  return End;
2347 }
2348 
2349 /// getFunctionType - Return the underlying function type for this block.
2350 ///
2352  // The block pointer is never sugared, but the function type might be.
2353  return cast<BlockPointerType>(getType())
2354  ->getPointeeType()->castAs<FunctionProtoType>();
2355 }
2356 
2358  return TheBlock->getCaretLocation();
2359 }
2360 const Stmt *BlockExpr::getBody() const {
2361  return TheBlock->getBody();
2362 }
2364  return TheBlock->getBody();
2365 }
2366 
2367 
2368 //===----------------------------------------------------------------------===//
2369 // Generic Expression Routines
2370 //===----------------------------------------------------------------------===//
2371 
2372 /// isUnusedResultAWarning - Return true if this immediate expression should
2373 /// be warned about if the result is unused. If so, fill in Loc and Ranges
2374 /// with location to warn on and the source range[s] to report with the
2375 /// warning.
2377  SourceRange &R1, SourceRange &R2,
2378  ASTContext &Ctx) const {
2379  // Don't warn if the expr is type dependent. The type could end up
2380  // instantiating to void.
2381  if (isTypeDependent())
2382  return false;
2383 
2384  switch (getStmtClass()) {
2385  default:
2386  if (getType()->isVoidType())
2387  return false;
2388  WarnE = this;
2389  Loc = getExprLoc();
2390  R1 = getSourceRange();
2391  return true;
2392  case ParenExprClass:
2393  return cast<ParenExpr>(this)->getSubExpr()->
2394  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2395  case GenericSelectionExprClass:
2396  return cast<GenericSelectionExpr>(this)->getResultExpr()->
2397  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2398  case CoawaitExprClass:
2399  case CoyieldExprClass:
2400  return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2401  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2402  case ChooseExprClass:
2403  return cast<ChooseExpr>(this)->getChosenSubExpr()->
2404  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2405  case UnaryOperatorClass: {
2406  const UnaryOperator *UO = cast<UnaryOperator>(this);
2407 
2408  switch (UO->getOpcode()) {
2409  case UO_Plus:
2410  case UO_Minus:
2411  case UO_AddrOf:
2412  case UO_Not:
2413  case UO_LNot:
2414  case UO_Deref:
2415  break;
2416  case UO_Coawait:
2417  // This is just the 'operator co_await' call inside the guts of a
2418  // dependent co_await call.
2419  case UO_PostInc:
2420  case UO_PostDec:
2421  case UO_PreInc:
2422  case UO_PreDec: // ++/--
2423  return false; // Not a warning.
2424  case UO_Real:
2425  case UO_Imag:
2426  // accessing a piece of a volatile complex is a side-effect.
2427  if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2428  .isVolatileQualified())
2429  return false;
2430  break;
2431  case UO_Extension:
2432  return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2433  }
2434  WarnE = this;
2435  Loc = UO->getOperatorLoc();
2436  R1 = UO->getSubExpr()->getSourceRange();
2437  return true;
2438  }
2439  case BinaryOperatorClass: {
2440  const BinaryOperator *BO = cast<BinaryOperator>(this);
2441  switch (BO->getOpcode()) {
2442  default:
2443  break;
2444  // Consider the RHS of comma for side effects. LHS was checked by
2445  // Sema::CheckCommaOperands.
2446  case BO_Comma:
2447  // ((foo = <blah>), 0) is an idiom for hiding the result (and
2448  // lvalue-ness) of an assignment written in a macro.
2449  if (IntegerLiteral *IE =
2450  dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2451  if (IE->getValue() == 0)
2452  return false;
2453  return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2454  // Consider '||', '&&' to have side effects if the LHS or RHS does.
2455  case BO_LAnd:
2456  case BO_LOr:
2457  if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2458  !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2459  return false;
2460  break;
2461  }
2462  if (BO->isAssignmentOp())
2463  return false;
2464  WarnE = this;
2465  Loc = BO->getOperatorLoc();
2466  R1 = BO->getLHS()->getSourceRange();
2467  R2 = BO->getRHS()->getSourceRange();
2468  return true;
2469  }
2470  case CompoundAssignOperatorClass:
2471  case VAArgExprClass:
2472  case AtomicExprClass:
2473  return false;
2474 
2475  case ConditionalOperatorClass: {
2476  // If only one of the LHS or RHS is a warning, the operator might
2477  // be being used for control flow. Only warn if both the LHS and
2478  // RHS are warnings.
2479  const auto *Exp = cast<ConditionalOperator>(this);
2480  return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2481  Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2482  }
2483  case BinaryConditionalOperatorClass: {
2484  const auto *Exp = cast<BinaryConditionalOperator>(this);
2485  return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2486  }
2487 
2488  case MemberExprClass:
2489  WarnE = this;
2490  Loc = cast<MemberExpr>(this)->getMemberLoc();
2491  R1 = SourceRange(Loc, Loc);
2492  R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2493  return true;
2494 
2495  case ArraySubscriptExprClass:
2496  WarnE = this;
2497  Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2498  R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2499  R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2500  return true;
2501 
2502  case CXXOperatorCallExprClass: {
2503  // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2504  // overloads as there is no reasonable way to define these such that they
2505  // have non-trivial, desirable side-effects. See the -Wunused-comparison
2506  // warning: operators == and != are commonly typo'ed, and so warning on them
2507  // provides additional value as well. If this list is updated,
2508  // DiagnoseUnusedComparison should be as well.
2509  const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2510  switch (Op->getOperator()) {
2511  default:
2512  break;
2513  case OO_EqualEqual:
2514  case OO_ExclaimEqual:
2515  case OO_Less:
2516  case OO_Greater:
2517  case OO_GreaterEqual:
2518  case OO_LessEqual:
2519  if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2520  Op->getCallReturnType(Ctx)->isVoidType())
2521  break;
2522  WarnE = this;
2523  Loc = Op->getOperatorLoc();
2524  R1 = Op->getSourceRange();
2525  return true;
2526  }
2527 
2528  // Fallthrough for generic call handling.
2529  LLVM_FALLTHROUGH;
2530  }
2531  case CallExprClass:
2532  case CXXMemberCallExprClass:
2533  case UserDefinedLiteralClass: {
2534  // If this is a direct call, get the callee.
2535  const CallExpr *CE = cast<CallExpr>(this);
2536  if (const Decl *FD = CE->getCalleeDecl()) {
2537  // If the callee has attribute pure, const, or warn_unused_result, warn
2538  // about it. void foo() { strlen("bar"); } should warn.
2539  //
2540  // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2541  // updated to match for QoI.
2542  if (CE->hasUnusedResultAttr(Ctx) ||
2543  FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2544  WarnE = this;
2545  Loc = CE->getCallee()->getBeginLoc();
2546  R1 = CE->getCallee()->getSourceRange();
2547 
2548  if (unsigned NumArgs = CE->getNumArgs())
2549  R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2550  CE->getArg(NumArgs - 1)->getEndLoc());
2551  return true;
2552  }
2553  }
2554  return false;
2555  }
2556 
2557  // If we don't know precisely what we're looking at, let's not warn.
2558  case UnresolvedLookupExprClass:
2559  case CXXUnresolvedConstructExprClass:
2560  return false;
2561 
2562  case CXXTemporaryObjectExprClass:
2563  case CXXConstructExprClass: {
2564  if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2565  if (Type->hasAttr<WarnUnusedAttr>()) {
2566  WarnE = this;
2567  Loc = getBeginLoc();
2568  R1 = getSourceRange();
2569  return true;
2570  }
2571  }
2572  return false;
2573  }
2574 
2575  case ObjCMessageExprClass: {
2576  const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2577  if (Ctx.getLangOpts().ObjCAutoRefCount &&
2578  ME->isInstanceMessage() &&
2579  !ME->getType()->isVoidType() &&
2580  ME->getMethodFamily() == OMF_init) {
2581  WarnE = this;
2582  Loc = getExprLoc();
2583  R1 = ME->getSourceRange();
2584  return true;
2585  }
2586 
2587  if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2588  if (MD->hasAttr<WarnUnusedResultAttr>()) {
2589  WarnE = this;
2590  Loc = getExprLoc();
2591  return true;
2592  }
2593 
2594  return false;
2595  }
2596 
2597  case ObjCPropertyRefExprClass:
2598  WarnE = this;
2599  Loc = getExprLoc();
2600  R1 = getSourceRange();
2601  return true;
2602 
2603  case PseudoObjectExprClass: {
2604  const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2605 
2606  // Only complain about things that have the form of a getter.
2607  if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2608  isa<BinaryOperator>(PO->getSyntacticForm()))
2609  return false;
2610 
2611  WarnE = this;
2612  Loc = getExprLoc();
2613  R1 = getSourceRange();
2614  return true;
2615  }
2616 
2617  case StmtExprClass: {
2618  // Statement exprs don't logically have side effects themselves, but are
2619  // sometimes used in macros in ways that give them a type that is unused.
2620  // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2621  // however, if the result of the stmt expr is dead, we don't want to emit a
2622  // warning.
2623  const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2624  if (!CS->body_empty()) {
2625  if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2626  return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2627  if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2628  if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2629  return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2630  }
2631 
2632  if (getType()->isVoidType())
2633  return false;
2634  WarnE = this;
2635  Loc = cast<StmtExpr>(this)->getLParenLoc();
2636  R1 = getSourceRange();
2637  return true;
2638  }
2639  case CXXFunctionalCastExprClass:
2640  case CStyleCastExprClass: {
2641  // Ignore an explicit cast to void unless the operand is a non-trivial
2642  // volatile lvalue.
2643  const CastExpr *CE = cast<CastExpr>(this);
2644  if (CE->getCastKind() == CK_ToVoid) {
2645  if (CE->getSubExpr()->isGLValue() &&
2646  CE->getSubExpr()->getType().isVolatileQualified()) {
2647  const DeclRefExpr *DRE =
2648  dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2649  if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2650  cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2651  !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
2652  return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2653  R1, R2, Ctx);
2654  }
2655  }
2656  return false;
2657  }
2658 
2659  // If this is a cast to a constructor conversion, check the operand.
2660  // Otherwise, the result of the cast is unused.
2661  if (CE->getCastKind() == CK_ConstructorConversion)
2662  return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2663 
2664  WarnE = this;
2665  if (const CXXFunctionalCastExpr *CXXCE =
2666  dyn_cast<CXXFunctionalCastExpr>(this)) {
2667  Loc = CXXCE->getBeginLoc();
2668  R1 = CXXCE->getSubExpr()->getSourceRange();
2669  } else {
2670  const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2671  Loc = CStyleCE->getLParenLoc();
2672  R1 = CStyleCE->getSubExpr()->getSourceRange();
2673  }
2674  return true;
2675  }
2676  case ImplicitCastExprClass: {
2677  const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2678 
2679  // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2680  if (ICE->getCastKind() == CK_LValueToRValue &&
2682  return false;
2683 
2684  return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2685  }
2686  case CXXDefaultArgExprClass:
2687  return (cast<CXXDefaultArgExpr>(this)
2688  ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2689  case CXXDefaultInitExprClass:
2690  return (cast<CXXDefaultInitExpr>(this)
2691  ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2692 
2693  case CXXNewExprClass:
2694  // FIXME: In theory, there might be new expressions that don't have side
2695  // effects (e.g. a placement new with an uninitialized POD).
2696  case CXXDeleteExprClass:
2697  return false;
2698  case MaterializeTemporaryExprClass:
2699  return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2700  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2701  case CXXBindTemporaryExprClass:
2702  return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2703  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2704  case ExprWithCleanupsClass:
2705  return cast<ExprWithCleanups>(this)->getSubExpr()
2706  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2707  }
2708 }
2709 
2710 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2711 /// returns true, if it is; false otherwise.
2713  const Expr *E = IgnoreParens();
2714  switch (E->getStmtClass()) {
2715  default:
2716  return false;
2717  case ObjCIvarRefExprClass:
2718  return true;
2719  case Expr::UnaryOperatorClass:
2720  return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2721  case ImplicitCastExprClass:
2722  return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2723  case MaterializeTemporaryExprClass:
2724  return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2725  ->isOBJCGCCandidate(Ctx);
2726  case CStyleCastExprClass:
2727  return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2728  case DeclRefExprClass: {
2729  const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2730 
2731  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2732  if (VD->hasGlobalStorage())
2733  return true;
2734  QualType T = VD->getType();
2735  // dereferencing to a pointer is always a gc'able candidate,
2736  // unless it is __weak.
2737  return T->isPointerType() &&
2738  (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2739  }
2740  return false;
2741  }
2742  case MemberExprClass: {
2743  const MemberExpr *M = cast<MemberExpr>(E);
2744  return M->getBase()->isOBJCGCCandidate(Ctx);
2745  }
2746  case ArraySubscriptExprClass:
2747  return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2748  }
2749 }
2750 
2752  if (isTypeDependent())
2753  return false;
2754  return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2755 }
2756 
2758  assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2759 
2760  // Bound member expressions are always one of these possibilities:
2761  // x->m x.m x->*y x.*y
2762  // (possibly parenthesized)
2763 
2764  expr = expr->IgnoreParens();
2765  if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2766  assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2767  return mem->getMemberDecl()->getType();
2768  }
2769 
2770  if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2771  QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2772  ->getPointeeType();
2773  assert(type->isFunctionType());
2774  return type;
2775  }
2776 
2777  assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
2778  return QualType();
2779 }
2780 
2782  if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2783  return ICE->getSubExpr();
2784 
2785  if (auto *FE = dyn_cast<FullExpr>(E))
2786  return FE->getSubExpr();
2787 
2788  return E;
2789 }
2790 
2792  // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2793  // addition to what IgnoreImpCasts() skips to account for the current
2794  // behaviour of IgnoreParenImpCasts().
2795  Expr *SubE = IgnoreImpCastsSingleStep(E);
2796  if (SubE != E)
2797  return SubE;
2798 
2799  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2800  return MTE->GetTemporaryExpr();
2801 
2802  if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2803  return NTTP->getReplacement();
2804 
2805  return E;
2806 }
2807 
2809  if (auto *CE = dyn_cast<CastExpr>(E))
2810  return CE->getSubExpr();
2811 
2812  if (auto *FE = dyn_cast<FullExpr>(E))
2813  return FE->getSubExpr();
2814 
2815  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2816  return MTE->GetTemporaryExpr();
2817 
2818  if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2819  return NTTP->getReplacement();
2820 
2821  return E;
2822 }
2823 
2825  // Skip what IgnoreCastsSingleStep skips, except that only
2826  // lvalue-to-rvalue casts are skipped.
2827  if (auto *CE = dyn_cast<CastExpr>(E))
2828  if (CE->getCastKind() != CK_LValueToRValue)
2829  return E;
2830 
2831  return IgnoreCastsSingleStep(E);
2832 }
2833 
2835  if (auto *CE = dyn_cast<CastExpr>(E))
2836  if (CE->getCastKind() == CK_DerivedToBase ||
2837  CE->getCastKind() == CK_UncheckedDerivedToBase ||
2838  CE->getCastKind() == CK_NoOp)
2839  return CE->getSubExpr();
2840 
2841  return E;
2842 }
2843 
2845  Expr *SubE = IgnoreImpCastsSingleStep(E);
2846  if (SubE != E)
2847  return SubE;
2848 
2849  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2850  return MTE->GetTemporaryExpr();
2851 
2852  if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2853  return BTE->getSubExpr();
2854 
2855  return E;
2856 }
2857 
2859  if (auto *PE = dyn_cast<ParenExpr>(E))
2860  return PE->getSubExpr();
2861 
2862  if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2863  if (UO->getOpcode() == UO_Extension)
2864  return UO->getSubExpr();
2865  }
2866 
2867  else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2868  if (!GSE->isResultDependent())
2869  return GSE->getResultExpr();
2870  }
2871 
2872  else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2873  if (!CE->isConditionDependent())
2874  return CE->getChosenSubExpr();
2875  }
2876 
2877  else if (auto *CE = dyn_cast<ConstantExpr>(E))
2878  return CE->getSubExpr();
2879 
2880  return E;
2881 }
2882 
2884  if (auto *CE = dyn_cast<CastExpr>(E)) {
2885  // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2886  // ptr<->int casts of the same width. We also ignore all identity casts.
2887  Expr *SubExpr = CE->getSubExpr();
2888  bool IsIdentityCast =
2889  Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2890  bool IsSameWidthCast =
2891  (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2892  (SubExpr->getType()->isPointerType() ||
2893  SubExpr->getType()->isIntegralType(Ctx)) &&
2894  (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2895 
2896  if (IsIdentityCast || IsSameWidthCast)
2897  return SubExpr;
2898  }
2899 
2900  else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2901  return NTTP->getReplacement();
2902 
2903  return E;
2904 }
2905 
2906 static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2907 template <typename FnTy, typename... FnTys>
2908 static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2909  return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2910 }
2911 
2912 /// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2913 /// Recursively apply each of the functions to E until reaching a fixed point.
2914 /// Note that a null E is valid; in this case nothing is done.
2915 template <typename... FnTys>
2916 static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
2917  Expr *LastE = nullptr;
2918  while (E != LastE) {
2919  LastE = E;
2920  E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
2921  }
2922  return E;
2923 }
2924 
2927 }
2928 
2930  return IgnoreExprNodes(this, IgnoreCastsSingleStep);
2931 }
2932 
2935 }
2936 
2939 }
2940 
2944 }
2945 
2948 }
2949 
2951  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2952  if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2953  return MCE->getImplicitObjectArgument();
2954  }
2955  return this;
2956 }
2957 
2961 }
2962 
2966 }
2967 
2969  return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
2970  return IgnoreNoopCastsSingleStep(Ctx, E);
2971  });
2972 }
2973 
2975  const Expr *E = this;
2976  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2977  E = M->GetTemporaryExpr();
2978 
2979  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2980  E = ICE->getSubExprAsWritten();
2981 
2982  return isa<CXXDefaultArgExpr>(E);
2983 }
2984 
2985 /// Skip over any no-op casts and any temporary-binding
2986 /// expressions.
2988  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2989  E = M->GetTemporaryExpr();
2990 
2991  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2992  if (ICE->getCastKind() == CK_NoOp)
2993  E = ICE->getSubExpr();
2994  else
2995  break;
2996  }
2997 
2998  while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2999  E = BE->getSubExpr();
3000 
3001  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3002  if (ICE->getCastKind() == CK_NoOp)
3003  E = ICE->getSubExpr();
3004  else
3005  break;
3006  }
3007 
3008  return E->IgnoreParens();
3009 }
3010 
3011 /// isTemporaryObject - Determines if this expression produces a
3012 /// temporary of the given class type.
3013 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3014  if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3015  return false;
3016 
3018 
3019  // Temporaries are by definition pr-values of class type.
3020  if (!E->Classify(C).isPRValue()) {
3021  // In this context, property reference is a message call and is pr-value.
3022  if (!isa<ObjCPropertyRefExpr>(E))
3023  return false;
3024  }
3025 
3026  // Black-list a few cases which yield pr-values of class type that don't
3027  // refer to temporaries of that type:
3028 
3029  // - implicit derived-to-base conversions
3030  if (isa<ImplicitCastExpr>(E)) {
3031  switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3032  case CK_DerivedToBase:
3033  case CK_UncheckedDerivedToBase:
3034  return false;
3035  default:
3036  break;
3037  }
3038  }
3039 
3040  // - member expressions (all)
3041  if (isa<MemberExpr>(E))
3042  return false;
3043 
3044  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3045  if (BO->isPtrMemOp())
3046  return false;
3047 
3048  // - opaque values (all)
3049  if (isa<OpaqueValueExpr>(E))
3050  return false;
3051 
3052  return true;
3053 }
3054 
3056  const Expr *E = this;
3057 
3058  // Strip away parentheses and casts we don't care about.
3059  while (true) {
3060  if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3061  E = Paren->getSubExpr();
3062  continue;
3063  }
3064 
3065  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3066  if (ICE->getCastKind() == CK_NoOp ||
3067  ICE->getCastKind() == CK_LValueToRValue ||
3068  ICE->getCastKind() == CK_DerivedToBase ||
3069  ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3070  E = ICE->getSubExpr();
3071  continue;
3072  }
3073  }
3074 
3075  if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3076  if (UnOp->getOpcode() == UO_Extension) {
3077  E = UnOp->getSubExpr();
3078  continue;
3079  }
3080  }
3081 
3082  if (const MaterializeTemporaryExpr *M
3083  = dyn_cast<MaterializeTemporaryExpr>(E)) {
3084  E = M->GetTemporaryExpr();
3085  continue;
3086  }
3087 
3088  break;
3089  }
3090 
3091  if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3092  return This->isImplicit();
3093 
3094  return false;
3095 }
3096 
3097 /// hasAnyTypeDependentArguments - Determines if any of the expressions
3098 /// in Exprs is type-dependent.
3100  for (unsigned I = 0; I < Exprs.size(); ++I)
3101  if (Exprs[I]->isTypeDependent())
3102  return true;
3103 
3104  return false;
3105 }
3106 
3107 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3108  const Expr **Culprit) const {
3109  assert(!isValueDependent() &&
3110  "Expression evaluator can't be called on a dependent expression.");
3111 
3112  // This function is attempting whether an expression is an initializer
3113  // which can be evaluated at compile-time. It very closely parallels
3114  // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3115  // will lead to unexpected results. Like ConstExprEmitter, it falls back
3116  // to isEvaluatable most of the time.
3117  //
3118  // If we ever capture reference-binding directly in the AST, we can
3119  // kill the second parameter.
3120 
3121  if (IsForRef) {
3123  if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3124  return true;
3125  if (Culprit)
3126  *Culprit = this;
3127  return false;
3128  }
3129 
3130  switch (getStmtClass()) {
3131  default: break;
3132  case StringLiteralClass:
3133  case ObjCEncodeExprClass:
3134  return true;
3135  case CXXTemporaryObjectExprClass:
3136  case CXXConstructExprClass: {
3137  const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3138 
3139  if (CE->getConstructor()->isTrivial() &&
3141  // Trivial default constructor
3142  if (!CE->getNumArgs()) return true;
3143 
3144  // Trivial copy constructor
3145  assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3146  return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3147  }
3148 
3149  break;
3150  }
3151  case ConstantExprClass: {
3152  // FIXME: We should be able to return "true" here, but it can lead to extra
3153  // error messages. E.g. in Sema/array-init.c.
3154  const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3155  return Exp->isConstantInitializer(Ctx, false, Culprit);
3156  }
3157  case CompoundLiteralExprClass: {
3158  // This handles gcc's extension that allows global initializers like
3159  // "struct x {int x;} x = (struct x) {};".
3160  // FIXME: This accepts other cases it shouldn't!
3161  const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3162  return Exp->isConstantInitializer(Ctx, false, Culprit);
3163  }
3164  case DesignatedInitUpdateExprClass: {
3165  const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3166  return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3167  DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3168  }
3169  case InitListExprClass: {
3170  const InitListExpr *ILE = cast<InitListExpr>(this);
3171  assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3172  if (ILE->getType()->isArrayType()) {
3173  unsigned numInits = ILE->getNumInits();
3174  for (unsigned i = 0; i < numInits; i++) {
3175  if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3176  return false;
3177  }
3178  return true;
3179  }
3180 
3181  if (ILE->getType()->isRecordType()) {
3182  unsigned ElementNo = 0;
3183  RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
3184  for (const auto *Field : RD->fields()) {
3185  // If this is a union, skip all the fields that aren't being initialized.
3186  if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3187  continue;
3188 
3189  // Don't emit anonymous bitfields, they just affect layout.
3190  if (Field->isUnnamedBitfield())
3191  continue;
3192 
3193  if (ElementNo < ILE->getNumInits()) {
3194  const Expr *Elt = ILE->getInit(ElementNo++);
3195  if (Field->isBitField()) {
3196  // Bitfields have to evaluate to an integer.
3198  if (!Elt->EvaluateAsInt(Result, Ctx)) {
3199  if (Culprit)
3200  *Culprit = Elt;
3201  return false;
3202  }
3203  } else {
3204  bool RefType = Field->getType()->isReferenceType();
3205  if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3206  return false;
3207  }
3208  }
3209  }
3210  return true;
3211  }
3212 
3213  break;
3214  }
3215  case ImplicitValueInitExprClass:
3216  case NoInitExprClass:
3217  return true;
3218  case ParenExprClass:
3219  return cast<ParenExpr>(this)->getSubExpr()
3220  ->isConstantInitializer(Ctx, IsForRef, Culprit);
3221  case GenericSelectionExprClass:
3222  return cast<GenericSelectionExpr>(this)->getResultExpr()
3223  ->isConstantInitializer(Ctx, IsForRef, Culprit);
3224  case ChooseExprClass:
3225  if (cast<ChooseExpr>(this)->isConditionDependent()) {
3226  if (Culprit)
3227  *Culprit = this;
3228  return false;
3229  }
3230  return cast<ChooseExpr>(this)->getChosenSubExpr()
3231  ->isConstantInitializer(Ctx, IsForRef, Culprit);
3232  case UnaryOperatorClass: {
3233  const UnaryOperator* Exp = cast<UnaryOperator>(this);
3234  if (Exp->getOpcode() == UO_Extension)
3235  return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3236  break;
3237  }
3238  case CXXFunctionalCastExprClass:
3239  case CXXStaticCastExprClass:
3240  case ImplicitCastExprClass:
3241  case CStyleCastExprClass:
3242  case ObjCBridgedCastExprClass:
3243  case CXXDynamicCastExprClass:
3244  case CXXReinterpretCastExprClass:
3245  case CXXConstCastExprClass: {
3246  const CastExpr *CE = cast<CastExpr>(this);
3247 
3248  // Handle misc casts we want to ignore.
3249  if (CE->getCastKind() == CK_NoOp ||
3250  CE->getCastKind() == CK_LValueToRValue ||
3251  CE->getCastKind() == CK_ToUnion ||
3252  CE->getCastKind() == CK_ConstructorConversion ||
3253  CE->getCastKind() == CK_NonAtomicToAtomic ||
3254  CE->getCastKind() == CK_AtomicToNonAtomic ||
3255  CE->getCastKind() == CK_IntToOCLSampler)
3256  return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3257 
3258  break;
3259  }
3260  case MaterializeTemporaryExprClass:
3261  return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
3262  ->isConstantInitializer(Ctx, false, Culprit);
3263 
3264  case SubstNonTypeTemplateParmExprClass:
3265  return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3266  ->isConstantInitializer(Ctx, false, Culprit);
3267  case CXXDefaultArgExprClass:
3268  return cast<CXXDefaultArgExpr>(this)->getExpr()
3269  ->isConstantInitializer(Ctx, false, Culprit);
3270  case CXXDefaultInitExprClass:
3271  return cast<CXXDefaultInitExpr>(this)->getExpr()
3272  ->isConstantInitializer(Ctx, false, Culprit);
3273  }
3274  // Allow certain forms of UB in constant initializers: signed integer
3275  // overflow and floating-point division by zero. We'll give a warning on
3276  // these, but they're common enough that we have to accept them.
3278  return true;
3279  if (Culprit)
3280  *Culprit = this;
3281  return false;
3282 }
3283 
3285  const FunctionDecl* FD = getDirectCallee();
3286  if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3287  FD->getBuiltinID() != Builtin::BI__builtin_assume))
3288  return false;
3289 
3290  const Expr* Arg = getArg(0);
3291  bool ArgVal;
3292  return !Arg->isValueDependent() &&
3293  Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3294 }
3295 
3296 namespace {
3297  /// Look for any side effects within a Stmt.
3298  class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3300  const bool IncludePossibleEffects;
3301  bool HasSideEffects;
3302 
3303  public:
3304  explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3305  : Inherited(Context),
3306  IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3307 
3308  bool hasSideEffects() const { return HasSideEffects; }
3309 
3310  void VisitExpr(const Expr *E) {
3311  if (!HasSideEffects &&
3312  E->HasSideEffects(Context, IncludePossibleEffects))
3313  HasSideEffects = true;
3314  }
3315  };
3316 }
3317 
3319  bool IncludePossibleEffects) const {
3320  // In circumstances where we care about definite side effects instead of
3321  // potential side effects, we want to ignore expressions that are part of a
3322  // macro expansion as a potential side effect.
3323  if (!IncludePossibleEffects && getExprLoc().isMacroID())
3324  return false;
3325 
3327  return IncludePossibleEffects;
3328 
3329  switch (getStmtClass()) {
3330  case NoStmtClass:
3331  #define ABSTRACT_STMT(Type)
3332  #define STMT(Type, Base) case Type##Class:
3333  #define EXPR(Type, Base)
3334  #include "clang/AST/StmtNodes.inc"
3335  llvm_unreachable("unexpected Expr kind");
3336 
3337  case DependentScopeDeclRefExprClass:
3338  case CXXUnresolvedConstructExprClass:
3339  case CXXDependentScopeMemberExprClass:
3340  case UnresolvedLookupExprClass:
3341  case UnresolvedMemberExprClass:
3342  case PackExpansionExprClass:
3343  case SubstNonTypeTemplateParmPackExprClass:
3344  case FunctionParmPackExprClass:
3345  case TypoExprClass:
3346  case CXXFoldExprClass:
3347  llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3348 
3349  case DeclRefExprClass:
3350  case ObjCIvarRefExprClass:
3351  case PredefinedExprClass:
3352  case IntegerLiteralClass:
3353  case FixedPointLiteralClass:
3354  case FloatingLiteralClass:
3355  case ImaginaryLiteralClass:
3356  case StringLiteralClass:
3357  case CharacterLiteralClass:
3358  case OffsetOfExprClass:
3359  case ImplicitValueInitExprClass:
3360  case UnaryExprOrTypeTraitExprClass:
3361  case AddrLabelExprClass:
3362  case GNUNullExprClass:
3363  case ArrayInitIndexExprClass:
3364  case NoInitExprClass:
3365  case CXXBoolLiteralExprClass:
3366  case CXXNullPtrLiteralExprClass:
3367  case CXXThisExprClass:
3368  case CXXScalarValueInitExprClass:
3369  case TypeTraitExprClass:
3370  case ArrayTypeTraitExprClass:
3371  case ExpressionTraitExprClass:
3372  case CXXNoexceptExprClass:
3373  case SizeOfPackExprClass:
3374  case ObjCStringLiteralClass:
3375  case ObjCEncodeExprClass:
3376  case ObjCBoolLiteralExprClass:
3377  case ObjCAvailabilityCheckExprClass:
3378  case CXXUuidofExprClass:
3379  case OpaqueValueExprClass:
3380  case SourceLocExprClass:
3381  // These never have a side-effect.
3382  return false;
3383 
3384  case ConstantExprClass:
3385  // FIXME: Move this into the "return false;" block above.
3386  return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3387  Ctx, IncludePossibleEffects);
3388 
3389  case CallExprClass:
3390  case CXXOperatorCallExprClass:
3391  case CXXMemberCallExprClass:
3392  case CUDAKernelCallExprClass:
3393  case UserDefinedLiteralClass: {
3394  // We don't know a call definitely has side effects, except for calls
3395  // to pure/const functions that definitely don't.
3396  // If the call itself is considered side-effect free, check the operands.
3397  const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3398  bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3399  if (IsPure || !IncludePossibleEffects)
3400  break;
3401  return true;
3402  }
3403 
3404  case BlockExprClass:
3405  case CXXBindTemporaryExprClass:
3406  if (!IncludePossibleEffects)
3407  break;
3408  return true;
3409 
3410  case MSPropertyRefExprClass:
3411  case MSPropertySubscriptExprClass:
3412  case CompoundAssignOperatorClass:
3413  case VAArgExprClass:
3414  case AtomicExprClass:
3415  case CXXThrowExprClass:
3416  case CXXNewExprClass:
3417  case CXXDeleteExprClass:
3418  case CoawaitExprClass:
3419  case DependentCoawaitExprClass:
3420  case CoyieldExprClass:
3421  // These always have a side-effect.
3422  return true;
3423 
3424  case StmtExprClass: {
3425  // StmtExprs have a side-effect if any substatement does.
3426  SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3427  Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3428  return Finder.hasSideEffects();
3429  }
3430 
3431  case ExprWithCleanupsClass:
3432  if (IncludePossibleEffects)
3433  if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3434  return true;
3435  break;
3436 
3437  case ParenExprClass:
3438  case ArraySubscriptExprClass:
3439  case OMPArraySectionExprClass:
3440  case MemberExprClass:
3441  case ConditionalOperatorClass:
3442  case BinaryConditionalOperatorClass:
3443  case CompoundLiteralExprClass:
3444  case ExtVectorElementExprClass:
3445  case DesignatedInitExprClass:
3446  case DesignatedInitUpdateExprClass:
3447  case ArrayInitLoopExprClass:
3448  case ParenListExprClass:
3449  case CXXPseudoDestructorExprClass:
3450  case CXXStdInitializerListExprClass:
3451  case SubstNonTypeTemplateParmExprClass:
3452  case MaterializeTemporaryExprClass:
3453  case ShuffleVectorExprClass:
3454  case ConvertVectorExprClass:
3455  case AsTypeExprClass:
3456  // These have a side-effect if any subexpression does.
3457  break;
3458 
3459  case UnaryOperatorClass:
3460  if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3461  return true;
3462  break;
3463 
3464  case BinaryOperatorClass:
3465  if (cast<BinaryOperator>(this)->isAssignmentOp())
3466  return true;
3467  break;
3468 
3469  case InitListExprClass:
3470  // FIXME: The children for an InitListExpr doesn't include the array filler.
3471  if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3472  if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3473  return true;
3474  break;
3475 
3476  case GenericSelectionExprClass:
3477  return cast<GenericSelectionExpr>(this)->getResultExpr()->
3478  HasSideEffects(Ctx, IncludePossibleEffects);
3479 
3480  case ChooseExprClass:
3481  return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3482  Ctx, IncludePossibleEffects);
3483 
3484  case CXXDefaultArgExprClass:
3485  return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3486  Ctx, IncludePossibleEffects);
3487 
3488  case CXXDefaultInitExprClass: {
3489  const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3490  if (const Expr *E = FD->getInClassInitializer())
3491  return E->HasSideEffects(Ctx, IncludePossibleEffects);
3492  // If we've not yet parsed the initializer, assume it has side-effects.
3493  return true;
3494  }
3495 
3496  case CXXDynamicCastExprClass: {
3497  // A dynamic_cast expression has side-effects if it can throw.
3498  const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3499  if (DCE->getTypeAsWritten()->isReferenceType() &&
3500  DCE->getCastKind() == CK_Dynamic)
3501  return true;
3502  }
3503  LLVM_FALLTHROUGH;
3504  case ImplicitCastExprClass:
3505  case CStyleCastExprClass:
3506  case CXXStaticCastExprClass:
3507  case CXXReinterpretCastExprClass:
3508  case CXXConstCastExprClass:
3509  case CXXFunctionalCastExprClass: {
3510  // While volatile reads are side-effecting in both C and C++, we treat them
3511  // as having possible (not definite) side-effects. This allows idiomatic
3512  // code to behave without warning, such as sizeof(*v) for a volatile-
3513  // qualified pointer.
3514  if (!IncludePossibleEffects)
3515  break;
3516 
3517  const CastExpr *CE = cast<CastExpr>(this);
3518  if (CE->getCastKind() == CK_LValueToRValue &&
3520  return true;
3521  break;
3522  }
3523 
3524  case CXXTypeidExprClass:
3525  // typeid might throw if its subexpression is potentially-evaluated, so has
3526  // side-effects in that case whether or not its subexpression does.
3527  return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3528 
3529  case CXXConstructExprClass:
3530  case CXXTemporaryObjectExprClass: {
3531  const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3532  if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3533  return true;
3534  // A trivial constructor does not add any side-effects of its own. Just look
3535  // at its arguments.
3536  break;
3537  }
3538 
3539  case CXXInheritedCtorInitExprClass: {
3540  const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3541  if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3542  return true;
3543  break;
3544  }
3545 
3546  case LambdaExprClass: {
3547  const LambdaExpr *LE = cast<LambdaExpr>(this);
3548  for (Expr *E : LE->capture_inits())
3549  if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3550  return true;
3551  return false;
3552  }
3553 
3554  case PseudoObjectExprClass: {
3555  // Only look for side-effects in the semantic form, and look past
3556  // OpaqueValueExpr bindings in that form.
3557  const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3559  E = PO->semantics_end();
3560  I != E; ++I) {
3561  const Expr *Subexpr = *I;
3562  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3563  Subexpr = OVE->getSourceExpr();
3564  if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3565  return true;
3566  }
3567  return false;
3568  }
3569 
3570  case ObjCBoxedExprClass:
3571  case ObjCArrayLiteralClass:
3572  case ObjCDictionaryLiteralClass:
3573  case ObjCSelectorExprClass:
3574  case ObjCProtocolExprClass:
3575  case ObjCIsaExprClass:
3576  case ObjCIndirectCopyRestoreExprClass:
3577  case ObjCSubscriptRefExprClass:
3578  case ObjCBridgedCastExprClass:
3579  case ObjCMessageExprClass:
3580  case ObjCPropertyRefExprClass:
3581  // FIXME: Classify these cases better.
3582  if (IncludePossibleEffects)
3583  return true;
3584  break;
3585  }
3586 
3587  // Recurse to children.
3588  for (const Stmt *SubStmt : children())
3589  if (SubStmt &&
3590  cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3591  return true;
3592 
3593  return false;
3594 }
3595 
3596 namespace {
3597  /// Look for a call to a non-trivial function within an expression.
3598  class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3599  {
3601 
3602  bool NonTrivial;
3603 
3604  public:
3605  explicit NonTrivialCallFinder(const ASTContext &Context)
3606  : Inherited(Context), NonTrivial(false) { }
3607 
3608  bool hasNonTrivialCall() const { return NonTrivial; }
3609 
3610  void VisitCallExpr(const CallExpr *E) {
3611  if (const CXXMethodDecl *Method
3612  = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3613  if (Method->isTrivial()) {
3614  // Recurse to children of the call.
3615  Inherited::VisitStmt(E);
3616  return;
3617  }
3618  }
3619 
3620  NonTrivial = true;
3621  }
3622 
3623  void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3624  if (E->getConstructor()->isTrivial()) {
3625  // Recurse to children of the call.
3626  Inherited::VisitStmt(E);
3627  return;
3628  }
3629 
3630  NonTrivial = true;
3631  }
3632 
3633  void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3634  if (E->getTemporary()->getDestructor()->isTrivial()) {
3635  Inherited::VisitStmt(E);
3636  return;
3637  }
3638 
3639  NonTrivial = true;
3640  }
3641  };
3642 }
3643 
3644 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3645  NonTrivialCallFinder Finder(Ctx);
3646  Finder.Visit(this);
3647  return Finder.hasNonTrivialCall();
3648 }
3649 
3650 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3651 /// pointer constant or not, as well as the specific kind of constant detected.
3652 /// Null pointer constants can be integer constant expressions with the
3653 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3654 /// (a GNU extension).
3658  if (isValueDependent() &&
3659  (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3660  switch (NPC) {
3662  llvm_unreachable("Unexpected value dependent expression!");
3664  if (isTypeDependent() || getType()->isIntegralType(Ctx))
3665  return NPCK_ZeroExpression;
3666  else
3667  return NPCK_NotNull;
3668 
3670  return NPCK_NotNull;
3671  }
3672  }
3673 
3674  // Strip off a cast to void*, if it exists. Except in C++.
3675  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3676  if (!Ctx.getLangOpts().CPlusPlus) {
3677  // Check that it is a cast to void*.
3678  if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3679  QualType Pointee = PT->getPointeeType();
3680  Qualifiers Qs = Pointee.getQualifiers();
3681  // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3682  // has non-default address space it is not treated as nullptr.
3683  // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3684  // since it cannot be assigned to a pointer to constant address space.
3685  if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
3686  Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3687  (Ctx.getLangOpts().OpenCL &&
3688  Ctx.getLangOpts().OpenCLVersion < 200 &&
3690  Qs.removeAddressSpace();
3691 
3692  if (Pointee->isVoidType() && Qs.empty() && // to void*
3693  CE->getSubExpr()->getType()->isIntegerType()) // from int
3694  return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3695  }
3696  }
3697  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3698  // Ignore the ImplicitCastExpr type entirely.
3699  return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3700  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3701  // Accept ((void*)0) as a null pointer constant, as many other
3702  // implementations do.
3703  return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3704  } else if (const GenericSelectionExpr *GE =
3705  dyn_cast<GenericSelectionExpr>(this)) {
3706  if (GE->isResultDependent())
3707  return NPCK_NotNull;
3708  return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3709  } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3710  if (CE->isConditionDependent())
3711  return NPCK_NotNull;
3712  return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3713  } else if (const CXXDefaultArgExpr *DefaultArg
3714  = dyn_cast<CXXDefaultArgExpr>(this)) {
3715  // See through default argument expressions.
3716  return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3717  } else if (const CXXDefaultInitExpr *DefaultInit
3718  = dyn_cast<CXXDefaultInitExpr>(this)) {
3719  // See through default initializer expressions.
3720  return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3721  } else if (isa<GNUNullExpr>(this)) {
3722  // The GNU __null extension is always a null pointer constant.
3723  return NPCK_GNUNull;
3724  } else if (const MaterializeTemporaryExpr *M
3725  = dyn_cast<MaterializeTemporaryExpr>(this)) {
3726  return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
3727  } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3728  if (const Expr *Source = OVE->getSourceExpr())
3729  return Source->isNullPointerConstant(Ctx, NPC);
3730  }
3731 
3732  // C++11 nullptr_t is always a null pointer constant.
3733  if (getType()->isNullPtrType())
3734  return NPCK_CXX11_nullptr;
3735 
3736  if (const RecordType *UT = getType()->getAsUnionType())
3737  if (!Ctx.getLangOpts().CPlusPlus11 &&
3738  UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3739  if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3740  const Expr *InitExpr = CLE->getInitializer();
3741  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3742  return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3743  }
3744  // This expression must be an integer type.
3745  if (!getType()->isIntegerType() ||
3746  (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3747  return NPCK_NotNull;
3748 
3749  if (Ctx.getLangOpts().CPlusPlus11) {
3750  // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3751  // value zero or a prvalue of type std::nullptr_t.
3752  // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3753  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3754  if (Lit && !Lit->getValue())
3755  return NPCK_ZeroLiteral;
3756  else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3757  return NPCK_NotNull;
3758  } else {
3759  // If we have an integer constant expression, we need to *evaluate* it and
3760  // test for the value 0.
3761  if (!isIntegerConstantExpr(Ctx))
3762  return NPCK_NotNull;
3763  }
3764 
3765  if (EvaluateKnownConstInt(Ctx) != 0)
3766  return NPCK_NotNull;
3767 
3768  if (isa<IntegerLiteral>(this))
3769  return NPCK_ZeroLiteral;
3770  return NPCK_ZeroExpression;
3771 }
3772 
3773 /// If this expression is an l-value for an Objective C
3774 /// property, find the underlying property reference expression.
3776  const Expr *E = this;
3777  while (true) {
3778  assert((E->getValueKind() == VK_LValue &&
3779  E->getObjectKind() == OK_ObjCProperty) &&
3780  "expression is not a property reference");
3781  E = E->IgnoreParenCasts();
3782  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3783  if (BO->getOpcode() == BO_Comma) {
3784  E = BO->getRHS();
3785  continue;
3786  }
3787  }
3788 
3789  break;
3790  }
3791 
3792  return cast<ObjCPropertyRefExpr>(E);
3793 }
3794 
3795 bool Expr::isObjCSelfExpr() const {
3796  const Expr *E = IgnoreParenImpCasts();
3797 
3798  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3799  if (!DRE)
3800  return false;
3801 
3802  const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3803  if (!Param)
3804  return false;
3805 
3806  const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3807  if (!M)
3808  return false;
3809 
3810  return M->getSelfDecl() == Param;
3811 }
3812 
3814  Expr *E = this->IgnoreParens();
3815 
3816  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3817  if (ICE->getCastKind() == CK_LValueToRValue ||
3818  (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
3819  E = ICE->getSubExpr()->IgnoreParens();
3820  else
3821  break;
3822  }
3823 
3824  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3825  if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3826  if (Field->isBitField())
3827  return Field;
3828 
3829  if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3830  FieldDecl *Ivar = IvarRef->getDecl();
3831  if (Ivar->isBitField())
3832  return Ivar;
3833  }
3834 
3835  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3836  if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3837  if (Field->isBitField())
3838  return Field;
3839 
3840  if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3841  if (Expr *E = BD->getBinding())
3842  return E->getSourceBitField();
3843  }
3844 
3845  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3846  if (BinOp->isAssignmentOp() && BinOp->getLHS())
3847  return BinOp->getLHS()->getSourceBitField();
3848 
3849  if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3850  return BinOp->getRHS()->getSourceBitField();
3851  }
3852 
3853  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3854  if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3855  return UnOp->getSubExpr()->getSourceBitField();
3856 
3857  return nullptr;
3858 }
3859 
3861  // FIXME: Why do we not just look at the ObjectKind here?
3862  const Expr *E = this->IgnoreParens();
3863 
3864  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3865  if (ICE->getValueKind() != VK_RValue &&
3866  ICE->getCastKind() == CK_NoOp)
3867  E = ICE->getSubExpr()->IgnoreParens();
3868  else
3869  break;
3870  }
3871 
3872  if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3873  return ASE->getBase()->getType()->isVectorType();
3874 
3875  if (isa<ExtVectorElementExpr>(E))
3876  return true;
3877 
3878  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3879  if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3880  if (auto *E = BD->getBinding())
3881  return E->refersToVectorElement();
3882 
3883  return false;
3884 }
3885 
3887  const Expr *E = this->IgnoreParenImpCasts();
3888 
3889  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3890  if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3891  if (VD->getStorageClass() == SC_Register &&
3892  VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3893  return true;
3894 
3895  return false;
3896 }
3897 
3898 /// isArrow - Return true if the base expression is a pointer to vector,
3899 /// return false if the base expression is a vector.
3901  return getBase()->getType()->isPointerType();
3902 }
3903 
3905  if (const VectorType *VT = getType()->getAs<VectorType>())
3906  return VT->getNumElements();
3907  return 1;
3908 }
3909 
3910 /// containsDuplicateElements - Return true if any element access is repeated.
3912  // FIXME: Refactor this code to an accessor on the AST node which returns the
3913  // "type" of component access, and share with code below and in Sema.
3914  StringRef Comp = Accessor->getName();
3915 
3916  // Halving swizzles do not contain duplicate elements.
3917  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
3918  return false;
3919 
3920  // Advance past s-char prefix on hex swizzles.
3921  if (Comp[0] == 's' || Comp[0] == 'S')
3922  Comp = Comp.substr(1);
3923 
3924  for (unsigned i = 0, e = Comp.size(); i != e; ++i)
3925  if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
3926  return true;
3927 
3928  return false;
3929 }
3930 
3931 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
3933  SmallVectorImpl<uint32_t> &Elts) const {
3934  StringRef Comp = Accessor->getName();
3935  bool isNumericAccessor = false;
3936  if (Comp[0] == 's' || Comp[0] == 'S') {
3937  Comp = Comp.substr(1);
3938  isNumericAccessor = true;
3939  }
3940 
3941  bool isHi = Comp == "hi";
3942  bool isLo = Comp == "lo";
3943  bool isEven = Comp == "even";
3944  bool isOdd = Comp == "odd";
3945 
3946  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3947  uint64_t Index;
3948 
3949  if (isHi)
3950  Index = e + i;
3951  else if (isLo)
3952  Index = i;
3953  else if (isEven)
3954  Index = 2 * i;
3955  else if (isOdd)
3956  Index = 2 * i + 1;
3957  else
3958  Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
3959 
3960  Elts.push_back(Index);
3961  }
3962 }
3963 
3965  QualType Type, SourceLocation BLoc,
3966  SourceLocation RP)
3967  : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3968  Type->isDependentType(), Type->isDependentType(),
3969  Type->isInstantiationDependentType(),
3971  BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3972 {
3973  SubExprs = new (C) Stmt*[args.size()];
3974  for (unsigned i = 0; i != args.size(); i++) {
3975  if (args[i]->isTypeDependent())
3976  ExprBits.TypeDependent = true;
3977  if (args[i]->isValueDependent())
3978  ExprBits.ValueDependent = true;
3979  if (args[i]->isInstantiationDependent())
3980  ExprBits.InstantiationDependent = true;
3982  ExprBits.ContainsUnexpandedParameterPack = true;
3983 
3984  SubExprs[i] = args[i];
3985  }
3986 }
3987 
3989  if (SubExprs) C.Deallocate(SubExprs);
3990 
3991  this->NumExprs = Exprs.size();
3992  SubExprs = new (C) Stmt*[NumExprs];
3993  memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
3994 }
3995 
3996 GenericSelectionExpr::GenericSelectionExpr(
3997  const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
3998  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3999  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4000  bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4001  : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4002  AssocExprs[ResultIndex]->getValueKind(),
4003  AssocExprs[ResultIndex]->getObjectKind(),
4004  AssocExprs[ResultIndex]->isTypeDependent(),
4005  AssocExprs[ResultIndex]->isValueDependent(),
4006  AssocExprs[ResultIndex]->isInstantiationDependent(),
4007  ContainsUnexpandedParameterPack),
4008  NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4009  DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4010  assert(AssocTypes.size() == AssocExprs.size() &&
4011  "Must have the same number of association expressions"
4012  " and TypeSourceInfo!");
4013  assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4014 
4015  GenericSelectionExprBits.GenericLoc = GenericLoc;
4016  getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4017  std::copy(AssocExprs.begin(), AssocExprs.end(),
4018  getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4019  std::copy(AssocTypes.begin(), AssocTypes.end(),
4020  getTrailingObjects<TypeSourceInfo *>());
4021 }
4022 
4023 GenericSelectionExpr::GenericSelectionExpr(
4024  const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4025  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4026  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4027  bool ContainsUnexpandedParameterPack)
4028  : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
4029  OK_Ordinary,
4030  /*isTypeDependent=*/true,
4031  /*isValueDependent=*/true,
4032  /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack),
4033  NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4034  DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4035  assert(AssocTypes.size() == AssocExprs.size() &&
4036  "Must have the same number of association expressions"
4037  " and TypeSourceInfo!");
4038 
4039  GenericSelectionExprBits.GenericLoc = GenericLoc;
4040  getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4041  std::copy(AssocExprs.begin(), AssocExprs.end(),
4042  getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4043  std::copy(AssocTypes.begin(), AssocTypes.end(),
4044  getTrailingObjects<TypeSourceInfo *>());
4045 }
4046 
4047 GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4048  : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4049 
4051  const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4052  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4053  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4054  bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4055  unsigned NumAssocs = AssocExprs.size();
4056  void *Mem = Context.Allocate(
4057  totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4058  alignof(GenericSelectionExpr));
4059  return new (Mem) GenericSelectionExpr(
4060  Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4061  RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4062 }
4063 
4065  const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4066  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4067  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4068  bool ContainsUnexpandedParameterPack) {
4069  unsigned NumAssocs = AssocExprs.size();
4070  void *Mem = Context.Allocate(
4071  totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4072  alignof(GenericSelectionExpr));
4073  return new (Mem) GenericSelectionExpr(
4074  Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4075  RParenLoc, ContainsUnexpandedParameterPack);
4076 }
4077 
4080  unsigned NumAssocs) {
4081  void *Mem = Context.Allocate(
4082  totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4083  alignof(GenericSelectionExpr));
4084  return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4085 }
4086 
4087 //===----------------------------------------------------------------------===//
4088 // DesignatedInitExpr
4089 //===----------------------------------------------------------------------===//
4090 
4092  assert(Kind == FieldDesignator && "Only valid on a field designator");
4093  if (Field.NameOrField & 0x01)
4094  return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
4095  else
4096  return getField()->getIdentifier();
4097 }
4098 
4099 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4100  llvm::ArrayRef<Designator> Designators,
4101  SourceLocation EqualOrColonLoc,
4102  bool GNUSyntax,
4103  ArrayRef<Expr*> IndexExprs,
4104  Expr *Init)
4105  : Expr(DesignatedInitExprClass, Ty,
4106  Init->getValueKind(), Init->getObjectKind(),
4107  Init->isTypeDependent(), Init->isValueDependent(),
4108  Init->isInstantiationDependent(),
4110  EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4111  NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4112  this->Designators = new (C) Designator[NumDesignators];
4113 
4114  // Record the initializer itself.
4115  child_iterator Child = child_begin();
4116  *Child++ = Init;
4117 
4118  // Copy the designators and their subexpressions, computing
4119  // value-dependence along the way.
4120  unsigned IndexIdx = 0;
4121  for (unsigned I = 0; I != NumDesignators; ++I) {
4122  this->Designators[I] = Designators[I];
4123 
4124  if (this->Designators[I].isArrayDesignator()) {
4125  // Compute type- and value-dependence.
4126  Expr *Index = IndexExprs[IndexIdx];
4127  if (Index->isTypeDependent() || Index->isValueDependent())
4128  ExprBits.TypeDependent = ExprBits.ValueDependent = true;
4129  if (Index->isInstantiationDependent())
4130  ExprBits.InstantiationDependent = true;
4131  // Propagate unexpanded parameter packs.
4133  ExprBits.ContainsUnexpandedParameterPack = true;
4134 
4135  // Copy the index expressions into permanent storage.
4136  *Child++ = IndexExprs[IndexIdx++];
4137  } else if (this->Designators[I].isArrayRangeDesignator()) {
4138  // Compute type- and value-dependence.
4139  Expr *Start = IndexExprs[IndexIdx];
4140  Expr *End = IndexExprs[IndexIdx + 1];
4141  if (Start->isTypeDependent() || Start->isValueDependent() ||
4142  End->isTypeDependent() || End->isValueDependent()) {
4143  ExprBits.TypeDependent = ExprBits.ValueDependent = true;
4144  ExprBits.InstantiationDependent = true;
4145  } else if (Start->isInstantiationDependent() ||
4146  End->isInstantiationDependent()) {
4147  ExprBits.InstantiationDependent = true;
4148  }
4149 
4150  // Propagate unexpanded parameter packs.
4151  if (Start->containsUnexpandedParameterPack() ||
4153  ExprBits.ContainsUnexpandedParameterPack = true;
4154 
4155  // Copy the start/end expressions into permanent storage.
4156  *Child++ = IndexExprs[IndexIdx++];
4157  *Child++ = IndexExprs[IndexIdx++];
4158  }
4159  }
4160 
4161  assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4162 }
4163 
4166  llvm::ArrayRef<Designator> Designators,
4167  ArrayRef<Expr*> IndexExprs,
4168  SourceLocation ColonOrEqualLoc,
4169  bool UsesColonSyntax, Expr *Init) {
4170  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4171  alignof(DesignatedInitExpr));
4172  return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4173  ColonOrEqualLoc, UsesColonSyntax,
4174  IndexExprs, Init);
4175 }
4176 
4178  unsigned NumIndexExprs) {
4179  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4180  alignof(DesignatedInitExpr));
4181  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4182 }
4183 
4185  const Designator *Desigs,
4186  unsigned NumDesigs) {
4187  Designators = new (C) Designator[NumDesigs];
4188  NumDesignators = NumDesigs;
4189  for (unsigned I = 0; I != NumDesigs; ++I)
4190  Designators[I] = Desigs[I];
4191 }
4192 
4194  DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4195  if (size() == 1)
4196  return DIE->getDesignator(0)->getSourceRange();
4197  return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4198  DIE->getDesignator(size() - 1)->getEndLoc());
4199 }
4200 
4202  SourceLocation StartLoc;
4203  auto *DIE = const_cast<DesignatedInitExpr *>(this);
4204  Designator &First = *DIE->getDesignator(0);
4205  if (First.isFieldDesignator()) {
4206  if (GNUSyntax)
4208  else
4210  } else
4211  StartLoc =
4213  return StartLoc;
4214 }
4215 
4217  return getInit()->getEndLoc();
4218 }
4219 
4221  assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
4222  return getSubExpr(D.ArrayOrRange.Index + 1);
4223 }
4224 
4226  assert(D.Kind == Designator::ArrayRangeDesignator &&
4227  "Requires array range designator");
4228  return getSubExpr(D.ArrayOrRange.Index + 1);
4229 }
4230 
4232  assert(D.Kind == Designator::ArrayRangeDesignator &&
4233  "Requires array range designator");
4234  return getSubExpr(D.ArrayOrRange.Index + 2);
4235 }
4236 
4237 /// Replaces the designator at index @p Idx with the series
4238 /// of designators in [First, Last).
4240  const Designator *First,
4241  const Designator *Last) {
4242  unsigned NumNewDesignators = Last - First;
4243  if (NumNewDesignators == 0) {
4244  std::copy_backward(Designators + Idx + 1,
4245  Designators + NumDesignators,
4246  Designators + Idx);
4247  --NumNewDesignators;
4248  return;
4249  } else if (NumNewDesignators == 1) {
4250  Designators[Idx] = *First;
4251  return;
4252  }
4253 
4254  Designator *NewDesignators
4255  = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4256  std::copy(Designators, Designators + Idx, NewDesignators);
4257  std::copy(First, Last, NewDesignators + Idx);
4258  std::copy(Designators + Idx + 1, Designators + NumDesignators,
4259  NewDesignators + Idx + NumNewDesignators);
4260  Designators = NewDesignators;
4261  NumDesignators = NumDesignators - 1 + NumNewDesignators;
4262 }
4263 
4265  SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
4266  : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4268  BaseAndUpdaterExprs[0] = baseExpr;
4269 
4270  InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4271  ILE->setType(baseExpr->getType());
4272  BaseAndUpdaterExprs[1] = ILE;
4273 }
4274 
4276  return getBase()->getBeginLoc();
4277 }
4278 
4280  return getBase()->getEndLoc();
4281 }
4282 
4283 ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4284  SourceLocation RParenLoc)
4285  : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4286  false, false),
4287  LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4288  ParenListExprBits.NumExprs = Exprs.size();
4289 
4290  for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4291  if (Exprs[I]->isTypeDependent())
4292  ExprBits.TypeDependent = true;
4293  if (Exprs[I]->isValueDependent())
4294  ExprBits.ValueDependent = true;
4295  if (Exprs[I]->isInstantiationDependent())
4296  ExprBits.InstantiationDependent = true;
4297  if (Exprs[I]->containsUnexpandedParameterPack())
4298  ExprBits.ContainsUnexpandedParameterPack = true;
4299 
4300  getTrailingObjects<Stmt *>()[I] = Exprs[I];
4301  }
4302 }
4303 
4304 ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4305  : Expr(ParenListExprClass, Empty) {
4306  ParenListExprBits.NumExprs = NumExprs;
4307 }
4308 
4310  SourceLocation LParenLoc,
4311  ArrayRef<Expr *> Exprs,
4312  SourceLocation RParenLoc) {
4313  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4314  alignof(ParenListExpr));
4315  return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4316 }
4317 
4319  unsigned NumExprs) {
4320  void *Mem =
4321  Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4322  return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4323 }
4324 
4326  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4327  e = ewc->getSubExpr();
4328  if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4329  e = m->GetTemporaryExpr();
4330  e = cast<CXXConstructExpr>(e)->getArg(0);
4331  while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4332  e = ice->getSubExpr();
4333  return cast<OpaqueValueExpr>(e);
4334 }
4335 
4337  EmptyShell sh,
4338  unsigned numSemanticExprs) {
4339  void *buffer =
4340  Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4341  alignof(PseudoObjectExpr));
4342  return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4343 }
4344 
4345 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4346  : Expr(PseudoObjectExprClass, shell) {
4347  PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4348 }
4349 
4351  ArrayRef<Expr*> semantics,
4352  unsigned resultIndex) {
4353  assert(syntax && "no syntactic expression!");
4354  assert(semantics.size() && "no semantic expressions!");
4355 
4356  QualType type;
4357  ExprValueKind VK;
4358  if (resultIndex == NoResult) {
4359  type = C.VoidTy;
4360  VK = VK_RValue;
4361  } else {
4362  assert(resultIndex < semantics.size());
4363  type = semantics[resultIndex]->getType();
4364  VK = semantics[resultIndex]->getValueKind();
4365  assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4366  }
4367 
4368  void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4369  alignof(PseudoObjectExpr));
4370  return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4371  resultIndex);
4372 }
4373 
4374 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4375  Expr *syntax, ArrayRef<Expr*> semantics,
4376  unsigned resultIndex)
4377  : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4378  /*filled in at end of ctor*/ false, false, false, false) {
4379  PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4380  PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4381 
4382  for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4383  Expr *E = (i == 0 ? syntax : semantics[i-1]);
4384  getSubExprsBuffer()[i] = E;
4385 
4386  if (E->isTypeDependent())
4387  ExprBits.TypeDependent = true;
4388  if (E->isValueDependent())
4389  ExprBits.ValueDependent = true;
4391  ExprBits.InstantiationDependent = true;
4393  ExprBits.ContainsUnexpandedParameterPack = true;
4394 
4395  if (isa<OpaqueValueExpr>(E))
4396  assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
4397  "opaque-value semantic expressions for pseudo-object "
4398  "operations must have sources");
4399  }
4400 }
4401 
4402 //===----------------------------------------------------------------------===//
4403 // Child Iterators for iterating over subexpressions/substatements
4404 //===----------------------------------------------------------------------===//
4405 
4406 // UnaryExprOrTypeTraitExpr
4408  const_child_range CCR =
4409  const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4410  return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4411 }
4412 
4414  // If this is of a type and the type is a VLA type (and not a typedef), the
4415  // size expression of the VLA needs to be treated as an executable expression.
4416  // Why isn't this weirdness documented better in StmtIterator?
4417  if (isArgumentType()) {
4418  if (const VariableArrayType *T =
4419  dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4422  }
4423  return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4424 }
4425 
4428  : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4429  false, false, false, false),
4430  NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4431 {
4432  assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4433  for (unsigned i = 0; i != args.size(); i++) {
4434  if (args[i]->isTypeDependent())
4435  ExprBits.TypeDependent = true;
4436  if (args[i]->isValueDependent())
4437  ExprBits.ValueDependent = true;
4438  if (args[i]->isInstantiationDependent())
4439  ExprBits.InstantiationDependent = true;
4441  ExprBits.ContainsUnexpandedParameterPack = true;
4442 
4443  SubExprs[i] = args[i];
4444  }
4445 }
4446 
4448  switch (Op) {
4449  case AO__c11_atomic_init:
4450  case AO__opencl_atomic_init:
4451  case AO__c11_atomic_load:
4452  case AO__atomic_load_n:
4453  return 2;
4454 
4455  case AO__opencl_atomic_load:
4456  case AO__c11_atomic_store:
4457  case AO__c11_atomic_exchange:
4458  case AO__atomic_load:
4459  case AO__atomic_store:
4460  case AO__atomic_store_n:
4461  case AO__atomic_exchange_n:
4462  case AO__c11_atomic_fetch_add:
4463  case AO__c11_atomic_fetch_sub:
4464  case AO__c11_atomic_fetch_and:
4465  case AO__c11_atomic_fetch_or:
4466  case AO__c11_atomic_fetch_xor:
4467  case AO__atomic_fetch_add:
4468  case AO__atomic_fetch_sub:
4469  case AO__atomic_fetch_and:
4470  case AO__atomic_fetch_or:
4471  case AO__atomic_fetch_xor:
4472  case AO__atomic_fetch_nand:
4473  case AO__atomic_add_fetch:
4474  case AO__atomic_sub_fetch:
4475  case AO__atomic_and_fetch:
4476  case AO__atomic_or_fetch:
4477  case AO__atomic_xor_fetch:
4478  case AO__atomic_nand_fetch:
4479  case AO__atomic_fetch_min:
4480  case AO__atomic_fetch_max:
4481  return 3;
4482 
4483  case AO__opencl_atomic_store:
4484  case AO__opencl_atomic_exchange:
4485  case AO__opencl_atomic_fetch_add:
4486  case AO__opencl_atomic_fetch_sub:
4487  case AO__opencl_atomic_fetch_and:
4488  case AO__opencl_atomic_fetch_or:
4489  case AO__opencl_atomic_fetch_xor:
4490  case AO__opencl_atomic_fetch_min:
4491  case AO__opencl_atomic_fetch_max:
4492  case AO__atomic_exchange:
4493  return 4;
4494 
4495  case AO__c11_atomic_compare_exchange_strong:
4496  case AO__c11_atomic_compare_exchange_weak:
4497  return 5;
4498 
4499  case AO__opencl_atomic_compare_exchange_strong:
4500  case AO__opencl_atomic_compare_exchange_weak:
4501  case AO__atomic_compare_exchange:
4502  case AO__atomic_compare_exchange_n:
4503  return 6;
4504  }
4505  llvm_unreachable("unknown atomic op");
4506 }
4507 
4509  auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4510  if (auto AT = T->getAs<AtomicType>())
4511  return AT->getValueType();
4512  return T;
4513 }
4514 
4516  unsigned ArraySectionCount = 0;
4517  while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4518  Base = OASE->getBase();
4519  ++ArraySectionCount;
4520  }
4521  while (auto *ASE =
4522  dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4523  Base = ASE->getBase();
4524  ++ArraySectionCount;
4525  }
4526  Base = Base->IgnoreParenImpCasts();
4527  auto OriginalTy = Base->getType();
4528  if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4529  if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4530  OriginalTy = PVD->getOriginalType().getNonReferenceType();
4531 
4532  for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4533  if (OriginalTy->isAnyPointerType())
4534  OriginalTy = OriginalTy->getPointeeType();
4535  else {
4536  assert (OriginalTy->isArrayType());
4537  OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4538  }
4539  }
4540  return OriginalTy;
4541 }
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:4475
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:4680
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:2791
static Expr * IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E)
Definition: Expr.cpp:2883
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1256
Represents a function declaration or definition.
Definition: Decl.h:1748
Expr * getArrayIndex(const Designator &D) const
Definition: Expr.cpp:4220
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:6657
StringRef Identifier
Definition: Format.cpp:1716
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
Definition: Expr.h:5707
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:2760
void setArrayFiller(Expr *filler)
Definition: Expr.cpp:2255
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition: Expr.cpp:2351
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2554
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:4201
QualType getPointeeType() const
Definition: Type.h:2567
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:6407
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2673
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:856
unsigned FieldLoc
The location of the field name in the designated initializer.
Definition: Expr.h:4657
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4419
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value...
Definition: Expr.h:4303
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:4264
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2660
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3372
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:3644
bool isRecordType() const
Definition: Type.h:6431
reverse_iterator rbegin()
Definition: ASTVector.h:103
Expr * getBase() const
Definition: Expr.h:2884
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:6597
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:3932
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:2279
Defines the C++ template declaration subclasses.
Opcode getOpcode() const
Definition: Expr.h:3440
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:4521
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:2829
DeclRefExprBitfields DeclRefExprBits
Definition: Stmt.h:962
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1326
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:3368
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:693
A container of type source information.
Definition: Decl.h:86
SourceLocation getLocation() const
Definition: Expr.h:4306
bool containsDuplicateElements() const
containsDuplicateElements - Return true if any element access is repeated.
Definition: Expr.cpp:3911
unsigned getCharWidth() const
Definition: TargetInfo.h:380
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2566
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4320
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:2963
QualType getElementType() const
Definition: Type.h:2864
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:4325
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:3775
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3048
bool isEnumeralType() const
Definition: Type.h:6435
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6818
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type...
Definition: Type.h:6892
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition: Expr.cpp:2239
void setInit(unsigned Init, Expr *expr)
Definition: Expr.h:4429
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:2302
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:3207
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3531
static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind)
Definition: Expr.cpp:232
Defines the clang::Expr interface and subclasses for C++ expressions.
long i
Definition: xmmintrin.h:1456
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:3813
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:1695
Represents a struct/union/class.
Definition: Decl.h:3624
Represents a C99 designated initializer expression.
Definition: Expr.h:4605
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:568
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:920
bool isCharType() const
Definition: Type.cpp:1818
field_range fields() const
Definition: Decl.h:3815
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:2605
static DesignatedInitExpr * Create(const ASTContext &C, llvm::ArrayRef< Designator > Designators, ArrayRef< Expr *> IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition: Expr.cpp:4165
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:96
static Expr * IgnoreLValueCastsSingleStep(Expr *E)
Definition: Expr.cpp:2824
bool isReferenceType() const
Definition: Type.h:6363
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2683
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:3173
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition: Expr.cpp:3900
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:6714
NestedNameSpecifierLoc QualifierLoc
The nested-name-specifier that qualifies the name, including source-location information.
Definition: Expr.h:2798
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:4690
const Expr *const * const_semantics_iterator
Definition: Expr.h:5730
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:3964
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:512
StringRef getOpcodeStr() const
Definition: Expr.h:3461
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:4309
Describes an C or C++ initializer list.
Definition: Expr.h:4371
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:2683
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:4216
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:2808
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:5829
static QualType getDecayedSourceLocExprType(const ASTContext &Ctx, SourceLocExpr::IdentKind Kind)
Definition: Expr.cpp:2128
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:6869
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:5737
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3405
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6197
SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc, SourceLocation RParenLoc, DeclContext *Context)
Definition: Expr.cpp:2143
child_range children()
Definition: Expr.h:4554
bool isBoundMemberFunction(ASTContext &Ctx) const
Returns true if this expression is a bound member function.
Definition: Expr.cpp:2751
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2946
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:2357
IdentKind getIdentKind() const
Definition: Expr.h:4284
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:3121
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1277
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1296
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:1722
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:4082
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:2360
A binding in a decomposition declaration.
Definition: DeclCXX.h:3923
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:1106
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:2925
bool isObjCSelfExpr() const
Check if this expression is the ObjC &#39;self&#39; implicit parameter.
Definition: Expr.cpp:3795
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:1001
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, Expr *LHS, Expr *RHS)
Definition: Expr.cpp:2095
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:3331
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:3703
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:3704
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1398
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:1974
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:2152
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:4957
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:1711
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:3318
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:4184
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:2636
A non-discriminated union of a base, field, or array index.
Definition: APValue.h:151
static Expr * IgnoreExprNodesImpl(Expr *E)
Definition: Expr.cpp:2906
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:2781
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:1742
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6883
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:2907
__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:2830
Expr * getCallee()
Definition: Expr.h:2634
unsigned getNumInits() const
Definition: Expr.h:4401
bool isNullPtrType() const
Definition: Type.h:6635
const Expr * skipRValueSubobjectAdjustments() const
Definition: Expr.h:903
field_iterator field_end() const
Definition: Decl.h:3818
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:4299
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
ArrayRef< Expr * > inits()
Definition: Expr.h:4411
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:2795
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:3013
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:2758
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:2212
Expr * getSubExprAsWritten()
Retrieve the cast subexpression as it was written in the source code, looking through any implicit ca...
Definition: Expr.cpp:1897
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:4664
Represents a GCC generic vector type.
Definition: Type.h:3185
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:4781
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4110
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1081
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:1398
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:3342
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:1570
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:558
RecordDecl * getDecl() const
Definition: Type.h:4433
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:2929
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2032
Expr * IgnoreConversionOperator() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:2950
AtomicExpr(SourceLocation BLoc, ArrayRef< Expr *> args, QualType t, AtomicOp op, SourceLocation RP)
Definition: Expr.cpp:4426
unsigned DotLoc
The location of the &#39;.&#39; in the designated initializer.
Definition: Expr.h:4654
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:349
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:4239
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:4954
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:6166
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5663
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:3656
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:3630
SourceLocation getOperatorLoc() const
Definition: Expr.h:3437
PseudoObjectExprBitfields PseudoObjectExprBits
Definition: Stmt.h:976
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6243
Expression is not a Null pointer constant.
Definition: Expr.h:706
Expr * getSubExpr() const
Definition: Expr.h:2046
CastKind getCastKind() const
Definition: Expr.h:3167
static const FieldDecl * getTargetFieldForToUnionCast(QualType unionType, QualType opType)
Definition: Expr.cpp:1954
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:468
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3095
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:563
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:1856
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:2752
void FixedPointValueToString(SmallVectorImpl< char > &Str, llvm::APSInt Val, unsigned Scale)
Definition: Type.cpp:4124
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