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