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