1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
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 extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 /// Checks that a call expression's argument count is the desired number.
113 /// This is useful when doing custom type-checking.  Returns true on error.
114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115   unsigned argCount = call->getNumArgs();
116   if (argCount == desiredArgCount) return false;
117 
118   if (argCount < desiredArgCount)
119     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120            << 0 /*function call*/ << desiredArgCount << argCount
121            << call->getSourceRange();
122 
123   // Highlight all the excess arguments.
124   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125                     call->getArg(argCount - 1)->getEndLoc());
126 
127   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128     << 0 /*function call*/ << desiredArgCount << argCount
129     << call->getArg(1)->getSourceRange();
130 }
131 
132 /// Check that the first argument to __builtin_annotation is an integer
133 /// and the second argument is a non-wide string literal.
134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135   if (checkArgCount(S, TheCall, 2))
136     return true;
137 
138   // First argument should be an integer.
139   Expr *ValArg = TheCall->getArg(0);
140   QualType Ty = ValArg->getType();
141   if (!Ty->isIntegerType()) {
142     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143         << ValArg->getSourceRange();
144     return true;
145   }
146 
147   // Second argument should be a constant string.
148   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150   if (!Literal || !Literal->isAscii()) {
151     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152         << StrArg->getSourceRange();
153     return true;
154   }
155 
156   TheCall->setType(Ty);
157   return false;
158 }
159 
160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161   // We need at least one argument.
162   if (TheCall->getNumArgs() < 1) {
163     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164         << 0 << 1 << TheCall->getNumArgs()
165         << TheCall->getCallee()->getSourceRange();
166     return true;
167   }
168 
169   // All arguments should be wide string literals.
170   for (Expr *Arg : TheCall->arguments()) {
171     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172     if (!Literal || !Literal->isWide()) {
173       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174           << Arg->getSourceRange();
175       return true;
176     }
177   }
178 
179   return false;
180 }
181 
182 /// Check that the argument to __builtin_addressof is a glvalue, and set the
183 /// result type to the corresponding pointer type.
184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185   if (checkArgCount(S, TheCall, 1))
186     return true;
187 
188   ExprResult Arg(TheCall->getArg(0));
189   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190   if (ResultType.isNull())
191     return true;
192 
193   TheCall->setArg(0, Arg.get());
194   TheCall->setType(ResultType);
195   return false;
196 }
197 
198 /// Check the number of arguments and set the result type to
199 /// the argument type.
200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201   if (checkArgCount(S, TheCall, 1))
202     return true;
203 
204   TheCall->setType(TheCall->getArg(0)->getType());
205   return false;
206 }
207 
208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210 /// type (but not a function pointer) and that the alignment is a power-of-two.
211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212   if (checkArgCount(S, TheCall, 2))
213     return true;
214 
215   clang::Expr *Source = TheCall->getArg(0);
216   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217 
218   auto IsValidIntegerType = [](QualType Ty) {
219     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220   };
221   QualType SrcTy = Source->getType();
222   // We should also be able to use it with arrays (but not functions!).
223   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224     SrcTy = S.Context.getDecayedType(SrcTy);
225   }
226   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227       SrcTy->isFunctionPointerType()) {
228     // FIXME: this is not quite the right error message since we don't allow
229     // floating point types, or member pointers.
230     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231         << SrcTy;
232     return true;
233   }
234 
235   clang::Expr *AlignOp = TheCall->getArg(1);
236   if (!IsValidIntegerType(AlignOp->getType())) {
237     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238         << AlignOp->getType();
239     return true;
240   }
241   Expr::EvalResult AlignResult;
242   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243   // We can't check validity of alignment if it is value dependent.
244   if (!AlignOp->isValueDependent() &&
245       AlignOp->EvaluateAsInt(AlignResult, S.Context,
246                              Expr::SE_AllowSideEffects)) {
247     llvm::APSInt AlignValue = AlignResult.Val.getInt();
248     llvm::APSInt MaxValue(
249         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250     if (AlignValue < 1) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252       return true;
253     }
254     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256           << MaxValue.toString(10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed ExtIntType args larger than 128 bits to mul function until
329   // we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
592 /// __builtin_*_chk function, then use the object size argument specified in the
593 /// source. Otherwise, infer the object size using __builtin_object_size.
594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
595                                                CallExpr *TheCall) {
596   // FIXME: There are some more useful checks we could be doing here:
597   //  - Evaluate strlen of strcpy arguments, use as object size.
598 
599   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
600       isConstantEvaluated())
601     return;
602 
603   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
604   if (!BuiltinID)
605     return;
606 
607   const TargetInfo &TI = getASTContext().getTargetInfo();
608   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
609 
610   unsigned DiagID = 0;
611   bool IsChkVariant = false;
612   Optional<llvm::APSInt> UsedSize;
613   unsigned SizeIndex, ObjectIndex;
614   switch (BuiltinID) {
615   default:
616     return;
617   case Builtin::BIsprintf:
618   case Builtin::BI__builtin___sprintf_chk: {
619     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
620     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
621 
622     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
623 
624       if (!Format->isAscii() && !Format->isUTF8())
625         return;
626 
627       StringRef FormatStrRef = Format->getString();
628       EstimateSizeFormatHandler H(FormatStrRef);
629       const char *FormatBytes = FormatStrRef.data();
630       const ConstantArrayType *T =
631           Context.getAsConstantArrayType(Format->getType());
632       assert(T && "String literal not of constant array type!");
633       size_t TypeSize = T->getSize().getZExtValue();
634 
635       // In case there's a null byte somewhere.
636       size_t StrLen =
637           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
638       if (!analyze_format_string::ParsePrintfString(
639               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
640               Context.getTargetInfo(), false)) {
641         DiagID = diag::warn_fortify_source_format_overflow;
642         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
643                        .extOrTrunc(SizeTypeWidth);
644         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
645           IsChkVariant = true;
646           ObjectIndex = 2;
647         } else {
648           IsChkVariant = false;
649           ObjectIndex = 0;
650         }
651         break;
652       }
653     }
654     return;
655   }
656   case Builtin::BI__builtin___memcpy_chk:
657   case Builtin::BI__builtin___memmove_chk:
658   case Builtin::BI__builtin___memset_chk:
659   case Builtin::BI__builtin___strlcat_chk:
660   case Builtin::BI__builtin___strlcpy_chk:
661   case Builtin::BI__builtin___strncat_chk:
662   case Builtin::BI__builtin___strncpy_chk:
663   case Builtin::BI__builtin___stpncpy_chk:
664   case Builtin::BI__builtin___memccpy_chk:
665   case Builtin::BI__builtin___mempcpy_chk: {
666     DiagID = diag::warn_builtin_chk_overflow;
667     IsChkVariant = true;
668     SizeIndex = TheCall->getNumArgs() - 2;
669     ObjectIndex = TheCall->getNumArgs() - 1;
670     break;
671   }
672 
673   case Builtin::BI__builtin___snprintf_chk:
674   case Builtin::BI__builtin___vsnprintf_chk: {
675     DiagID = diag::warn_builtin_chk_overflow;
676     IsChkVariant = true;
677     SizeIndex = 1;
678     ObjectIndex = 3;
679     break;
680   }
681 
682   case Builtin::BIstrncat:
683   case Builtin::BI__builtin_strncat:
684   case Builtin::BIstrncpy:
685   case Builtin::BI__builtin_strncpy:
686   case Builtin::BIstpncpy:
687   case Builtin::BI__builtin_stpncpy: {
688     // Whether these functions overflow depends on the runtime strlen of the
689     // string, not just the buffer size, so emitting the "always overflow"
690     // diagnostic isn't quite right. We should still diagnose passing a buffer
691     // size larger than the destination buffer though; this is a runtime abort
692     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
693     DiagID = diag::warn_fortify_source_size_mismatch;
694     SizeIndex = TheCall->getNumArgs() - 1;
695     ObjectIndex = 0;
696     break;
697   }
698 
699   case Builtin::BImemcpy:
700   case Builtin::BI__builtin_memcpy:
701   case Builtin::BImemmove:
702   case Builtin::BI__builtin_memmove:
703   case Builtin::BImemset:
704   case Builtin::BI__builtin_memset:
705   case Builtin::BImempcpy:
706   case Builtin::BI__builtin_mempcpy: {
707     DiagID = diag::warn_fortify_source_overflow;
708     SizeIndex = TheCall->getNumArgs() - 1;
709     ObjectIndex = 0;
710     break;
711   }
712   case Builtin::BIsnprintf:
713   case Builtin::BI__builtin_snprintf:
714   case Builtin::BIvsnprintf:
715   case Builtin::BI__builtin_vsnprintf: {
716     DiagID = diag::warn_fortify_source_size_mismatch;
717     SizeIndex = 1;
718     ObjectIndex = 0;
719     break;
720   }
721   }
722 
723   llvm::APSInt ObjectSize;
724   // For __builtin___*_chk, the object size is explicitly provided by the caller
725   // (usually using __builtin_object_size). Use that value to check this call.
726   if (IsChkVariant) {
727     Expr::EvalResult Result;
728     Expr *SizeArg = TheCall->getArg(ObjectIndex);
729     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
730       return;
731     ObjectSize = Result.Val.getInt();
732 
733   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
734   } else {
735     // If the parameter has a pass_object_size attribute, then we should use its
736     // (potentially) more strict checking mode. Otherwise, conservatively assume
737     // type 0.
738     int BOSType = 0;
739     if (const auto *POS =
740             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
741       BOSType = POS->getType();
742 
743     Expr *ObjArg = TheCall->getArg(ObjectIndex);
744     uint64_t Result;
745     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
746       return;
747     // Get the object size in the target's size_t width.
748     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
749   }
750 
751   // Evaluate the number of bytes of the object that this call will use.
752   if (!UsedSize) {
753     Expr::EvalResult Result;
754     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
755     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
756       return;
757     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
758   }
759 
760   if (UsedSize.getValue().ule(ObjectSize))
761     return;
762 
763   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
764   // Skim off the details of whichever builtin was called to produce a better
765   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
766   if (IsChkVariant) {
767     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
768     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
769   } else if (FunctionName.startswith("__builtin_")) {
770     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
771   }
772 
773   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
774                       PDiag(DiagID)
775                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
776                           << UsedSize.getValue().toString(/*Radix=*/10));
777 }
778 
779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
780                                      Scope::ScopeFlags NeededScopeFlags,
781                                      unsigned DiagID) {
782   // Scopes aren't available during instantiation. Fortunately, builtin
783   // functions cannot be template args so they cannot be formed through template
784   // instantiation. Therefore checking once during the parse is sufficient.
785   if (SemaRef.inTemplateInstantiation())
786     return false;
787 
788   Scope *S = SemaRef.getCurScope();
789   while (S && !S->isSEHExceptScope())
790     S = S->getParent();
791   if (!S || !(S->getFlags() & NeededScopeFlags)) {
792     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
793     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
794         << DRE->getDecl()->getIdentifier();
795     return true;
796   }
797 
798   return false;
799 }
800 
801 static inline bool isBlockPointer(Expr *Arg) {
802   return Arg->getType()->isBlockPointerType();
803 }
804 
805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
806 /// void*, which is a requirement of device side enqueue.
807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
808   const BlockPointerType *BPT =
809       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
810   ArrayRef<QualType> Params =
811       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
812   unsigned ArgCounter = 0;
813   bool IllegalParams = false;
814   // Iterate through the block parameters until either one is found that is not
815   // a local void*, or the block is valid.
816   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
817        I != E; ++I, ++ArgCounter) {
818     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
819         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
820             LangAS::opencl_local) {
821       // Get the location of the error. If a block literal has been passed
822       // (BlockExpr) then we can point straight to the offending argument,
823       // else we just point to the variable reference.
824       SourceLocation ErrorLoc;
825       if (isa<BlockExpr>(BlockArg)) {
826         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
827         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
828       } else if (isa<DeclRefExpr>(BlockArg)) {
829         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
830       }
831       S.Diag(ErrorLoc,
832              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
833       IllegalParams = true;
834     }
835   }
836 
837   return IllegalParams;
838 }
839 
840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
841   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_subgroups",
842                                               S.getLangOpts())) {
843     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
844         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
845     return true;
846   }
847   return false;
848 }
849 
850 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
851   if (checkArgCount(S, TheCall, 2))
852     return true;
853 
854   if (checkOpenCLSubgroupExt(S, TheCall))
855     return true;
856 
857   // First argument is an ndrange_t type.
858   Expr *NDRangeArg = TheCall->getArg(0);
859   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
860     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
861         << TheCall->getDirectCallee() << "'ndrange_t'";
862     return true;
863   }
864 
865   Expr *BlockArg = TheCall->getArg(1);
866   if (!isBlockPointer(BlockArg)) {
867     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
868         << TheCall->getDirectCallee() << "block";
869     return true;
870   }
871   return checkOpenCLBlockArgs(S, BlockArg);
872 }
873 
874 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
875 /// get_kernel_work_group_size
876 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
877 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
878   if (checkArgCount(S, TheCall, 1))
879     return true;
880 
881   Expr *BlockArg = TheCall->getArg(0);
882   if (!isBlockPointer(BlockArg)) {
883     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
884         << TheCall->getDirectCallee() << "block";
885     return true;
886   }
887   return checkOpenCLBlockArgs(S, BlockArg);
888 }
889 
890 /// Diagnose integer type and any valid implicit conversion to it.
891 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
892                                       const QualType &IntType);
893 
894 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
895                                             unsigned Start, unsigned End) {
896   bool IllegalParams = false;
897   for (unsigned I = Start; I <= End; ++I)
898     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
899                                               S.Context.getSizeType());
900   return IllegalParams;
901 }
902 
903 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
904 /// 'local void*' parameter of passed block.
905 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
906                                            Expr *BlockArg,
907                                            unsigned NumNonVarArgs) {
908   const BlockPointerType *BPT =
909       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
910   unsigned NumBlockParams =
911       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
912   unsigned TotalNumArgs = TheCall->getNumArgs();
913 
914   // For each argument passed to the block, a corresponding uint needs to
915   // be passed to describe the size of the local memory.
916   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
917     S.Diag(TheCall->getBeginLoc(),
918            diag::err_opencl_enqueue_kernel_local_size_args);
919     return true;
920   }
921 
922   // Check that the sizes of the local memory are specified by integers.
923   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
924                                          TotalNumArgs - 1);
925 }
926 
927 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
928 /// overload formats specified in Table 6.13.17.1.
929 /// int enqueue_kernel(queue_t queue,
930 ///                    kernel_enqueue_flags_t flags,
931 ///                    const ndrange_t ndrange,
932 ///                    void (^block)(void))
933 /// int enqueue_kernel(queue_t queue,
934 ///                    kernel_enqueue_flags_t flags,
935 ///                    const ndrange_t ndrange,
936 ///                    uint num_events_in_wait_list,
937 ///                    clk_event_t *event_wait_list,
938 ///                    clk_event_t *event_ret,
939 ///                    void (^block)(void))
940 /// int enqueue_kernel(queue_t queue,
941 ///                    kernel_enqueue_flags_t flags,
942 ///                    const ndrange_t ndrange,
943 ///                    void (^block)(local void*, ...),
944 ///                    uint size0, ...)
945 /// int enqueue_kernel(queue_t queue,
946 ///                    kernel_enqueue_flags_t flags,
947 ///                    const ndrange_t ndrange,
948 ///                    uint num_events_in_wait_list,
949 ///                    clk_event_t *event_wait_list,
950 ///                    clk_event_t *event_ret,
951 ///                    void (^block)(local void*, ...),
952 ///                    uint size0, ...)
953 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
954   unsigned NumArgs = TheCall->getNumArgs();
955 
956   if (NumArgs < 4) {
957     S.Diag(TheCall->getBeginLoc(),
958            diag::err_typecheck_call_too_few_args_at_least)
959         << 0 << 4 << NumArgs;
960     return true;
961   }
962 
963   Expr *Arg0 = TheCall->getArg(0);
964   Expr *Arg1 = TheCall->getArg(1);
965   Expr *Arg2 = TheCall->getArg(2);
966   Expr *Arg3 = TheCall->getArg(3);
967 
968   // First argument always needs to be a queue_t type.
969   if (!Arg0->getType()->isQueueT()) {
970     S.Diag(TheCall->getArg(0)->getBeginLoc(),
971            diag::err_opencl_builtin_expected_type)
972         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
973     return true;
974   }
975 
976   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
977   if (!Arg1->getType()->isIntegerType()) {
978     S.Diag(TheCall->getArg(1)->getBeginLoc(),
979            diag::err_opencl_builtin_expected_type)
980         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
981     return true;
982   }
983 
984   // Third argument is always an ndrange_t type.
985   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
986     S.Diag(TheCall->getArg(2)->getBeginLoc(),
987            diag::err_opencl_builtin_expected_type)
988         << TheCall->getDirectCallee() << "'ndrange_t'";
989     return true;
990   }
991 
992   // With four arguments, there is only one form that the function could be
993   // called in: no events and no variable arguments.
994   if (NumArgs == 4) {
995     // check that the last argument is the right block type.
996     if (!isBlockPointer(Arg3)) {
997       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
998           << TheCall->getDirectCallee() << "block";
999       return true;
1000     }
1001     // we have a block type, check the prototype
1002     const BlockPointerType *BPT =
1003         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1004     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1005       S.Diag(Arg3->getBeginLoc(),
1006              diag::err_opencl_enqueue_kernel_blocks_no_args);
1007       return true;
1008     }
1009     return false;
1010   }
1011   // we can have block + varargs.
1012   if (isBlockPointer(Arg3))
1013     return (checkOpenCLBlockArgs(S, Arg3) ||
1014             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1015   // last two cases with either exactly 7 args or 7 args and varargs.
1016   if (NumArgs >= 7) {
1017     // check common block argument.
1018     Expr *Arg6 = TheCall->getArg(6);
1019     if (!isBlockPointer(Arg6)) {
1020       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1021           << TheCall->getDirectCallee() << "block";
1022       return true;
1023     }
1024     if (checkOpenCLBlockArgs(S, Arg6))
1025       return true;
1026 
1027     // Forth argument has to be any integer type.
1028     if (!Arg3->getType()->isIntegerType()) {
1029       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1030              diag::err_opencl_builtin_expected_type)
1031           << TheCall->getDirectCallee() << "integer";
1032       return true;
1033     }
1034     // check remaining common arguments.
1035     Expr *Arg4 = TheCall->getArg(4);
1036     Expr *Arg5 = TheCall->getArg(5);
1037 
1038     // Fifth argument is always passed as a pointer to clk_event_t.
1039     if (!Arg4->isNullPointerConstant(S.Context,
1040                                      Expr::NPC_ValueDependentIsNotNull) &&
1041         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1042       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1043              diag::err_opencl_builtin_expected_type)
1044           << TheCall->getDirectCallee()
1045           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1046       return true;
1047     }
1048 
1049     // Sixth argument is always passed as a pointer to clk_event_t.
1050     if (!Arg5->isNullPointerConstant(S.Context,
1051                                      Expr::NPC_ValueDependentIsNotNull) &&
1052         !(Arg5->getType()->isPointerType() &&
1053           Arg5->getType()->getPointeeType()->isClkEventT())) {
1054       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1055              diag::err_opencl_builtin_expected_type)
1056           << TheCall->getDirectCallee()
1057           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1058       return true;
1059     }
1060 
1061     if (NumArgs == 7)
1062       return false;
1063 
1064     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1065   }
1066 
1067   // None of the specific case has been detected, give generic error
1068   S.Diag(TheCall->getBeginLoc(),
1069          diag::err_opencl_enqueue_kernel_incorrect_args);
1070   return true;
1071 }
1072 
1073 /// Returns OpenCL access qual.
1074 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1075     return D->getAttr<OpenCLAccessAttr>();
1076 }
1077 
1078 /// Returns true if pipe element type is different from the pointer.
1079 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1080   const Expr *Arg0 = Call->getArg(0);
1081   // First argument type should always be pipe.
1082   if (!Arg0->getType()->isPipeType()) {
1083     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1084         << Call->getDirectCallee() << Arg0->getSourceRange();
1085     return true;
1086   }
1087   OpenCLAccessAttr *AccessQual =
1088       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1089   // Validates the access qualifier is compatible with the call.
1090   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1091   // read_only and write_only, and assumed to be read_only if no qualifier is
1092   // specified.
1093   switch (Call->getDirectCallee()->getBuiltinID()) {
1094   case Builtin::BIread_pipe:
1095   case Builtin::BIreserve_read_pipe:
1096   case Builtin::BIcommit_read_pipe:
1097   case Builtin::BIwork_group_reserve_read_pipe:
1098   case Builtin::BIsub_group_reserve_read_pipe:
1099   case Builtin::BIwork_group_commit_read_pipe:
1100   case Builtin::BIsub_group_commit_read_pipe:
1101     if (!(!AccessQual || AccessQual->isReadOnly())) {
1102       S.Diag(Arg0->getBeginLoc(),
1103              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1104           << "read_only" << Arg0->getSourceRange();
1105       return true;
1106     }
1107     break;
1108   case Builtin::BIwrite_pipe:
1109   case Builtin::BIreserve_write_pipe:
1110   case Builtin::BIcommit_write_pipe:
1111   case Builtin::BIwork_group_reserve_write_pipe:
1112   case Builtin::BIsub_group_reserve_write_pipe:
1113   case Builtin::BIwork_group_commit_write_pipe:
1114   case Builtin::BIsub_group_commit_write_pipe:
1115     if (!(AccessQual && AccessQual->isWriteOnly())) {
1116       S.Diag(Arg0->getBeginLoc(),
1117              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1118           << "write_only" << Arg0->getSourceRange();
1119       return true;
1120     }
1121     break;
1122   default:
1123     break;
1124   }
1125   return false;
1126 }
1127 
1128 /// Returns true if pipe element type is different from the pointer.
1129 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1130   const Expr *Arg0 = Call->getArg(0);
1131   const Expr *ArgIdx = Call->getArg(Idx);
1132   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1133   const QualType EltTy = PipeTy->getElementType();
1134   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1135   // The Idx argument should be a pointer and the type of the pointer and
1136   // the type of pipe element should also be the same.
1137   if (!ArgTy ||
1138       !S.Context.hasSameType(
1139           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1140     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1141         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1142         << ArgIdx->getType() << ArgIdx->getSourceRange();
1143     return true;
1144   }
1145   return false;
1146 }
1147 
1148 // Performs semantic analysis for the read/write_pipe call.
1149 // \param S Reference to the semantic analyzer.
1150 // \param Call A pointer to the builtin call.
1151 // \return True if a semantic error has been found, false otherwise.
1152 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1153   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1154   // functions have two forms.
1155   switch (Call->getNumArgs()) {
1156   case 2:
1157     if (checkOpenCLPipeArg(S, Call))
1158       return true;
1159     // The call with 2 arguments should be
1160     // read/write_pipe(pipe T, T*).
1161     // Check packet type T.
1162     if (checkOpenCLPipePacketType(S, Call, 1))
1163       return true;
1164     break;
1165 
1166   case 4: {
1167     if (checkOpenCLPipeArg(S, Call))
1168       return true;
1169     // The call with 4 arguments should be
1170     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1171     // Check reserve_id_t.
1172     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1173       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1174           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1175           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1176       return true;
1177     }
1178 
1179     // Check the index.
1180     const Expr *Arg2 = Call->getArg(2);
1181     if (!Arg2->getType()->isIntegerType() &&
1182         !Arg2->getType()->isUnsignedIntegerType()) {
1183       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1184           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1185           << Arg2->getType() << Arg2->getSourceRange();
1186       return true;
1187     }
1188 
1189     // Check packet type T.
1190     if (checkOpenCLPipePacketType(S, Call, 3))
1191       return true;
1192   } break;
1193   default:
1194     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1195         << Call->getDirectCallee() << Call->getSourceRange();
1196     return true;
1197   }
1198 
1199   return false;
1200 }
1201 
1202 // Performs a semantic analysis on the {work_group_/sub_group_
1203 //        /_}reserve_{read/write}_pipe
1204 // \param S Reference to the semantic analyzer.
1205 // \param Call The call to the builtin function to be analyzed.
1206 // \return True if a semantic error was found, false otherwise.
1207 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1208   if (checkArgCount(S, Call, 2))
1209     return true;
1210 
1211   if (checkOpenCLPipeArg(S, Call))
1212     return true;
1213 
1214   // Check the reserve size.
1215   if (!Call->getArg(1)->getType()->isIntegerType() &&
1216       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1217     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1218         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1219         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1220     return true;
1221   }
1222 
1223   // Since return type of reserve_read/write_pipe built-in function is
1224   // reserve_id_t, which is not defined in the builtin def file , we used int
1225   // as return type and need to override the return type of these functions.
1226   Call->setType(S.Context.OCLReserveIDTy);
1227 
1228   return false;
1229 }
1230 
1231 // Performs a semantic analysis on {work_group_/sub_group_
1232 //        /_}commit_{read/write}_pipe
1233 // \param S Reference to the semantic analyzer.
1234 // \param Call The call to the builtin function to be analyzed.
1235 // \return True if a semantic error was found, false otherwise.
1236 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1237   if (checkArgCount(S, Call, 2))
1238     return true;
1239 
1240   if (checkOpenCLPipeArg(S, Call))
1241     return true;
1242 
1243   // Check reserve_id_t.
1244   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1245     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1246         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1247         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1248     return true;
1249   }
1250 
1251   return false;
1252 }
1253 
1254 // Performs a semantic analysis on the call to built-in Pipe
1255 //        Query Functions.
1256 // \param S Reference to the semantic analyzer.
1257 // \param Call The call to the builtin function to be analyzed.
1258 // \return True if a semantic error was found, false otherwise.
1259 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1260   if (checkArgCount(S, Call, 1))
1261     return true;
1262 
1263   if (!Call->getArg(0)->getType()->isPipeType()) {
1264     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1265         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1266     return true;
1267   }
1268 
1269   return false;
1270 }
1271 
1272 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1273 // Performs semantic analysis for the to_global/local/private call.
1274 // \param S Reference to the semantic analyzer.
1275 // \param BuiltinID ID of the builtin function.
1276 // \param Call A pointer to the builtin call.
1277 // \return True if a semantic error has been found, false otherwise.
1278 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1279                                     CallExpr *Call) {
1280   if (checkArgCount(S, Call, 1))
1281     return true;
1282 
1283   auto RT = Call->getArg(0)->getType();
1284   if (!RT->isPointerType() || RT->getPointeeType()
1285       .getAddressSpace() == LangAS::opencl_constant) {
1286     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1287         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1288     return true;
1289   }
1290 
1291   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1292     S.Diag(Call->getArg(0)->getBeginLoc(),
1293            diag::warn_opencl_generic_address_space_arg)
1294         << Call->getDirectCallee()->getNameInfo().getAsString()
1295         << Call->getArg(0)->getSourceRange();
1296   }
1297 
1298   RT = RT->getPointeeType();
1299   auto Qual = RT.getQualifiers();
1300   switch (BuiltinID) {
1301   case Builtin::BIto_global:
1302     Qual.setAddressSpace(LangAS::opencl_global);
1303     break;
1304   case Builtin::BIto_local:
1305     Qual.setAddressSpace(LangAS::opencl_local);
1306     break;
1307   case Builtin::BIto_private:
1308     Qual.setAddressSpace(LangAS::opencl_private);
1309     break;
1310   default:
1311     llvm_unreachable("Invalid builtin function");
1312   }
1313   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1314       RT.getUnqualifiedType(), Qual)));
1315 
1316   return false;
1317 }
1318 
1319 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1320   if (checkArgCount(S, TheCall, 1))
1321     return ExprError();
1322 
1323   // Compute __builtin_launder's parameter type from the argument.
1324   // The parameter type is:
1325   //  * The type of the argument if it's not an array or function type,
1326   //  Otherwise,
1327   //  * The decayed argument type.
1328   QualType ParamTy = [&]() {
1329     QualType ArgTy = TheCall->getArg(0)->getType();
1330     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1331       return S.Context.getPointerType(Ty->getElementType());
1332     if (ArgTy->isFunctionType()) {
1333       return S.Context.getPointerType(ArgTy);
1334     }
1335     return ArgTy;
1336   }();
1337 
1338   TheCall->setType(ParamTy);
1339 
1340   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1341     if (!ParamTy->isPointerType())
1342       return 0;
1343     if (ParamTy->isFunctionPointerType())
1344       return 1;
1345     if (ParamTy->isVoidPointerType())
1346       return 2;
1347     return llvm::Optional<unsigned>{};
1348   }();
1349   if (DiagSelect.hasValue()) {
1350     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1351         << DiagSelect.getValue() << TheCall->getSourceRange();
1352     return ExprError();
1353   }
1354 
1355   // We either have an incomplete class type, or we have a class template
1356   // whose instantiation has not been forced. Example:
1357   //
1358   //   template <class T> struct Foo { T value; };
1359   //   Foo<int> *p = nullptr;
1360   //   auto *d = __builtin_launder(p);
1361   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1362                             diag::err_incomplete_type))
1363     return ExprError();
1364 
1365   assert(ParamTy->getPointeeType()->isObjectType() &&
1366          "Unhandled non-object pointer case");
1367 
1368   InitializedEntity Entity =
1369       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1370   ExprResult Arg =
1371       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1372   if (Arg.isInvalid())
1373     return ExprError();
1374   TheCall->setArg(0, Arg.get());
1375 
1376   return TheCall;
1377 }
1378 
1379 // Emit an error and return true if the current architecture is not in the list
1380 // of supported architectures.
1381 static bool
1382 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1383                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1384   llvm::Triple::ArchType CurArch =
1385       S.getASTContext().getTargetInfo().getTriple().getArch();
1386   if (llvm::is_contained(SupportedArchs, CurArch))
1387     return false;
1388   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1389       << TheCall->getSourceRange();
1390   return true;
1391 }
1392 
1393 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1394                                  SourceLocation CallSiteLoc);
1395 
1396 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1397                                       CallExpr *TheCall) {
1398   switch (TI.getTriple().getArch()) {
1399   default:
1400     // Some builtins don't require additional checking, so just consider these
1401     // acceptable.
1402     return false;
1403   case llvm::Triple::arm:
1404   case llvm::Triple::armeb:
1405   case llvm::Triple::thumb:
1406   case llvm::Triple::thumbeb:
1407     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1408   case llvm::Triple::aarch64:
1409   case llvm::Triple::aarch64_32:
1410   case llvm::Triple::aarch64_be:
1411     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1412   case llvm::Triple::bpfeb:
1413   case llvm::Triple::bpfel:
1414     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1415   case llvm::Triple::hexagon:
1416     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1417   case llvm::Triple::mips:
1418   case llvm::Triple::mipsel:
1419   case llvm::Triple::mips64:
1420   case llvm::Triple::mips64el:
1421     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1422   case llvm::Triple::systemz:
1423     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1424   case llvm::Triple::x86:
1425   case llvm::Triple::x86_64:
1426     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1427   case llvm::Triple::ppc:
1428   case llvm::Triple::ppcle:
1429   case llvm::Triple::ppc64:
1430   case llvm::Triple::ppc64le:
1431     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1432   case llvm::Triple::amdgcn:
1433     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1434   case llvm::Triple::riscv32:
1435   case llvm::Triple::riscv64:
1436     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1437   }
1438 }
1439 
1440 ExprResult
1441 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1442                                CallExpr *TheCall) {
1443   ExprResult TheCallResult(TheCall);
1444 
1445   // Find out if any arguments are required to be integer constant expressions.
1446   unsigned ICEArguments = 0;
1447   ASTContext::GetBuiltinTypeError Error;
1448   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1449   if (Error != ASTContext::GE_None)
1450     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1451 
1452   // If any arguments are required to be ICE's, check and diagnose.
1453   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1454     // Skip arguments not required to be ICE's.
1455     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1456 
1457     llvm::APSInt Result;
1458     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1459       return true;
1460     ICEArguments &= ~(1 << ArgNo);
1461   }
1462 
1463   switch (BuiltinID) {
1464   case Builtin::BI__builtin___CFStringMakeConstantString:
1465     assert(TheCall->getNumArgs() == 1 &&
1466            "Wrong # arguments to builtin CFStringMakeConstantString");
1467     if (CheckObjCString(TheCall->getArg(0)))
1468       return ExprError();
1469     break;
1470   case Builtin::BI__builtin_ms_va_start:
1471   case Builtin::BI__builtin_stdarg_start:
1472   case Builtin::BI__builtin_va_start:
1473     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1474       return ExprError();
1475     break;
1476   case Builtin::BI__va_start: {
1477     switch (Context.getTargetInfo().getTriple().getArch()) {
1478     case llvm::Triple::aarch64:
1479     case llvm::Triple::arm:
1480     case llvm::Triple::thumb:
1481       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1482         return ExprError();
1483       break;
1484     default:
1485       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1486         return ExprError();
1487       break;
1488     }
1489     break;
1490   }
1491 
1492   // The acquire, release, and no fence variants are ARM and AArch64 only.
1493   case Builtin::BI_interlockedbittestandset_acq:
1494   case Builtin::BI_interlockedbittestandset_rel:
1495   case Builtin::BI_interlockedbittestandset_nf:
1496   case Builtin::BI_interlockedbittestandreset_acq:
1497   case Builtin::BI_interlockedbittestandreset_rel:
1498   case Builtin::BI_interlockedbittestandreset_nf:
1499     if (CheckBuiltinTargetSupport(
1500             *this, BuiltinID, TheCall,
1501             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1502       return ExprError();
1503     break;
1504 
1505   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1506   case Builtin::BI_bittest64:
1507   case Builtin::BI_bittestandcomplement64:
1508   case Builtin::BI_bittestandreset64:
1509   case Builtin::BI_bittestandset64:
1510   case Builtin::BI_interlockedbittestandreset64:
1511   case Builtin::BI_interlockedbittestandset64:
1512     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1513                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1514                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1515       return ExprError();
1516     break;
1517 
1518   case Builtin::BI__builtin_isgreater:
1519   case Builtin::BI__builtin_isgreaterequal:
1520   case Builtin::BI__builtin_isless:
1521   case Builtin::BI__builtin_islessequal:
1522   case Builtin::BI__builtin_islessgreater:
1523   case Builtin::BI__builtin_isunordered:
1524     if (SemaBuiltinUnorderedCompare(TheCall))
1525       return ExprError();
1526     break;
1527   case Builtin::BI__builtin_fpclassify:
1528     if (SemaBuiltinFPClassification(TheCall, 6))
1529       return ExprError();
1530     break;
1531   case Builtin::BI__builtin_isfinite:
1532   case Builtin::BI__builtin_isinf:
1533   case Builtin::BI__builtin_isinf_sign:
1534   case Builtin::BI__builtin_isnan:
1535   case Builtin::BI__builtin_isnormal:
1536   case Builtin::BI__builtin_signbit:
1537   case Builtin::BI__builtin_signbitf:
1538   case Builtin::BI__builtin_signbitl:
1539     if (SemaBuiltinFPClassification(TheCall, 1))
1540       return ExprError();
1541     break;
1542   case Builtin::BI__builtin_shufflevector:
1543     return SemaBuiltinShuffleVector(TheCall);
1544     // TheCall will be freed by the smart pointer here, but that's fine, since
1545     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1546   case Builtin::BI__builtin_prefetch:
1547     if (SemaBuiltinPrefetch(TheCall))
1548       return ExprError();
1549     break;
1550   case Builtin::BI__builtin_alloca_with_align:
1551     if (SemaBuiltinAllocaWithAlign(TheCall))
1552       return ExprError();
1553     LLVM_FALLTHROUGH;
1554   case Builtin::BI__builtin_alloca:
1555     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1556         << TheCall->getDirectCallee();
1557     break;
1558   case Builtin::BI__assume:
1559   case Builtin::BI__builtin_assume:
1560     if (SemaBuiltinAssume(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_assume_aligned:
1564     if (SemaBuiltinAssumeAligned(TheCall))
1565       return ExprError();
1566     break;
1567   case Builtin::BI__builtin_dynamic_object_size:
1568   case Builtin::BI__builtin_object_size:
1569     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1570       return ExprError();
1571     break;
1572   case Builtin::BI__builtin_longjmp:
1573     if (SemaBuiltinLongjmp(TheCall))
1574       return ExprError();
1575     break;
1576   case Builtin::BI__builtin_setjmp:
1577     if (SemaBuiltinSetjmp(TheCall))
1578       return ExprError();
1579     break;
1580   case Builtin::BI__builtin_classify_type:
1581     if (checkArgCount(*this, TheCall, 1)) return true;
1582     TheCall->setType(Context.IntTy);
1583     break;
1584   case Builtin::BI__builtin_complex:
1585     if (SemaBuiltinComplex(TheCall))
1586       return ExprError();
1587     break;
1588   case Builtin::BI__builtin_constant_p: {
1589     if (checkArgCount(*this, TheCall, 1)) return true;
1590     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1591     if (Arg.isInvalid()) return true;
1592     TheCall->setArg(0, Arg.get());
1593     TheCall->setType(Context.IntTy);
1594     break;
1595   }
1596   case Builtin::BI__builtin_launder:
1597     return SemaBuiltinLaunder(*this, TheCall);
1598   case Builtin::BI__sync_fetch_and_add:
1599   case Builtin::BI__sync_fetch_and_add_1:
1600   case Builtin::BI__sync_fetch_and_add_2:
1601   case Builtin::BI__sync_fetch_and_add_4:
1602   case Builtin::BI__sync_fetch_and_add_8:
1603   case Builtin::BI__sync_fetch_and_add_16:
1604   case Builtin::BI__sync_fetch_and_sub:
1605   case Builtin::BI__sync_fetch_and_sub_1:
1606   case Builtin::BI__sync_fetch_and_sub_2:
1607   case Builtin::BI__sync_fetch_and_sub_4:
1608   case Builtin::BI__sync_fetch_and_sub_8:
1609   case Builtin::BI__sync_fetch_and_sub_16:
1610   case Builtin::BI__sync_fetch_and_or:
1611   case Builtin::BI__sync_fetch_and_or_1:
1612   case Builtin::BI__sync_fetch_and_or_2:
1613   case Builtin::BI__sync_fetch_and_or_4:
1614   case Builtin::BI__sync_fetch_and_or_8:
1615   case Builtin::BI__sync_fetch_and_or_16:
1616   case Builtin::BI__sync_fetch_and_and:
1617   case Builtin::BI__sync_fetch_and_and_1:
1618   case Builtin::BI__sync_fetch_and_and_2:
1619   case Builtin::BI__sync_fetch_and_and_4:
1620   case Builtin::BI__sync_fetch_and_and_8:
1621   case Builtin::BI__sync_fetch_and_and_16:
1622   case Builtin::BI__sync_fetch_and_xor:
1623   case Builtin::BI__sync_fetch_and_xor_1:
1624   case Builtin::BI__sync_fetch_and_xor_2:
1625   case Builtin::BI__sync_fetch_and_xor_4:
1626   case Builtin::BI__sync_fetch_and_xor_8:
1627   case Builtin::BI__sync_fetch_and_xor_16:
1628   case Builtin::BI__sync_fetch_and_nand:
1629   case Builtin::BI__sync_fetch_and_nand_1:
1630   case Builtin::BI__sync_fetch_and_nand_2:
1631   case Builtin::BI__sync_fetch_and_nand_4:
1632   case Builtin::BI__sync_fetch_and_nand_8:
1633   case Builtin::BI__sync_fetch_and_nand_16:
1634   case Builtin::BI__sync_add_and_fetch:
1635   case Builtin::BI__sync_add_and_fetch_1:
1636   case Builtin::BI__sync_add_and_fetch_2:
1637   case Builtin::BI__sync_add_and_fetch_4:
1638   case Builtin::BI__sync_add_and_fetch_8:
1639   case Builtin::BI__sync_add_and_fetch_16:
1640   case Builtin::BI__sync_sub_and_fetch:
1641   case Builtin::BI__sync_sub_and_fetch_1:
1642   case Builtin::BI__sync_sub_and_fetch_2:
1643   case Builtin::BI__sync_sub_and_fetch_4:
1644   case Builtin::BI__sync_sub_and_fetch_8:
1645   case Builtin::BI__sync_sub_and_fetch_16:
1646   case Builtin::BI__sync_and_and_fetch:
1647   case Builtin::BI__sync_and_and_fetch_1:
1648   case Builtin::BI__sync_and_and_fetch_2:
1649   case Builtin::BI__sync_and_and_fetch_4:
1650   case Builtin::BI__sync_and_and_fetch_8:
1651   case Builtin::BI__sync_and_and_fetch_16:
1652   case Builtin::BI__sync_or_and_fetch:
1653   case Builtin::BI__sync_or_and_fetch_1:
1654   case Builtin::BI__sync_or_and_fetch_2:
1655   case Builtin::BI__sync_or_and_fetch_4:
1656   case Builtin::BI__sync_or_and_fetch_8:
1657   case Builtin::BI__sync_or_and_fetch_16:
1658   case Builtin::BI__sync_xor_and_fetch:
1659   case Builtin::BI__sync_xor_and_fetch_1:
1660   case Builtin::BI__sync_xor_and_fetch_2:
1661   case Builtin::BI__sync_xor_and_fetch_4:
1662   case Builtin::BI__sync_xor_and_fetch_8:
1663   case Builtin::BI__sync_xor_and_fetch_16:
1664   case Builtin::BI__sync_nand_and_fetch:
1665   case Builtin::BI__sync_nand_and_fetch_1:
1666   case Builtin::BI__sync_nand_and_fetch_2:
1667   case Builtin::BI__sync_nand_and_fetch_4:
1668   case Builtin::BI__sync_nand_and_fetch_8:
1669   case Builtin::BI__sync_nand_and_fetch_16:
1670   case Builtin::BI__sync_val_compare_and_swap:
1671   case Builtin::BI__sync_val_compare_and_swap_1:
1672   case Builtin::BI__sync_val_compare_and_swap_2:
1673   case Builtin::BI__sync_val_compare_and_swap_4:
1674   case Builtin::BI__sync_val_compare_and_swap_8:
1675   case Builtin::BI__sync_val_compare_and_swap_16:
1676   case Builtin::BI__sync_bool_compare_and_swap:
1677   case Builtin::BI__sync_bool_compare_and_swap_1:
1678   case Builtin::BI__sync_bool_compare_and_swap_2:
1679   case Builtin::BI__sync_bool_compare_and_swap_4:
1680   case Builtin::BI__sync_bool_compare_and_swap_8:
1681   case Builtin::BI__sync_bool_compare_and_swap_16:
1682   case Builtin::BI__sync_lock_test_and_set:
1683   case Builtin::BI__sync_lock_test_and_set_1:
1684   case Builtin::BI__sync_lock_test_and_set_2:
1685   case Builtin::BI__sync_lock_test_and_set_4:
1686   case Builtin::BI__sync_lock_test_and_set_8:
1687   case Builtin::BI__sync_lock_test_and_set_16:
1688   case Builtin::BI__sync_lock_release:
1689   case Builtin::BI__sync_lock_release_1:
1690   case Builtin::BI__sync_lock_release_2:
1691   case Builtin::BI__sync_lock_release_4:
1692   case Builtin::BI__sync_lock_release_8:
1693   case Builtin::BI__sync_lock_release_16:
1694   case Builtin::BI__sync_swap:
1695   case Builtin::BI__sync_swap_1:
1696   case Builtin::BI__sync_swap_2:
1697   case Builtin::BI__sync_swap_4:
1698   case Builtin::BI__sync_swap_8:
1699   case Builtin::BI__sync_swap_16:
1700     return SemaBuiltinAtomicOverloaded(TheCallResult);
1701   case Builtin::BI__sync_synchronize:
1702     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1703         << TheCall->getCallee()->getSourceRange();
1704     break;
1705   case Builtin::BI__builtin_nontemporal_load:
1706   case Builtin::BI__builtin_nontemporal_store:
1707     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1708   case Builtin::BI__builtin_memcpy_inline: {
1709     clang::Expr *SizeOp = TheCall->getArg(2);
1710     // We warn about copying to or from `nullptr` pointers when `size` is
1711     // greater than 0. When `size` is value dependent we cannot evaluate its
1712     // value so we bail out.
1713     if (SizeOp->isValueDependent())
1714       break;
1715     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1716       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1717       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1718     }
1719     break;
1720   }
1721 #define BUILTIN(ID, TYPE, ATTRS)
1722 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1723   case Builtin::BI##ID: \
1724     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1725 #include "clang/Basic/Builtins.def"
1726   case Builtin::BI__annotation:
1727     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1728       return ExprError();
1729     break;
1730   case Builtin::BI__builtin_annotation:
1731     if (SemaBuiltinAnnotation(*this, TheCall))
1732       return ExprError();
1733     break;
1734   case Builtin::BI__builtin_addressof:
1735     if (SemaBuiltinAddressof(*this, TheCall))
1736       return ExprError();
1737     break;
1738   case Builtin::BI__builtin_is_aligned:
1739   case Builtin::BI__builtin_align_up:
1740   case Builtin::BI__builtin_align_down:
1741     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1742       return ExprError();
1743     break;
1744   case Builtin::BI__builtin_add_overflow:
1745   case Builtin::BI__builtin_sub_overflow:
1746   case Builtin::BI__builtin_mul_overflow:
1747     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1748       return ExprError();
1749     break;
1750   case Builtin::BI__builtin_operator_new:
1751   case Builtin::BI__builtin_operator_delete: {
1752     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1753     ExprResult Res =
1754         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1755     if (Res.isInvalid())
1756       CorrectDelayedTyposInExpr(TheCallResult.get());
1757     return Res;
1758   }
1759   case Builtin::BI__builtin_dump_struct: {
1760     // We first want to ensure we are called with 2 arguments
1761     if (checkArgCount(*this, TheCall, 2))
1762       return ExprError();
1763     // Ensure that the first argument is of type 'struct XX *'
1764     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1765     const QualType PtrArgType = PtrArg->getType();
1766     if (!PtrArgType->isPointerType() ||
1767         !PtrArgType->getPointeeType()->isRecordType()) {
1768       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1769           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1770           << "structure pointer";
1771       return ExprError();
1772     }
1773 
1774     // Ensure that the second argument is of type 'FunctionType'
1775     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1776     const QualType FnPtrArgType = FnPtrArg->getType();
1777     if (!FnPtrArgType->isPointerType()) {
1778       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1779           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1780           << FnPtrArgType << "'int (*)(const char *, ...)'";
1781       return ExprError();
1782     }
1783 
1784     const auto *FuncType =
1785         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1786 
1787     if (!FuncType) {
1788       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1789           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1790           << FnPtrArgType << "'int (*)(const char *, ...)'";
1791       return ExprError();
1792     }
1793 
1794     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1795       if (!FT->getNumParams()) {
1796         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1797             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1798             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1799         return ExprError();
1800       }
1801       QualType PT = FT->getParamType(0);
1802       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1803           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1804           !PT->getPointeeType().isConstQualified()) {
1805         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1806             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1807             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1808         return ExprError();
1809       }
1810     }
1811 
1812     TheCall->setType(Context.IntTy);
1813     break;
1814   }
1815   case Builtin::BI__builtin_expect_with_probability: {
1816     // We first want to ensure we are called with 3 arguments
1817     if (checkArgCount(*this, TheCall, 3))
1818       return ExprError();
1819     // then check probability is constant float in range [0.0, 1.0]
1820     const Expr *ProbArg = TheCall->getArg(2);
1821     SmallVector<PartialDiagnosticAt, 8> Notes;
1822     Expr::EvalResult Eval;
1823     Eval.Diag = &Notes;
1824     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1825         !Eval.Val.isFloat()) {
1826       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1827           << ProbArg->getSourceRange();
1828       for (const PartialDiagnosticAt &PDiag : Notes)
1829         Diag(PDiag.first, PDiag.second);
1830       return ExprError();
1831     }
1832     llvm::APFloat Probability = Eval.Val.getFloat();
1833     bool LoseInfo = false;
1834     Probability.convert(llvm::APFloat::IEEEdouble(),
1835                         llvm::RoundingMode::Dynamic, &LoseInfo);
1836     if (!(Probability >= llvm::APFloat(0.0) &&
1837           Probability <= llvm::APFloat(1.0))) {
1838       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1839           << ProbArg->getSourceRange();
1840       return ExprError();
1841     }
1842     break;
1843   }
1844   case Builtin::BI__builtin_preserve_access_index:
1845     if (SemaBuiltinPreserveAI(*this, TheCall))
1846       return ExprError();
1847     break;
1848   case Builtin::BI__builtin_call_with_static_chain:
1849     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1850       return ExprError();
1851     break;
1852   case Builtin::BI__exception_code:
1853   case Builtin::BI_exception_code:
1854     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1855                                  diag::err_seh___except_block))
1856       return ExprError();
1857     break;
1858   case Builtin::BI__exception_info:
1859   case Builtin::BI_exception_info:
1860     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1861                                  diag::err_seh___except_filter))
1862       return ExprError();
1863     break;
1864   case Builtin::BI__GetExceptionInfo:
1865     if (checkArgCount(*this, TheCall, 1))
1866       return ExprError();
1867 
1868     if (CheckCXXThrowOperand(
1869             TheCall->getBeginLoc(),
1870             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1871             TheCall))
1872       return ExprError();
1873 
1874     TheCall->setType(Context.VoidPtrTy);
1875     break;
1876   // OpenCL v2.0, s6.13.16 - Pipe functions
1877   case Builtin::BIread_pipe:
1878   case Builtin::BIwrite_pipe:
1879     // Since those two functions are declared with var args, we need a semantic
1880     // check for the argument.
1881     if (SemaBuiltinRWPipe(*this, TheCall))
1882       return ExprError();
1883     break;
1884   case Builtin::BIreserve_read_pipe:
1885   case Builtin::BIreserve_write_pipe:
1886   case Builtin::BIwork_group_reserve_read_pipe:
1887   case Builtin::BIwork_group_reserve_write_pipe:
1888     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1889       return ExprError();
1890     break;
1891   case Builtin::BIsub_group_reserve_read_pipe:
1892   case Builtin::BIsub_group_reserve_write_pipe:
1893     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1894         SemaBuiltinReserveRWPipe(*this, TheCall))
1895       return ExprError();
1896     break;
1897   case Builtin::BIcommit_read_pipe:
1898   case Builtin::BIcommit_write_pipe:
1899   case Builtin::BIwork_group_commit_read_pipe:
1900   case Builtin::BIwork_group_commit_write_pipe:
1901     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1902       return ExprError();
1903     break;
1904   case Builtin::BIsub_group_commit_read_pipe:
1905   case Builtin::BIsub_group_commit_write_pipe:
1906     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1907         SemaBuiltinCommitRWPipe(*this, TheCall))
1908       return ExprError();
1909     break;
1910   case Builtin::BIget_pipe_num_packets:
1911   case Builtin::BIget_pipe_max_packets:
1912     if (SemaBuiltinPipePackets(*this, TheCall))
1913       return ExprError();
1914     break;
1915   case Builtin::BIto_global:
1916   case Builtin::BIto_local:
1917   case Builtin::BIto_private:
1918     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1919       return ExprError();
1920     break;
1921   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1922   case Builtin::BIenqueue_kernel:
1923     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1924       return ExprError();
1925     break;
1926   case Builtin::BIget_kernel_work_group_size:
1927   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1928     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1929       return ExprError();
1930     break;
1931   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1932   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1933     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1934       return ExprError();
1935     break;
1936   case Builtin::BI__builtin_os_log_format:
1937     Cleanup.setExprNeedsCleanups(true);
1938     LLVM_FALLTHROUGH;
1939   case Builtin::BI__builtin_os_log_format_buffer_size:
1940     if (SemaBuiltinOSLogFormat(TheCall))
1941       return ExprError();
1942     break;
1943   case Builtin::BI__builtin_frame_address:
1944   case Builtin::BI__builtin_return_address: {
1945     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1946       return ExprError();
1947 
1948     // -Wframe-address warning if non-zero passed to builtin
1949     // return/frame address.
1950     Expr::EvalResult Result;
1951     if (!TheCall->getArg(0)->isValueDependent() &&
1952         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1953         Result.Val.getInt() != 0)
1954       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1955           << ((BuiltinID == Builtin::BI__builtin_return_address)
1956                   ? "__builtin_return_address"
1957                   : "__builtin_frame_address")
1958           << TheCall->getSourceRange();
1959     break;
1960   }
1961 
1962   case Builtin::BI__builtin_matrix_transpose:
1963     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1964 
1965   case Builtin::BI__builtin_matrix_column_major_load:
1966     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1967 
1968   case Builtin::BI__builtin_matrix_column_major_store:
1969     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1970 
1971   case Builtin::BI__builtin_get_device_side_mangled_name: {
1972     auto Check = [](CallExpr *TheCall) {
1973       if (TheCall->getNumArgs() != 1)
1974         return false;
1975       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1976       if (!DRE)
1977         return false;
1978       auto *D = DRE->getDecl();
1979       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1980         return false;
1981       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1982              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1983     };
1984     if (!Check(TheCall)) {
1985       Diag(TheCall->getBeginLoc(),
1986            diag::err_hip_invalid_args_builtin_mangled_name);
1987       return ExprError();
1988     }
1989   }
1990   }
1991 
1992   // Since the target specific builtins for each arch overlap, only check those
1993   // of the arch we are compiling for.
1994   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1995     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1996       assert(Context.getAuxTargetInfo() &&
1997              "Aux Target Builtin, but not an aux target?");
1998 
1999       if (CheckTSBuiltinFunctionCall(
2000               *Context.getAuxTargetInfo(),
2001               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2002         return ExprError();
2003     } else {
2004       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2005                                      TheCall))
2006         return ExprError();
2007     }
2008   }
2009 
2010   return TheCallResult;
2011 }
2012 
2013 // Get the valid immediate range for the specified NEON type code.
2014 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2015   NeonTypeFlags Type(t);
2016   int IsQuad = ForceQuad ? true : Type.isQuad();
2017   switch (Type.getEltType()) {
2018   case NeonTypeFlags::Int8:
2019   case NeonTypeFlags::Poly8:
2020     return shift ? 7 : (8 << IsQuad) - 1;
2021   case NeonTypeFlags::Int16:
2022   case NeonTypeFlags::Poly16:
2023     return shift ? 15 : (4 << IsQuad) - 1;
2024   case NeonTypeFlags::Int32:
2025     return shift ? 31 : (2 << IsQuad) - 1;
2026   case NeonTypeFlags::Int64:
2027   case NeonTypeFlags::Poly64:
2028     return shift ? 63 : (1 << IsQuad) - 1;
2029   case NeonTypeFlags::Poly128:
2030     return shift ? 127 : (1 << IsQuad) - 1;
2031   case NeonTypeFlags::Float16:
2032     assert(!shift && "cannot shift float types!");
2033     return (4 << IsQuad) - 1;
2034   case NeonTypeFlags::Float32:
2035     assert(!shift && "cannot shift float types!");
2036     return (2 << IsQuad) - 1;
2037   case NeonTypeFlags::Float64:
2038     assert(!shift && "cannot shift float types!");
2039     return (1 << IsQuad) - 1;
2040   case NeonTypeFlags::BFloat16:
2041     assert(!shift && "cannot shift float types!");
2042     return (4 << IsQuad) - 1;
2043   }
2044   llvm_unreachable("Invalid NeonTypeFlag!");
2045 }
2046 
2047 /// getNeonEltType - Return the QualType corresponding to the elements of
2048 /// the vector type specified by the NeonTypeFlags.  This is used to check
2049 /// the pointer arguments for Neon load/store intrinsics.
2050 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2051                                bool IsPolyUnsigned, bool IsInt64Long) {
2052   switch (Flags.getEltType()) {
2053   case NeonTypeFlags::Int8:
2054     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2055   case NeonTypeFlags::Int16:
2056     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2057   case NeonTypeFlags::Int32:
2058     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2059   case NeonTypeFlags::Int64:
2060     if (IsInt64Long)
2061       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2062     else
2063       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2064                                 : Context.LongLongTy;
2065   case NeonTypeFlags::Poly8:
2066     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2067   case NeonTypeFlags::Poly16:
2068     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2069   case NeonTypeFlags::Poly64:
2070     if (IsInt64Long)
2071       return Context.UnsignedLongTy;
2072     else
2073       return Context.UnsignedLongLongTy;
2074   case NeonTypeFlags::Poly128:
2075     break;
2076   case NeonTypeFlags::Float16:
2077     return Context.HalfTy;
2078   case NeonTypeFlags::Float32:
2079     return Context.FloatTy;
2080   case NeonTypeFlags::Float64:
2081     return Context.DoubleTy;
2082   case NeonTypeFlags::BFloat16:
2083     return Context.BFloat16Ty;
2084   }
2085   llvm_unreachable("Invalid NeonTypeFlag!");
2086 }
2087 
2088 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2089   // Range check SVE intrinsics that take immediate values.
2090   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2091 
2092   switch (BuiltinID) {
2093   default:
2094     return false;
2095 #define GET_SVE_IMMEDIATE_CHECK
2096 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2097 #undef GET_SVE_IMMEDIATE_CHECK
2098   }
2099 
2100   // Perform all the immediate checks for this builtin call.
2101   bool HasError = false;
2102   for (auto &I : ImmChecks) {
2103     int ArgNum, CheckTy, ElementSizeInBits;
2104     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2105 
2106     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2107 
2108     // Function that checks whether the operand (ArgNum) is an immediate
2109     // that is one of the predefined values.
2110     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2111                                    int ErrDiag) -> bool {
2112       // We can't check the value of a dependent argument.
2113       Expr *Arg = TheCall->getArg(ArgNum);
2114       if (Arg->isTypeDependent() || Arg->isValueDependent())
2115         return false;
2116 
2117       // Check constant-ness first.
2118       llvm::APSInt Imm;
2119       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2120         return true;
2121 
2122       if (!CheckImm(Imm.getSExtValue()))
2123         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2124       return false;
2125     };
2126 
2127     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2128     case SVETypeFlags::ImmCheck0_31:
2129       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2130         HasError = true;
2131       break;
2132     case SVETypeFlags::ImmCheck0_13:
2133       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2134         HasError = true;
2135       break;
2136     case SVETypeFlags::ImmCheck1_16:
2137       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2138         HasError = true;
2139       break;
2140     case SVETypeFlags::ImmCheck0_7:
2141       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2142         HasError = true;
2143       break;
2144     case SVETypeFlags::ImmCheckExtract:
2145       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2146                                       (2048 / ElementSizeInBits) - 1))
2147         HasError = true;
2148       break;
2149     case SVETypeFlags::ImmCheckShiftRight:
2150       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2151         HasError = true;
2152       break;
2153     case SVETypeFlags::ImmCheckShiftRightNarrow:
2154       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2155                                       ElementSizeInBits / 2))
2156         HasError = true;
2157       break;
2158     case SVETypeFlags::ImmCheckShiftLeft:
2159       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2160                                       ElementSizeInBits - 1))
2161         HasError = true;
2162       break;
2163     case SVETypeFlags::ImmCheckLaneIndex:
2164       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2165                                       (128 / (1 * ElementSizeInBits)) - 1))
2166         HasError = true;
2167       break;
2168     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2169       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2170                                       (128 / (2 * ElementSizeInBits)) - 1))
2171         HasError = true;
2172       break;
2173     case SVETypeFlags::ImmCheckLaneIndexDot:
2174       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2175                                       (128 / (4 * ElementSizeInBits)) - 1))
2176         HasError = true;
2177       break;
2178     case SVETypeFlags::ImmCheckComplexRot90_270:
2179       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2180                               diag::err_rotation_argument_to_cadd))
2181         HasError = true;
2182       break;
2183     case SVETypeFlags::ImmCheckComplexRotAll90:
2184       if (CheckImmediateInSet(
2185               [](int64_t V) {
2186                 return V == 0 || V == 90 || V == 180 || V == 270;
2187               },
2188               diag::err_rotation_argument_to_cmla))
2189         HasError = true;
2190       break;
2191     case SVETypeFlags::ImmCheck0_1:
2192       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2193         HasError = true;
2194       break;
2195     case SVETypeFlags::ImmCheck0_2:
2196       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2197         HasError = true;
2198       break;
2199     case SVETypeFlags::ImmCheck0_3:
2200       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2201         HasError = true;
2202       break;
2203     }
2204   }
2205 
2206   return HasError;
2207 }
2208 
2209 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2210                                         unsigned BuiltinID, CallExpr *TheCall) {
2211   llvm::APSInt Result;
2212   uint64_t mask = 0;
2213   unsigned TV = 0;
2214   int PtrArgNum = -1;
2215   bool HasConstPtr = false;
2216   switch (BuiltinID) {
2217 #define GET_NEON_OVERLOAD_CHECK
2218 #include "clang/Basic/arm_neon.inc"
2219 #include "clang/Basic/arm_fp16.inc"
2220 #undef GET_NEON_OVERLOAD_CHECK
2221   }
2222 
2223   // For NEON intrinsics which are overloaded on vector element type, validate
2224   // the immediate which specifies which variant to emit.
2225   unsigned ImmArg = TheCall->getNumArgs()-1;
2226   if (mask) {
2227     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2228       return true;
2229 
2230     TV = Result.getLimitedValue(64);
2231     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2232       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2233              << TheCall->getArg(ImmArg)->getSourceRange();
2234   }
2235 
2236   if (PtrArgNum >= 0) {
2237     // Check that pointer arguments have the specified type.
2238     Expr *Arg = TheCall->getArg(PtrArgNum);
2239     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2240       Arg = ICE->getSubExpr();
2241     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2242     QualType RHSTy = RHS.get()->getType();
2243 
2244     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2245     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2246                           Arch == llvm::Triple::aarch64_32 ||
2247                           Arch == llvm::Triple::aarch64_be;
2248     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2249     QualType EltTy =
2250         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2251     if (HasConstPtr)
2252       EltTy = EltTy.withConst();
2253     QualType LHSTy = Context.getPointerType(EltTy);
2254     AssignConvertType ConvTy;
2255     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2256     if (RHS.isInvalid())
2257       return true;
2258     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2259                                  RHS.get(), AA_Assigning))
2260       return true;
2261   }
2262 
2263   // For NEON intrinsics which take an immediate value as part of the
2264   // instruction, range check them here.
2265   unsigned i = 0, l = 0, u = 0;
2266   switch (BuiltinID) {
2267   default:
2268     return false;
2269   #define GET_NEON_IMMEDIATE_CHECK
2270   #include "clang/Basic/arm_neon.inc"
2271   #include "clang/Basic/arm_fp16.inc"
2272   #undef GET_NEON_IMMEDIATE_CHECK
2273   }
2274 
2275   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2276 }
2277 
2278 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2279   switch (BuiltinID) {
2280   default:
2281     return false;
2282   #include "clang/Basic/arm_mve_builtin_sema.inc"
2283   }
2284 }
2285 
2286 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2287                                        CallExpr *TheCall) {
2288   bool Err = false;
2289   switch (BuiltinID) {
2290   default:
2291     return false;
2292 #include "clang/Basic/arm_cde_builtin_sema.inc"
2293   }
2294 
2295   if (Err)
2296     return true;
2297 
2298   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2299 }
2300 
2301 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2302                                         const Expr *CoprocArg, bool WantCDE) {
2303   if (isConstantEvaluated())
2304     return false;
2305 
2306   // We can't check the value of a dependent argument.
2307   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2308     return false;
2309 
2310   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2311   int64_t CoprocNo = CoprocNoAP.getExtValue();
2312   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2313 
2314   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2315   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2316 
2317   if (IsCDECoproc != WantCDE)
2318     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2319            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2320 
2321   return false;
2322 }
2323 
2324 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2325                                         unsigned MaxWidth) {
2326   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2327           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2328           BuiltinID == ARM::BI__builtin_arm_strex ||
2329           BuiltinID == ARM::BI__builtin_arm_stlex ||
2330           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2331           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2332           BuiltinID == AArch64::BI__builtin_arm_strex ||
2333           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2334          "unexpected ARM builtin");
2335   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2336                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2337                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2338                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2339 
2340   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2341 
2342   // Ensure that we have the proper number of arguments.
2343   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2344     return true;
2345 
2346   // Inspect the pointer argument of the atomic builtin.  This should always be
2347   // a pointer type, whose element is an integral scalar or pointer type.
2348   // Because it is a pointer type, we don't have to worry about any implicit
2349   // casts here.
2350   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2351   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2352   if (PointerArgRes.isInvalid())
2353     return true;
2354   PointerArg = PointerArgRes.get();
2355 
2356   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2357   if (!pointerType) {
2358     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2359         << PointerArg->getType() << PointerArg->getSourceRange();
2360     return true;
2361   }
2362 
2363   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2364   // task is to insert the appropriate casts into the AST. First work out just
2365   // what the appropriate type is.
2366   QualType ValType = pointerType->getPointeeType();
2367   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2368   if (IsLdrex)
2369     AddrType.addConst();
2370 
2371   // Issue a warning if the cast is dodgy.
2372   CastKind CastNeeded = CK_NoOp;
2373   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2374     CastNeeded = CK_BitCast;
2375     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2376         << PointerArg->getType() << Context.getPointerType(AddrType)
2377         << AA_Passing << PointerArg->getSourceRange();
2378   }
2379 
2380   // Finally, do the cast and replace the argument with the corrected version.
2381   AddrType = Context.getPointerType(AddrType);
2382   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2383   if (PointerArgRes.isInvalid())
2384     return true;
2385   PointerArg = PointerArgRes.get();
2386 
2387   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2388 
2389   // In general, we allow ints, floats and pointers to be loaded and stored.
2390   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2391       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2392     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2393         << PointerArg->getType() << PointerArg->getSourceRange();
2394     return true;
2395   }
2396 
2397   // But ARM doesn't have instructions to deal with 128-bit versions.
2398   if (Context.getTypeSize(ValType) > MaxWidth) {
2399     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2400     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2401         << PointerArg->getType() << PointerArg->getSourceRange();
2402     return true;
2403   }
2404 
2405   switch (ValType.getObjCLifetime()) {
2406   case Qualifiers::OCL_None:
2407   case Qualifiers::OCL_ExplicitNone:
2408     // okay
2409     break;
2410 
2411   case Qualifiers::OCL_Weak:
2412   case Qualifiers::OCL_Strong:
2413   case Qualifiers::OCL_Autoreleasing:
2414     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2415         << ValType << PointerArg->getSourceRange();
2416     return true;
2417   }
2418 
2419   if (IsLdrex) {
2420     TheCall->setType(ValType);
2421     return false;
2422   }
2423 
2424   // Initialize the argument to be stored.
2425   ExprResult ValArg = TheCall->getArg(0);
2426   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2427       Context, ValType, /*consume*/ false);
2428   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2429   if (ValArg.isInvalid())
2430     return true;
2431   TheCall->setArg(0, ValArg.get());
2432 
2433   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2434   // but the custom checker bypasses all default analysis.
2435   TheCall->setType(Context.IntTy);
2436   return false;
2437 }
2438 
2439 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2440                                        CallExpr *TheCall) {
2441   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2442       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2443       BuiltinID == ARM::BI__builtin_arm_strex ||
2444       BuiltinID == ARM::BI__builtin_arm_stlex) {
2445     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2446   }
2447 
2448   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2449     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2450       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2451   }
2452 
2453   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2454       BuiltinID == ARM::BI__builtin_arm_wsr64)
2455     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2456 
2457   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2458       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2459       BuiltinID == ARM::BI__builtin_arm_wsr ||
2460       BuiltinID == ARM::BI__builtin_arm_wsrp)
2461     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2462 
2463   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2464     return true;
2465   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2466     return true;
2467   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2468     return true;
2469 
2470   // For intrinsics which take an immediate value as part of the instruction,
2471   // range check them here.
2472   // FIXME: VFP Intrinsics should error if VFP not present.
2473   switch (BuiltinID) {
2474   default: return false;
2475   case ARM::BI__builtin_arm_ssat:
2476     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2477   case ARM::BI__builtin_arm_usat:
2478     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2479   case ARM::BI__builtin_arm_ssat16:
2480     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2481   case ARM::BI__builtin_arm_usat16:
2482     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2483   case ARM::BI__builtin_arm_vcvtr_f:
2484   case ARM::BI__builtin_arm_vcvtr_d:
2485     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2486   case ARM::BI__builtin_arm_dmb:
2487   case ARM::BI__builtin_arm_dsb:
2488   case ARM::BI__builtin_arm_isb:
2489   case ARM::BI__builtin_arm_dbg:
2490     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2491   case ARM::BI__builtin_arm_cdp:
2492   case ARM::BI__builtin_arm_cdp2:
2493   case ARM::BI__builtin_arm_mcr:
2494   case ARM::BI__builtin_arm_mcr2:
2495   case ARM::BI__builtin_arm_mrc:
2496   case ARM::BI__builtin_arm_mrc2:
2497   case ARM::BI__builtin_arm_mcrr:
2498   case ARM::BI__builtin_arm_mcrr2:
2499   case ARM::BI__builtin_arm_mrrc:
2500   case ARM::BI__builtin_arm_mrrc2:
2501   case ARM::BI__builtin_arm_ldc:
2502   case ARM::BI__builtin_arm_ldcl:
2503   case ARM::BI__builtin_arm_ldc2:
2504   case ARM::BI__builtin_arm_ldc2l:
2505   case ARM::BI__builtin_arm_stc:
2506   case ARM::BI__builtin_arm_stcl:
2507   case ARM::BI__builtin_arm_stc2:
2508   case ARM::BI__builtin_arm_stc2l:
2509     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2510            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2511                                         /*WantCDE*/ false);
2512   }
2513 }
2514 
2515 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2516                                            unsigned BuiltinID,
2517                                            CallExpr *TheCall) {
2518   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2519       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2520       BuiltinID == AArch64::BI__builtin_arm_strex ||
2521       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2522     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2523   }
2524 
2525   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2526     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2527       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2528       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2529       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2530   }
2531 
2532   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2533       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2534     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2535 
2536   // Memory Tagging Extensions (MTE) Intrinsics
2537   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2538       BuiltinID == AArch64::BI__builtin_arm_addg ||
2539       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2540       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2541       BuiltinID == AArch64::BI__builtin_arm_stg ||
2542       BuiltinID == AArch64::BI__builtin_arm_subp) {
2543     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2544   }
2545 
2546   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2547       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2548       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2549       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2550     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2551 
2552   // Only check the valid encoding range. Any constant in this range would be
2553   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2554   // an exception for incorrect registers. This matches MSVC behavior.
2555   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2556       BuiltinID == AArch64::BI_WriteStatusReg)
2557     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2558 
2559   if (BuiltinID == AArch64::BI__getReg)
2560     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2561 
2562   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2563     return true;
2564 
2565   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2566     return true;
2567 
2568   // For intrinsics which take an immediate value as part of the instruction,
2569   // range check them here.
2570   unsigned i = 0, l = 0, u = 0;
2571   switch (BuiltinID) {
2572   default: return false;
2573   case AArch64::BI__builtin_arm_dmb:
2574   case AArch64::BI__builtin_arm_dsb:
2575   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2576   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2577   }
2578 
2579   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2580 }
2581 
2582 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2583   if (Arg->getType()->getAsPlaceholderType())
2584     return false;
2585 
2586   // The first argument needs to be a record field access.
2587   // If it is an array element access, we delay decision
2588   // to BPF backend to check whether the access is a
2589   // field access or not.
2590   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2591           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2592           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2593 }
2594 
2595 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2596                             QualType VectorTy, QualType EltTy) {
2597   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2598   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2599     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2600         << Call->getSourceRange() << VectorEltTy << EltTy;
2601     return false;
2602   }
2603   return true;
2604 }
2605 
2606 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2607   QualType ArgType = Arg->getType();
2608   if (ArgType->getAsPlaceholderType())
2609     return false;
2610 
2611   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2612   // format:
2613   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2614   //   2. <type> var;
2615   //      __builtin_preserve_type_info(var, flag);
2616   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2617       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2618     return false;
2619 
2620   // Typedef type.
2621   if (ArgType->getAs<TypedefType>())
2622     return true;
2623 
2624   // Record type or Enum type.
2625   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2626   if (const auto *RT = Ty->getAs<RecordType>()) {
2627     if (!RT->getDecl()->getDeclName().isEmpty())
2628       return true;
2629   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2630     if (!ET->getDecl()->getDeclName().isEmpty())
2631       return true;
2632   }
2633 
2634   return false;
2635 }
2636 
2637 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2638   QualType ArgType = Arg->getType();
2639   if (ArgType->getAsPlaceholderType())
2640     return false;
2641 
2642   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2643   // format:
2644   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2645   //                                 flag);
2646   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2647   if (!UO)
2648     return false;
2649 
2650   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2651   if (!CE)
2652     return false;
2653   if (CE->getCastKind() != CK_IntegralToPointer &&
2654       CE->getCastKind() != CK_NullToPointer)
2655     return false;
2656 
2657   // The integer must be from an EnumConstantDecl.
2658   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2659   if (!DR)
2660     return false;
2661 
2662   const EnumConstantDecl *Enumerator =
2663       dyn_cast<EnumConstantDecl>(DR->getDecl());
2664   if (!Enumerator)
2665     return false;
2666 
2667   // The type must be EnumType.
2668   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2669   const auto *ET = Ty->getAs<EnumType>();
2670   if (!ET)
2671     return false;
2672 
2673   // The enum value must be supported.
2674   for (auto *EDI : ET->getDecl()->enumerators()) {
2675     if (EDI == Enumerator)
2676       return true;
2677   }
2678 
2679   return false;
2680 }
2681 
2682 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2683                                        CallExpr *TheCall) {
2684   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2685           BuiltinID == BPF::BI__builtin_btf_type_id ||
2686           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2687           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2688          "unexpected BPF builtin");
2689 
2690   if (checkArgCount(*this, TheCall, 2))
2691     return true;
2692 
2693   // The second argument needs to be a constant int
2694   Expr *Arg = TheCall->getArg(1);
2695   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2696   diag::kind kind;
2697   if (!Value) {
2698     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2699       kind = diag::err_preserve_field_info_not_const;
2700     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2701       kind = diag::err_btf_type_id_not_const;
2702     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2703       kind = diag::err_preserve_type_info_not_const;
2704     else
2705       kind = diag::err_preserve_enum_value_not_const;
2706     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2707     return true;
2708   }
2709 
2710   // The first argument
2711   Arg = TheCall->getArg(0);
2712   bool InvalidArg = false;
2713   bool ReturnUnsignedInt = true;
2714   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2715     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2716       InvalidArg = true;
2717       kind = diag::err_preserve_field_info_not_field;
2718     }
2719   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2720     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2721       InvalidArg = true;
2722       kind = diag::err_preserve_type_info_invalid;
2723     }
2724   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2725     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2726       InvalidArg = true;
2727       kind = diag::err_preserve_enum_value_invalid;
2728     }
2729     ReturnUnsignedInt = false;
2730   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2731     ReturnUnsignedInt = false;
2732   }
2733 
2734   if (InvalidArg) {
2735     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2736     return true;
2737   }
2738 
2739   if (ReturnUnsignedInt)
2740     TheCall->setType(Context.UnsignedIntTy);
2741   else
2742     TheCall->setType(Context.UnsignedLongTy);
2743   return false;
2744 }
2745 
2746 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2747   struct ArgInfo {
2748     uint8_t OpNum;
2749     bool IsSigned;
2750     uint8_t BitWidth;
2751     uint8_t Align;
2752   };
2753   struct BuiltinInfo {
2754     unsigned BuiltinID;
2755     ArgInfo Infos[2];
2756   };
2757 
2758   static BuiltinInfo Infos[] = {
2759     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2760     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2761     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2762     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2763     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2764     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2765     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2766     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2767     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2768     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2769     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2770 
2771     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2774     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2775     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2776     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2777     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2782 
2783     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2835                                                       {{ 1, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2843                                                       {{ 1, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2850                                                        { 2, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2852                                                        { 2, false, 6,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2854                                                        { 3, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2856                                                        { 3, false, 6,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2873                                                       {{ 2, false, 4,  0 },
2874                                                        { 3, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2876                                                       {{ 2, false, 4,  0 },
2877                                                        { 3, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2879                                                       {{ 2, false, 4,  0 },
2880                                                        { 3, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2882                                                       {{ 2, false, 4,  0 },
2883                                                        { 3, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2895                                                        { 2, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2897                                                        { 2, false, 6,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2907                                                       {{ 1, false, 4,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2910                                                       {{ 1, false, 4,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2931                                                       {{ 3, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2936                                                       {{ 3, false, 1,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2941                                                       {{ 3, false, 1,  0 }} },
2942   };
2943 
2944   // Use a dynamically initialized static to sort the table exactly once on
2945   // first run.
2946   static const bool SortOnce =
2947       (llvm::sort(Infos,
2948                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2949                    return LHS.BuiltinID < RHS.BuiltinID;
2950                  }),
2951        true);
2952   (void)SortOnce;
2953 
2954   const BuiltinInfo *F = llvm::partition_point(
2955       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2956   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2957     return false;
2958 
2959   bool Error = false;
2960 
2961   for (const ArgInfo &A : F->Infos) {
2962     // Ignore empty ArgInfo elements.
2963     if (A.BitWidth == 0)
2964       continue;
2965 
2966     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2967     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2968     if (!A.Align) {
2969       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2970     } else {
2971       unsigned M = 1 << A.Align;
2972       Min *= M;
2973       Max *= M;
2974       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2975                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2976     }
2977   }
2978   return Error;
2979 }
2980 
2981 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2982                                            CallExpr *TheCall) {
2983   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2984 }
2985 
2986 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2987                                         unsigned BuiltinID, CallExpr *TheCall) {
2988   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2989          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2990 }
2991 
2992 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2993                                CallExpr *TheCall) {
2994 
2995   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2996       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2997     if (!TI.hasFeature("dsp"))
2998       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2999   }
3000 
3001   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3002       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3003     if (!TI.hasFeature("dspr2"))
3004       return Diag(TheCall->getBeginLoc(),
3005                   diag::err_mips_builtin_requires_dspr2);
3006   }
3007 
3008   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3009       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3010     if (!TI.hasFeature("msa"))
3011       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3012   }
3013 
3014   return false;
3015 }
3016 
3017 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3018 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3019 // ordering for DSP is unspecified. MSA is ordered by the data format used
3020 // by the underlying instruction i.e., df/m, df/n and then by size.
3021 //
3022 // FIXME: The size tests here should instead be tablegen'd along with the
3023 //        definitions from include/clang/Basic/BuiltinsMips.def.
3024 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3025 //        be too.
3026 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3027   unsigned i = 0, l = 0, u = 0, m = 0;
3028   switch (BuiltinID) {
3029   default: return false;
3030   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3031   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3032   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3033   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3034   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3035   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3036   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3037   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3038   // df/m field.
3039   // These intrinsics take an unsigned 3 bit immediate.
3040   case Mips::BI__builtin_msa_bclri_b:
3041   case Mips::BI__builtin_msa_bnegi_b:
3042   case Mips::BI__builtin_msa_bseti_b:
3043   case Mips::BI__builtin_msa_sat_s_b:
3044   case Mips::BI__builtin_msa_sat_u_b:
3045   case Mips::BI__builtin_msa_slli_b:
3046   case Mips::BI__builtin_msa_srai_b:
3047   case Mips::BI__builtin_msa_srari_b:
3048   case Mips::BI__builtin_msa_srli_b:
3049   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3050   case Mips::BI__builtin_msa_binsli_b:
3051   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3052   // These intrinsics take an unsigned 4 bit immediate.
3053   case Mips::BI__builtin_msa_bclri_h:
3054   case Mips::BI__builtin_msa_bnegi_h:
3055   case Mips::BI__builtin_msa_bseti_h:
3056   case Mips::BI__builtin_msa_sat_s_h:
3057   case Mips::BI__builtin_msa_sat_u_h:
3058   case Mips::BI__builtin_msa_slli_h:
3059   case Mips::BI__builtin_msa_srai_h:
3060   case Mips::BI__builtin_msa_srari_h:
3061   case Mips::BI__builtin_msa_srli_h:
3062   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3063   case Mips::BI__builtin_msa_binsli_h:
3064   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3065   // These intrinsics take an unsigned 5 bit immediate.
3066   // The first block of intrinsics actually have an unsigned 5 bit field,
3067   // not a df/n field.
3068   case Mips::BI__builtin_msa_cfcmsa:
3069   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3070   case Mips::BI__builtin_msa_clei_u_b:
3071   case Mips::BI__builtin_msa_clei_u_h:
3072   case Mips::BI__builtin_msa_clei_u_w:
3073   case Mips::BI__builtin_msa_clei_u_d:
3074   case Mips::BI__builtin_msa_clti_u_b:
3075   case Mips::BI__builtin_msa_clti_u_h:
3076   case Mips::BI__builtin_msa_clti_u_w:
3077   case Mips::BI__builtin_msa_clti_u_d:
3078   case Mips::BI__builtin_msa_maxi_u_b:
3079   case Mips::BI__builtin_msa_maxi_u_h:
3080   case Mips::BI__builtin_msa_maxi_u_w:
3081   case Mips::BI__builtin_msa_maxi_u_d:
3082   case Mips::BI__builtin_msa_mini_u_b:
3083   case Mips::BI__builtin_msa_mini_u_h:
3084   case Mips::BI__builtin_msa_mini_u_w:
3085   case Mips::BI__builtin_msa_mini_u_d:
3086   case Mips::BI__builtin_msa_addvi_b:
3087   case Mips::BI__builtin_msa_addvi_h:
3088   case Mips::BI__builtin_msa_addvi_w:
3089   case Mips::BI__builtin_msa_addvi_d:
3090   case Mips::BI__builtin_msa_bclri_w:
3091   case Mips::BI__builtin_msa_bnegi_w:
3092   case Mips::BI__builtin_msa_bseti_w:
3093   case Mips::BI__builtin_msa_sat_s_w:
3094   case Mips::BI__builtin_msa_sat_u_w:
3095   case Mips::BI__builtin_msa_slli_w:
3096   case Mips::BI__builtin_msa_srai_w:
3097   case Mips::BI__builtin_msa_srari_w:
3098   case Mips::BI__builtin_msa_srli_w:
3099   case Mips::BI__builtin_msa_srlri_w:
3100   case Mips::BI__builtin_msa_subvi_b:
3101   case Mips::BI__builtin_msa_subvi_h:
3102   case Mips::BI__builtin_msa_subvi_w:
3103   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3104   case Mips::BI__builtin_msa_binsli_w:
3105   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3106   // These intrinsics take an unsigned 6 bit immediate.
3107   case Mips::BI__builtin_msa_bclri_d:
3108   case Mips::BI__builtin_msa_bnegi_d:
3109   case Mips::BI__builtin_msa_bseti_d:
3110   case Mips::BI__builtin_msa_sat_s_d:
3111   case Mips::BI__builtin_msa_sat_u_d:
3112   case Mips::BI__builtin_msa_slli_d:
3113   case Mips::BI__builtin_msa_srai_d:
3114   case Mips::BI__builtin_msa_srari_d:
3115   case Mips::BI__builtin_msa_srli_d:
3116   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3117   case Mips::BI__builtin_msa_binsli_d:
3118   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3119   // These intrinsics take a signed 5 bit immediate.
3120   case Mips::BI__builtin_msa_ceqi_b:
3121   case Mips::BI__builtin_msa_ceqi_h:
3122   case Mips::BI__builtin_msa_ceqi_w:
3123   case Mips::BI__builtin_msa_ceqi_d:
3124   case Mips::BI__builtin_msa_clti_s_b:
3125   case Mips::BI__builtin_msa_clti_s_h:
3126   case Mips::BI__builtin_msa_clti_s_w:
3127   case Mips::BI__builtin_msa_clti_s_d:
3128   case Mips::BI__builtin_msa_clei_s_b:
3129   case Mips::BI__builtin_msa_clei_s_h:
3130   case Mips::BI__builtin_msa_clei_s_w:
3131   case Mips::BI__builtin_msa_clei_s_d:
3132   case Mips::BI__builtin_msa_maxi_s_b:
3133   case Mips::BI__builtin_msa_maxi_s_h:
3134   case Mips::BI__builtin_msa_maxi_s_w:
3135   case Mips::BI__builtin_msa_maxi_s_d:
3136   case Mips::BI__builtin_msa_mini_s_b:
3137   case Mips::BI__builtin_msa_mini_s_h:
3138   case Mips::BI__builtin_msa_mini_s_w:
3139   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3140   // These intrinsics take an unsigned 8 bit immediate.
3141   case Mips::BI__builtin_msa_andi_b:
3142   case Mips::BI__builtin_msa_nori_b:
3143   case Mips::BI__builtin_msa_ori_b:
3144   case Mips::BI__builtin_msa_shf_b:
3145   case Mips::BI__builtin_msa_shf_h:
3146   case Mips::BI__builtin_msa_shf_w:
3147   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3148   case Mips::BI__builtin_msa_bseli_b:
3149   case Mips::BI__builtin_msa_bmnzi_b:
3150   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3151   // df/n format
3152   // These intrinsics take an unsigned 4 bit immediate.
3153   case Mips::BI__builtin_msa_copy_s_b:
3154   case Mips::BI__builtin_msa_copy_u_b:
3155   case Mips::BI__builtin_msa_insve_b:
3156   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3157   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3158   // These intrinsics take an unsigned 3 bit immediate.
3159   case Mips::BI__builtin_msa_copy_s_h:
3160   case Mips::BI__builtin_msa_copy_u_h:
3161   case Mips::BI__builtin_msa_insve_h:
3162   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3163   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3164   // These intrinsics take an unsigned 2 bit immediate.
3165   case Mips::BI__builtin_msa_copy_s_w:
3166   case Mips::BI__builtin_msa_copy_u_w:
3167   case Mips::BI__builtin_msa_insve_w:
3168   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3169   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3170   // These intrinsics take an unsigned 1 bit immediate.
3171   case Mips::BI__builtin_msa_copy_s_d:
3172   case Mips::BI__builtin_msa_copy_u_d:
3173   case Mips::BI__builtin_msa_insve_d:
3174   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3175   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3176   // Memory offsets and immediate loads.
3177   // These intrinsics take a signed 10 bit immediate.
3178   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3179   case Mips::BI__builtin_msa_ldi_h:
3180   case Mips::BI__builtin_msa_ldi_w:
3181   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3182   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3183   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3184   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3185   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3186   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3187   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3188   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3189   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3190   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3191   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3192   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3193   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3194   }
3195 
3196   if (!m)
3197     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3198 
3199   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3200          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3201 }
3202 
3203 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3204 /// advancing the pointer over the consumed characters. The decoded type is
3205 /// returned. If the decoded type represents a constant integer with a
3206 /// constraint on its value then Mask is set to that value. The type descriptors
3207 /// used in Str are specific to PPC MMA builtins and are documented in the file
3208 /// defining the PPC builtins.
3209 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3210                                         unsigned &Mask) {
3211   bool RequireICE = false;
3212   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3213   switch (*Str++) {
3214   case 'V':
3215     return Context.getVectorType(Context.UnsignedCharTy, 16,
3216                                  VectorType::VectorKind::AltiVecVector);
3217   case 'i': {
3218     char *End;
3219     unsigned size = strtoul(Str, &End, 10);
3220     assert(End != Str && "Missing constant parameter constraint");
3221     Str = End;
3222     Mask = size;
3223     return Context.IntTy;
3224   }
3225   case 'W': {
3226     char *End;
3227     unsigned size = strtoul(Str, &End, 10);
3228     assert(End != Str && "Missing PowerPC MMA type size");
3229     Str = End;
3230     QualType Type;
3231     switch (size) {
3232   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3233     case size: Type = Context.Id##Ty; break;
3234   #include "clang/Basic/PPCTypes.def"
3235     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3236     }
3237     bool CheckVectorArgs = false;
3238     while (!CheckVectorArgs) {
3239       switch (*Str++) {
3240       case '*':
3241         Type = Context.getPointerType(Type);
3242         break;
3243       case 'C':
3244         Type = Type.withConst();
3245         break;
3246       default:
3247         CheckVectorArgs = true;
3248         --Str;
3249         break;
3250       }
3251     }
3252     return Type;
3253   }
3254   default:
3255     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3256   }
3257 }
3258 
3259 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3260                                        CallExpr *TheCall) {
3261   unsigned i = 0, l = 0, u = 0;
3262   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3263                       BuiltinID == PPC::BI__builtin_divdeu ||
3264                       BuiltinID == PPC::BI__builtin_bpermd;
3265   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3266   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3267                        BuiltinID == PPC::BI__builtin_divweu ||
3268                        BuiltinID == PPC::BI__builtin_divde ||
3269                        BuiltinID == PPC::BI__builtin_divdeu;
3270 
3271   if (Is64BitBltin && !IsTarget64Bit)
3272     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3273            << TheCall->getSourceRange();
3274 
3275   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3276       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3277     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3278            << TheCall->getSourceRange();
3279 
3280   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3281     if (!TI.hasFeature("vsx"))
3282       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3283              << TheCall->getSourceRange();
3284     return false;
3285   };
3286 
3287   switch (BuiltinID) {
3288   default: return false;
3289   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3290   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3291     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3292            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3293   case PPC::BI__builtin_altivec_dss:
3294     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3295   case PPC::BI__builtin_tbegin:
3296   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3297   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3298   case PPC::BI__builtin_tabortwc:
3299   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3300   case PPC::BI__builtin_tabortwci:
3301   case PPC::BI__builtin_tabortdci:
3302     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3303            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3304   case PPC::BI__builtin_altivec_dst:
3305   case PPC::BI__builtin_altivec_dstt:
3306   case PPC::BI__builtin_altivec_dstst:
3307   case PPC::BI__builtin_altivec_dststt:
3308     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3309   case PPC::BI__builtin_vsx_xxpermdi:
3310   case PPC::BI__builtin_vsx_xxsldwi:
3311     return SemaBuiltinVSX(TheCall);
3312   case PPC::BI__builtin_unpack_vector_int128:
3313     return SemaVSXCheck(TheCall) ||
3314            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3315   case PPC::BI__builtin_pack_vector_int128:
3316     return SemaVSXCheck(TheCall);
3317   case PPC::BI__builtin_altivec_vgnb:
3318      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3319   case PPC::BI__builtin_altivec_vec_replace_elt:
3320   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3321     QualType VecTy = TheCall->getArg(0)->getType();
3322     QualType EltTy = TheCall->getArg(1)->getType();
3323     unsigned Width = Context.getIntWidth(EltTy);
3324     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3325            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3326   }
3327   case PPC::BI__builtin_vsx_xxeval:
3328      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3329   case PPC::BI__builtin_altivec_vsldbi:
3330      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3331   case PPC::BI__builtin_altivec_vsrdbi:
3332      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3333   case PPC::BI__builtin_vsx_xxpermx:
3334      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3335 #define CUSTOM_BUILTIN(Name, Types, Acc) \
3336   case PPC::BI__builtin_##Name: \
3337     return SemaBuiltinPPCMMACall(TheCall, Types);
3338 #include "clang/Basic/BuiltinsPPC.def"
3339   }
3340   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3341 }
3342 
3343 // Check if the given type is a non-pointer PPC MMA type. This function is used
3344 // in Sema to prevent invalid uses of restricted PPC MMA types.
3345 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3346   if (Type->isPointerType() || Type->isArrayType())
3347     return false;
3348 
3349   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3350 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3351   if (false
3352 #include "clang/Basic/PPCTypes.def"
3353      ) {
3354     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3355     return true;
3356   }
3357   return false;
3358 }
3359 
3360 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3361                                           CallExpr *TheCall) {
3362   // position of memory order and scope arguments in the builtin
3363   unsigned OrderIndex, ScopeIndex;
3364   switch (BuiltinID) {
3365   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3366   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3367   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3368   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3369     OrderIndex = 2;
3370     ScopeIndex = 3;
3371     break;
3372   case AMDGPU::BI__builtin_amdgcn_fence:
3373     OrderIndex = 0;
3374     ScopeIndex = 1;
3375     break;
3376   default:
3377     return false;
3378   }
3379 
3380   ExprResult Arg = TheCall->getArg(OrderIndex);
3381   auto ArgExpr = Arg.get();
3382   Expr::EvalResult ArgResult;
3383 
3384   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3385     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3386            << ArgExpr->getType();
3387   auto Ord = ArgResult.Val.getInt().getZExtValue();
3388 
3389   // Check valididty of memory ordering as per C11 / C++11's memody model.
3390   // Only fence needs check. Atomic dec/inc allow all memory orders.
3391   if (!llvm::isValidAtomicOrderingCABI(Ord))
3392     return Diag(ArgExpr->getBeginLoc(),
3393                 diag::warn_atomic_op_has_invalid_memory_order)
3394            << ArgExpr->getSourceRange();
3395   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3396   case llvm::AtomicOrderingCABI::relaxed:
3397   case llvm::AtomicOrderingCABI::consume:
3398     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3399       return Diag(ArgExpr->getBeginLoc(),
3400                   diag::warn_atomic_op_has_invalid_memory_order)
3401              << ArgExpr->getSourceRange();
3402     break;
3403   case llvm::AtomicOrderingCABI::acquire:
3404   case llvm::AtomicOrderingCABI::release:
3405   case llvm::AtomicOrderingCABI::acq_rel:
3406   case llvm::AtomicOrderingCABI::seq_cst:
3407     break;
3408   }
3409 
3410   Arg = TheCall->getArg(ScopeIndex);
3411   ArgExpr = Arg.get();
3412   Expr::EvalResult ArgResult1;
3413   // Check that sync scope is a constant literal
3414   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3415     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3416            << ArgExpr->getType();
3417 
3418   return false;
3419 }
3420 
3421 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3422                                          unsigned BuiltinID,
3423                                          CallExpr *TheCall) {
3424   // CodeGenFunction can also detect this, but this gives a better error
3425   // message.
3426   bool FeatureMissing = false;
3427   SmallVector<StringRef> ReqFeatures;
3428   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3429   Features.split(ReqFeatures, ',');
3430 
3431   // Check if each required feature is included
3432   for (StringRef F : ReqFeatures) {
3433     if (TI.hasFeature(F))
3434       continue;
3435 
3436     // If the feature is 64bit, alter the string so it will print better in
3437     // the diagnostic.
3438     if (F == "64bit")
3439       F = "RV64";
3440 
3441     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3442     F.consume_front("experimental-");
3443     std::string FeatureStr = F.str();
3444     FeatureStr[0] = std::toupper(FeatureStr[0]);
3445 
3446     // Error message
3447     FeatureMissing = true;
3448     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3449         << TheCall->getSourceRange() << StringRef(FeatureStr);
3450   }
3451 
3452   return FeatureMissing;
3453 }
3454 
3455 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3456                                            CallExpr *TheCall) {
3457   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3458     Expr *Arg = TheCall->getArg(0);
3459     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3460       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3461         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3462                << Arg->getSourceRange();
3463   }
3464 
3465   // For intrinsics which take an immediate value as part of the instruction,
3466   // range check them here.
3467   unsigned i = 0, l = 0, u = 0;
3468   switch (BuiltinID) {
3469   default: return false;
3470   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3471   case SystemZ::BI__builtin_s390_verimb:
3472   case SystemZ::BI__builtin_s390_verimh:
3473   case SystemZ::BI__builtin_s390_verimf:
3474   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3475   case SystemZ::BI__builtin_s390_vfaeb:
3476   case SystemZ::BI__builtin_s390_vfaeh:
3477   case SystemZ::BI__builtin_s390_vfaef:
3478   case SystemZ::BI__builtin_s390_vfaebs:
3479   case SystemZ::BI__builtin_s390_vfaehs:
3480   case SystemZ::BI__builtin_s390_vfaefs:
3481   case SystemZ::BI__builtin_s390_vfaezb:
3482   case SystemZ::BI__builtin_s390_vfaezh:
3483   case SystemZ::BI__builtin_s390_vfaezf:
3484   case SystemZ::BI__builtin_s390_vfaezbs:
3485   case SystemZ::BI__builtin_s390_vfaezhs:
3486   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3487   case SystemZ::BI__builtin_s390_vfisb:
3488   case SystemZ::BI__builtin_s390_vfidb:
3489     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3490            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3491   case SystemZ::BI__builtin_s390_vftcisb:
3492   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3493   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3494   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3495   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3496   case SystemZ::BI__builtin_s390_vstrcb:
3497   case SystemZ::BI__builtin_s390_vstrch:
3498   case SystemZ::BI__builtin_s390_vstrcf:
3499   case SystemZ::BI__builtin_s390_vstrczb:
3500   case SystemZ::BI__builtin_s390_vstrczh:
3501   case SystemZ::BI__builtin_s390_vstrczf:
3502   case SystemZ::BI__builtin_s390_vstrcbs:
3503   case SystemZ::BI__builtin_s390_vstrchs:
3504   case SystemZ::BI__builtin_s390_vstrcfs:
3505   case SystemZ::BI__builtin_s390_vstrczbs:
3506   case SystemZ::BI__builtin_s390_vstrczhs:
3507   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3508   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3509   case SystemZ::BI__builtin_s390_vfminsb:
3510   case SystemZ::BI__builtin_s390_vfmaxsb:
3511   case SystemZ::BI__builtin_s390_vfmindb:
3512   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3513   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3514   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3515   }
3516   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3517 }
3518 
3519 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3520 /// This checks that the target supports __builtin_cpu_supports and
3521 /// that the string argument is constant and valid.
3522 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3523                                    CallExpr *TheCall) {
3524   Expr *Arg = TheCall->getArg(0);
3525 
3526   // Check if the argument is a string literal.
3527   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3528     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3529            << Arg->getSourceRange();
3530 
3531   // Check the contents of the string.
3532   StringRef Feature =
3533       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3534   if (!TI.validateCpuSupports(Feature))
3535     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3536            << Arg->getSourceRange();
3537   return false;
3538 }
3539 
3540 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3541 /// This checks that the target supports __builtin_cpu_is and
3542 /// that the string argument is constant and valid.
3543 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3544   Expr *Arg = TheCall->getArg(0);
3545 
3546   // Check if the argument is a string literal.
3547   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3548     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3549            << Arg->getSourceRange();
3550 
3551   // Check the contents of the string.
3552   StringRef Feature =
3553       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3554   if (!TI.validateCpuIs(Feature))
3555     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3556            << Arg->getSourceRange();
3557   return false;
3558 }
3559 
3560 // Check if the rounding mode is legal.
3561 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3562   // Indicates if this instruction has rounding control or just SAE.
3563   bool HasRC = false;
3564 
3565   unsigned ArgNum = 0;
3566   switch (BuiltinID) {
3567   default:
3568     return false;
3569   case X86::BI__builtin_ia32_vcvttsd2si32:
3570   case X86::BI__builtin_ia32_vcvttsd2si64:
3571   case X86::BI__builtin_ia32_vcvttsd2usi32:
3572   case X86::BI__builtin_ia32_vcvttsd2usi64:
3573   case X86::BI__builtin_ia32_vcvttss2si32:
3574   case X86::BI__builtin_ia32_vcvttss2si64:
3575   case X86::BI__builtin_ia32_vcvttss2usi32:
3576   case X86::BI__builtin_ia32_vcvttss2usi64:
3577     ArgNum = 1;
3578     break;
3579   case X86::BI__builtin_ia32_maxpd512:
3580   case X86::BI__builtin_ia32_maxps512:
3581   case X86::BI__builtin_ia32_minpd512:
3582   case X86::BI__builtin_ia32_minps512:
3583     ArgNum = 2;
3584     break;
3585   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3586   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3587   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3588   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3589   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3590   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3591   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3592   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3593   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3594   case X86::BI__builtin_ia32_exp2pd_mask:
3595   case X86::BI__builtin_ia32_exp2ps_mask:
3596   case X86::BI__builtin_ia32_getexppd512_mask:
3597   case X86::BI__builtin_ia32_getexpps512_mask:
3598   case X86::BI__builtin_ia32_rcp28pd_mask:
3599   case X86::BI__builtin_ia32_rcp28ps_mask:
3600   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3601   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3602   case X86::BI__builtin_ia32_vcomisd:
3603   case X86::BI__builtin_ia32_vcomiss:
3604   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3605     ArgNum = 3;
3606     break;
3607   case X86::BI__builtin_ia32_cmppd512_mask:
3608   case X86::BI__builtin_ia32_cmpps512_mask:
3609   case X86::BI__builtin_ia32_cmpsd_mask:
3610   case X86::BI__builtin_ia32_cmpss_mask:
3611   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3612   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3613   case X86::BI__builtin_ia32_getexpss128_round_mask:
3614   case X86::BI__builtin_ia32_getmantpd512_mask:
3615   case X86::BI__builtin_ia32_getmantps512_mask:
3616   case X86::BI__builtin_ia32_maxsd_round_mask:
3617   case X86::BI__builtin_ia32_maxss_round_mask:
3618   case X86::BI__builtin_ia32_minsd_round_mask:
3619   case X86::BI__builtin_ia32_minss_round_mask:
3620   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3621   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3622   case X86::BI__builtin_ia32_reducepd512_mask:
3623   case X86::BI__builtin_ia32_reduceps512_mask:
3624   case X86::BI__builtin_ia32_rndscalepd_mask:
3625   case X86::BI__builtin_ia32_rndscaleps_mask:
3626   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3627   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3628     ArgNum = 4;
3629     break;
3630   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3631   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3632   case X86::BI__builtin_ia32_fixupimmps512_mask:
3633   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3634   case X86::BI__builtin_ia32_fixupimmsd_mask:
3635   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3636   case X86::BI__builtin_ia32_fixupimmss_mask:
3637   case X86::BI__builtin_ia32_fixupimmss_maskz:
3638   case X86::BI__builtin_ia32_getmantsd_round_mask:
3639   case X86::BI__builtin_ia32_getmantss_round_mask:
3640   case X86::BI__builtin_ia32_rangepd512_mask:
3641   case X86::BI__builtin_ia32_rangeps512_mask:
3642   case X86::BI__builtin_ia32_rangesd128_round_mask:
3643   case X86::BI__builtin_ia32_rangess128_round_mask:
3644   case X86::BI__builtin_ia32_reducesd_mask:
3645   case X86::BI__builtin_ia32_reducess_mask:
3646   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3647   case X86::BI__builtin_ia32_rndscaless_round_mask:
3648     ArgNum = 5;
3649     break;
3650   case X86::BI__builtin_ia32_vcvtsd2si64:
3651   case X86::BI__builtin_ia32_vcvtsd2si32:
3652   case X86::BI__builtin_ia32_vcvtsd2usi32:
3653   case X86::BI__builtin_ia32_vcvtsd2usi64:
3654   case X86::BI__builtin_ia32_vcvtss2si32:
3655   case X86::BI__builtin_ia32_vcvtss2si64:
3656   case X86::BI__builtin_ia32_vcvtss2usi32:
3657   case X86::BI__builtin_ia32_vcvtss2usi64:
3658   case X86::BI__builtin_ia32_sqrtpd512:
3659   case X86::BI__builtin_ia32_sqrtps512:
3660     ArgNum = 1;
3661     HasRC = true;
3662     break;
3663   case X86::BI__builtin_ia32_addpd512:
3664   case X86::BI__builtin_ia32_addps512:
3665   case X86::BI__builtin_ia32_divpd512:
3666   case X86::BI__builtin_ia32_divps512:
3667   case X86::BI__builtin_ia32_mulpd512:
3668   case X86::BI__builtin_ia32_mulps512:
3669   case X86::BI__builtin_ia32_subpd512:
3670   case X86::BI__builtin_ia32_subps512:
3671   case X86::BI__builtin_ia32_cvtsi2sd64:
3672   case X86::BI__builtin_ia32_cvtsi2ss32:
3673   case X86::BI__builtin_ia32_cvtsi2ss64:
3674   case X86::BI__builtin_ia32_cvtusi2sd64:
3675   case X86::BI__builtin_ia32_cvtusi2ss32:
3676   case X86::BI__builtin_ia32_cvtusi2ss64:
3677     ArgNum = 2;
3678     HasRC = true;
3679     break;
3680   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3681   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3682   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3683   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3684   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3685   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3686   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3687   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3688   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3689   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3690   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3691   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3692   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3693   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3694   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3695     ArgNum = 3;
3696     HasRC = true;
3697     break;
3698   case X86::BI__builtin_ia32_addss_round_mask:
3699   case X86::BI__builtin_ia32_addsd_round_mask:
3700   case X86::BI__builtin_ia32_divss_round_mask:
3701   case X86::BI__builtin_ia32_divsd_round_mask:
3702   case X86::BI__builtin_ia32_mulss_round_mask:
3703   case X86::BI__builtin_ia32_mulsd_round_mask:
3704   case X86::BI__builtin_ia32_subss_round_mask:
3705   case X86::BI__builtin_ia32_subsd_round_mask:
3706   case X86::BI__builtin_ia32_scalefpd512_mask:
3707   case X86::BI__builtin_ia32_scalefps512_mask:
3708   case X86::BI__builtin_ia32_scalefsd_round_mask:
3709   case X86::BI__builtin_ia32_scalefss_round_mask:
3710   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3711   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3712   case X86::BI__builtin_ia32_sqrtss_round_mask:
3713   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3714   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3715   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3716   case X86::BI__builtin_ia32_vfmaddss3_mask:
3717   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3718   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3719   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3720   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3721   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3722   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3723   case X86::BI__builtin_ia32_vfmaddps512_mask:
3724   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3725   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3726   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3727   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3728   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3729   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3730   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3731   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3732   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3733   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3734   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3735     ArgNum = 4;
3736     HasRC = true;
3737     break;
3738   }
3739 
3740   llvm::APSInt Result;
3741 
3742   // We can't check the value of a dependent argument.
3743   Expr *Arg = TheCall->getArg(ArgNum);
3744   if (Arg->isTypeDependent() || Arg->isValueDependent())
3745     return false;
3746 
3747   // Check constant-ness first.
3748   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3749     return true;
3750 
3751   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3752   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3753   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3754   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3755   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3756       Result == 8/*ROUND_NO_EXC*/ ||
3757       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3758       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3759     return false;
3760 
3761   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3762          << Arg->getSourceRange();
3763 }
3764 
3765 // Check if the gather/scatter scale is legal.
3766 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3767                                              CallExpr *TheCall) {
3768   unsigned ArgNum = 0;
3769   switch (BuiltinID) {
3770   default:
3771     return false;
3772   case X86::BI__builtin_ia32_gatherpfdpd:
3773   case X86::BI__builtin_ia32_gatherpfdps:
3774   case X86::BI__builtin_ia32_gatherpfqpd:
3775   case X86::BI__builtin_ia32_gatherpfqps:
3776   case X86::BI__builtin_ia32_scatterpfdpd:
3777   case X86::BI__builtin_ia32_scatterpfdps:
3778   case X86::BI__builtin_ia32_scatterpfqpd:
3779   case X86::BI__builtin_ia32_scatterpfqps:
3780     ArgNum = 3;
3781     break;
3782   case X86::BI__builtin_ia32_gatherd_pd:
3783   case X86::BI__builtin_ia32_gatherd_pd256:
3784   case X86::BI__builtin_ia32_gatherq_pd:
3785   case X86::BI__builtin_ia32_gatherq_pd256:
3786   case X86::BI__builtin_ia32_gatherd_ps:
3787   case X86::BI__builtin_ia32_gatherd_ps256:
3788   case X86::BI__builtin_ia32_gatherq_ps:
3789   case X86::BI__builtin_ia32_gatherq_ps256:
3790   case X86::BI__builtin_ia32_gatherd_q:
3791   case X86::BI__builtin_ia32_gatherd_q256:
3792   case X86::BI__builtin_ia32_gatherq_q:
3793   case X86::BI__builtin_ia32_gatherq_q256:
3794   case X86::BI__builtin_ia32_gatherd_d:
3795   case X86::BI__builtin_ia32_gatherd_d256:
3796   case X86::BI__builtin_ia32_gatherq_d:
3797   case X86::BI__builtin_ia32_gatherq_d256:
3798   case X86::BI__builtin_ia32_gather3div2df:
3799   case X86::BI__builtin_ia32_gather3div2di:
3800   case X86::BI__builtin_ia32_gather3div4df:
3801   case X86::BI__builtin_ia32_gather3div4di:
3802   case X86::BI__builtin_ia32_gather3div4sf:
3803   case X86::BI__builtin_ia32_gather3div4si:
3804   case X86::BI__builtin_ia32_gather3div8sf:
3805   case X86::BI__builtin_ia32_gather3div8si:
3806   case X86::BI__builtin_ia32_gather3siv2df:
3807   case X86::BI__builtin_ia32_gather3siv2di:
3808   case X86::BI__builtin_ia32_gather3siv4df:
3809   case X86::BI__builtin_ia32_gather3siv4di:
3810   case X86::BI__builtin_ia32_gather3siv4sf:
3811   case X86::BI__builtin_ia32_gather3siv4si:
3812   case X86::BI__builtin_ia32_gather3siv8sf:
3813   case X86::BI__builtin_ia32_gather3siv8si:
3814   case X86::BI__builtin_ia32_gathersiv8df:
3815   case X86::BI__builtin_ia32_gathersiv16sf:
3816   case X86::BI__builtin_ia32_gatherdiv8df:
3817   case X86::BI__builtin_ia32_gatherdiv16sf:
3818   case X86::BI__builtin_ia32_gathersiv8di:
3819   case X86::BI__builtin_ia32_gathersiv16si:
3820   case X86::BI__builtin_ia32_gatherdiv8di:
3821   case X86::BI__builtin_ia32_gatherdiv16si:
3822   case X86::BI__builtin_ia32_scatterdiv2df:
3823   case X86::BI__builtin_ia32_scatterdiv2di:
3824   case X86::BI__builtin_ia32_scatterdiv4df:
3825   case X86::BI__builtin_ia32_scatterdiv4di:
3826   case X86::BI__builtin_ia32_scatterdiv4sf:
3827   case X86::BI__builtin_ia32_scatterdiv4si:
3828   case X86::BI__builtin_ia32_scatterdiv8sf:
3829   case X86::BI__builtin_ia32_scatterdiv8si:
3830   case X86::BI__builtin_ia32_scattersiv2df:
3831   case X86::BI__builtin_ia32_scattersiv2di:
3832   case X86::BI__builtin_ia32_scattersiv4df:
3833   case X86::BI__builtin_ia32_scattersiv4di:
3834   case X86::BI__builtin_ia32_scattersiv4sf:
3835   case X86::BI__builtin_ia32_scattersiv4si:
3836   case X86::BI__builtin_ia32_scattersiv8sf:
3837   case X86::BI__builtin_ia32_scattersiv8si:
3838   case X86::BI__builtin_ia32_scattersiv8df:
3839   case X86::BI__builtin_ia32_scattersiv16sf:
3840   case X86::BI__builtin_ia32_scatterdiv8df:
3841   case X86::BI__builtin_ia32_scatterdiv16sf:
3842   case X86::BI__builtin_ia32_scattersiv8di:
3843   case X86::BI__builtin_ia32_scattersiv16si:
3844   case X86::BI__builtin_ia32_scatterdiv8di:
3845   case X86::BI__builtin_ia32_scatterdiv16si:
3846     ArgNum = 4;
3847     break;
3848   }
3849 
3850   llvm::APSInt Result;
3851 
3852   // We can't check the value of a dependent argument.
3853   Expr *Arg = TheCall->getArg(ArgNum);
3854   if (Arg->isTypeDependent() || Arg->isValueDependent())
3855     return false;
3856 
3857   // Check constant-ness first.
3858   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3859     return true;
3860 
3861   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3862     return false;
3863 
3864   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3865          << Arg->getSourceRange();
3866 }
3867 
3868 enum { TileRegLow = 0, TileRegHigh = 7 };
3869 
3870 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3871                                              ArrayRef<int> ArgNums) {
3872   for (int ArgNum : ArgNums) {
3873     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3874       return true;
3875   }
3876   return false;
3877 }
3878 
3879 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3880                                         ArrayRef<int> ArgNums) {
3881   // Because the max number of tile register is TileRegHigh + 1, so here we use
3882   // each bit to represent the usage of them in bitset.
3883   std::bitset<TileRegHigh + 1> ArgValues;
3884   for (int ArgNum : ArgNums) {
3885     Expr *Arg = TheCall->getArg(ArgNum);
3886     if (Arg->isTypeDependent() || Arg->isValueDependent())
3887       continue;
3888 
3889     llvm::APSInt Result;
3890     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3891       return true;
3892     int ArgExtValue = Result.getExtValue();
3893     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3894            "Incorrect tile register num.");
3895     if (ArgValues.test(ArgExtValue))
3896       return Diag(TheCall->getBeginLoc(),
3897                   diag::err_x86_builtin_tile_arg_duplicate)
3898              << TheCall->getArg(ArgNum)->getSourceRange();
3899     ArgValues.set(ArgExtValue);
3900   }
3901   return false;
3902 }
3903 
3904 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3905                                                 ArrayRef<int> ArgNums) {
3906   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3907          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3908 }
3909 
3910 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3911   switch (BuiltinID) {
3912   default:
3913     return false;
3914   case X86::BI__builtin_ia32_tileloadd64:
3915   case X86::BI__builtin_ia32_tileloaddt164:
3916   case X86::BI__builtin_ia32_tilestored64:
3917   case X86::BI__builtin_ia32_tilezero:
3918     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3919   case X86::BI__builtin_ia32_tdpbssd:
3920   case X86::BI__builtin_ia32_tdpbsud:
3921   case X86::BI__builtin_ia32_tdpbusd:
3922   case X86::BI__builtin_ia32_tdpbuud:
3923   case X86::BI__builtin_ia32_tdpbf16ps:
3924     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3925   }
3926 }
3927 static bool isX86_32Builtin(unsigned BuiltinID) {
3928   // These builtins only work on x86-32 targets.
3929   switch (BuiltinID) {
3930   case X86::BI__builtin_ia32_readeflags_u32:
3931   case X86::BI__builtin_ia32_writeeflags_u32:
3932     return true;
3933   }
3934 
3935   return false;
3936 }
3937 
3938 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3939                                        CallExpr *TheCall) {
3940   if (BuiltinID == X86::BI__builtin_cpu_supports)
3941     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3942 
3943   if (BuiltinID == X86::BI__builtin_cpu_is)
3944     return SemaBuiltinCpuIs(*this, TI, TheCall);
3945 
3946   // Check for 32-bit only builtins on a 64-bit target.
3947   const llvm::Triple &TT = TI.getTriple();
3948   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3949     return Diag(TheCall->getCallee()->getBeginLoc(),
3950                 diag::err_32_bit_builtin_64_bit_tgt);
3951 
3952   // If the intrinsic has rounding or SAE make sure its valid.
3953   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3954     return true;
3955 
3956   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3957   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3958     return true;
3959 
3960   // If the intrinsic has a tile arguments, make sure they are valid.
3961   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3962     return true;
3963 
3964   // For intrinsics which take an immediate value as part of the instruction,
3965   // range check them here.
3966   int i = 0, l = 0, u = 0;
3967   switch (BuiltinID) {
3968   default:
3969     return false;
3970   case X86::BI__builtin_ia32_vec_ext_v2si:
3971   case X86::BI__builtin_ia32_vec_ext_v2di:
3972   case X86::BI__builtin_ia32_vextractf128_pd256:
3973   case X86::BI__builtin_ia32_vextractf128_ps256:
3974   case X86::BI__builtin_ia32_vextractf128_si256:
3975   case X86::BI__builtin_ia32_extract128i256:
3976   case X86::BI__builtin_ia32_extractf64x4_mask:
3977   case X86::BI__builtin_ia32_extracti64x4_mask:
3978   case X86::BI__builtin_ia32_extractf32x8_mask:
3979   case X86::BI__builtin_ia32_extracti32x8_mask:
3980   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3981   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3982   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3983   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3984     i = 1; l = 0; u = 1;
3985     break;
3986   case X86::BI__builtin_ia32_vec_set_v2di:
3987   case X86::BI__builtin_ia32_vinsertf128_pd256:
3988   case X86::BI__builtin_ia32_vinsertf128_ps256:
3989   case X86::BI__builtin_ia32_vinsertf128_si256:
3990   case X86::BI__builtin_ia32_insert128i256:
3991   case X86::BI__builtin_ia32_insertf32x8:
3992   case X86::BI__builtin_ia32_inserti32x8:
3993   case X86::BI__builtin_ia32_insertf64x4:
3994   case X86::BI__builtin_ia32_inserti64x4:
3995   case X86::BI__builtin_ia32_insertf64x2_256:
3996   case X86::BI__builtin_ia32_inserti64x2_256:
3997   case X86::BI__builtin_ia32_insertf32x4_256:
3998   case X86::BI__builtin_ia32_inserti32x4_256:
3999     i = 2; l = 0; u = 1;
4000     break;
4001   case X86::BI__builtin_ia32_vpermilpd:
4002   case X86::BI__builtin_ia32_vec_ext_v4hi:
4003   case X86::BI__builtin_ia32_vec_ext_v4si:
4004   case X86::BI__builtin_ia32_vec_ext_v4sf:
4005   case X86::BI__builtin_ia32_vec_ext_v4di:
4006   case X86::BI__builtin_ia32_extractf32x4_mask:
4007   case X86::BI__builtin_ia32_extracti32x4_mask:
4008   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4009   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4010     i = 1; l = 0; u = 3;
4011     break;
4012   case X86::BI_mm_prefetch:
4013   case X86::BI__builtin_ia32_vec_ext_v8hi:
4014   case X86::BI__builtin_ia32_vec_ext_v8si:
4015     i = 1; l = 0; u = 7;
4016     break;
4017   case X86::BI__builtin_ia32_sha1rnds4:
4018   case X86::BI__builtin_ia32_blendpd:
4019   case X86::BI__builtin_ia32_shufpd:
4020   case X86::BI__builtin_ia32_vec_set_v4hi:
4021   case X86::BI__builtin_ia32_vec_set_v4si:
4022   case X86::BI__builtin_ia32_vec_set_v4di:
4023   case X86::BI__builtin_ia32_shuf_f32x4_256:
4024   case X86::BI__builtin_ia32_shuf_f64x2_256:
4025   case X86::BI__builtin_ia32_shuf_i32x4_256:
4026   case X86::BI__builtin_ia32_shuf_i64x2_256:
4027   case X86::BI__builtin_ia32_insertf64x2_512:
4028   case X86::BI__builtin_ia32_inserti64x2_512:
4029   case X86::BI__builtin_ia32_insertf32x4:
4030   case X86::BI__builtin_ia32_inserti32x4:
4031     i = 2; l = 0; u = 3;
4032     break;
4033   case X86::BI__builtin_ia32_vpermil2pd:
4034   case X86::BI__builtin_ia32_vpermil2pd256:
4035   case X86::BI__builtin_ia32_vpermil2ps:
4036   case X86::BI__builtin_ia32_vpermil2ps256:
4037     i = 3; l = 0; u = 3;
4038     break;
4039   case X86::BI__builtin_ia32_cmpb128_mask:
4040   case X86::BI__builtin_ia32_cmpw128_mask:
4041   case X86::BI__builtin_ia32_cmpd128_mask:
4042   case X86::BI__builtin_ia32_cmpq128_mask:
4043   case X86::BI__builtin_ia32_cmpb256_mask:
4044   case X86::BI__builtin_ia32_cmpw256_mask:
4045   case X86::BI__builtin_ia32_cmpd256_mask:
4046   case X86::BI__builtin_ia32_cmpq256_mask:
4047   case X86::BI__builtin_ia32_cmpb512_mask:
4048   case X86::BI__builtin_ia32_cmpw512_mask:
4049   case X86::BI__builtin_ia32_cmpd512_mask:
4050   case X86::BI__builtin_ia32_cmpq512_mask:
4051   case X86::BI__builtin_ia32_ucmpb128_mask:
4052   case X86::BI__builtin_ia32_ucmpw128_mask:
4053   case X86::BI__builtin_ia32_ucmpd128_mask:
4054   case X86::BI__builtin_ia32_ucmpq128_mask:
4055   case X86::BI__builtin_ia32_ucmpb256_mask:
4056   case X86::BI__builtin_ia32_ucmpw256_mask:
4057   case X86::BI__builtin_ia32_ucmpd256_mask:
4058   case X86::BI__builtin_ia32_ucmpq256_mask:
4059   case X86::BI__builtin_ia32_ucmpb512_mask:
4060   case X86::BI__builtin_ia32_ucmpw512_mask:
4061   case X86::BI__builtin_ia32_ucmpd512_mask:
4062   case X86::BI__builtin_ia32_ucmpq512_mask:
4063   case X86::BI__builtin_ia32_vpcomub:
4064   case X86::BI__builtin_ia32_vpcomuw:
4065   case X86::BI__builtin_ia32_vpcomud:
4066   case X86::BI__builtin_ia32_vpcomuq:
4067   case X86::BI__builtin_ia32_vpcomb:
4068   case X86::BI__builtin_ia32_vpcomw:
4069   case X86::BI__builtin_ia32_vpcomd:
4070   case X86::BI__builtin_ia32_vpcomq:
4071   case X86::BI__builtin_ia32_vec_set_v8hi:
4072   case X86::BI__builtin_ia32_vec_set_v8si:
4073     i = 2; l = 0; u = 7;
4074     break;
4075   case X86::BI__builtin_ia32_vpermilpd256:
4076   case X86::BI__builtin_ia32_roundps:
4077   case X86::BI__builtin_ia32_roundpd:
4078   case X86::BI__builtin_ia32_roundps256:
4079   case X86::BI__builtin_ia32_roundpd256:
4080   case X86::BI__builtin_ia32_getmantpd128_mask:
4081   case X86::BI__builtin_ia32_getmantpd256_mask:
4082   case X86::BI__builtin_ia32_getmantps128_mask:
4083   case X86::BI__builtin_ia32_getmantps256_mask:
4084   case X86::BI__builtin_ia32_getmantpd512_mask:
4085   case X86::BI__builtin_ia32_getmantps512_mask:
4086   case X86::BI__builtin_ia32_vec_ext_v16qi:
4087   case X86::BI__builtin_ia32_vec_ext_v16hi:
4088     i = 1; l = 0; u = 15;
4089     break;
4090   case X86::BI__builtin_ia32_pblendd128:
4091   case X86::BI__builtin_ia32_blendps:
4092   case X86::BI__builtin_ia32_blendpd256:
4093   case X86::BI__builtin_ia32_shufpd256:
4094   case X86::BI__builtin_ia32_roundss:
4095   case X86::BI__builtin_ia32_roundsd:
4096   case X86::BI__builtin_ia32_rangepd128_mask:
4097   case X86::BI__builtin_ia32_rangepd256_mask:
4098   case X86::BI__builtin_ia32_rangepd512_mask:
4099   case X86::BI__builtin_ia32_rangeps128_mask:
4100   case X86::BI__builtin_ia32_rangeps256_mask:
4101   case X86::BI__builtin_ia32_rangeps512_mask:
4102   case X86::BI__builtin_ia32_getmantsd_round_mask:
4103   case X86::BI__builtin_ia32_getmantss_round_mask:
4104   case X86::BI__builtin_ia32_vec_set_v16qi:
4105   case X86::BI__builtin_ia32_vec_set_v16hi:
4106     i = 2; l = 0; u = 15;
4107     break;
4108   case X86::BI__builtin_ia32_vec_ext_v32qi:
4109     i = 1; l = 0; u = 31;
4110     break;
4111   case X86::BI__builtin_ia32_cmpps:
4112   case X86::BI__builtin_ia32_cmpss:
4113   case X86::BI__builtin_ia32_cmppd:
4114   case X86::BI__builtin_ia32_cmpsd:
4115   case X86::BI__builtin_ia32_cmpps256:
4116   case X86::BI__builtin_ia32_cmppd256:
4117   case X86::BI__builtin_ia32_cmpps128_mask:
4118   case X86::BI__builtin_ia32_cmppd128_mask:
4119   case X86::BI__builtin_ia32_cmpps256_mask:
4120   case X86::BI__builtin_ia32_cmppd256_mask:
4121   case X86::BI__builtin_ia32_cmpps512_mask:
4122   case X86::BI__builtin_ia32_cmppd512_mask:
4123   case X86::BI__builtin_ia32_cmpsd_mask:
4124   case X86::BI__builtin_ia32_cmpss_mask:
4125   case X86::BI__builtin_ia32_vec_set_v32qi:
4126     i = 2; l = 0; u = 31;
4127     break;
4128   case X86::BI__builtin_ia32_permdf256:
4129   case X86::BI__builtin_ia32_permdi256:
4130   case X86::BI__builtin_ia32_permdf512:
4131   case X86::BI__builtin_ia32_permdi512:
4132   case X86::BI__builtin_ia32_vpermilps:
4133   case X86::BI__builtin_ia32_vpermilps256:
4134   case X86::BI__builtin_ia32_vpermilpd512:
4135   case X86::BI__builtin_ia32_vpermilps512:
4136   case X86::BI__builtin_ia32_pshufd:
4137   case X86::BI__builtin_ia32_pshufd256:
4138   case X86::BI__builtin_ia32_pshufd512:
4139   case X86::BI__builtin_ia32_pshufhw:
4140   case X86::BI__builtin_ia32_pshufhw256:
4141   case X86::BI__builtin_ia32_pshufhw512:
4142   case X86::BI__builtin_ia32_pshuflw:
4143   case X86::BI__builtin_ia32_pshuflw256:
4144   case X86::BI__builtin_ia32_pshuflw512:
4145   case X86::BI__builtin_ia32_vcvtps2ph:
4146   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4147   case X86::BI__builtin_ia32_vcvtps2ph256:
4148   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4149   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4150   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4151   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4152   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4153   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4154   case X86::BI__builtin_ia32_rndscaleps_mask:
4155   case X86::BI__builtin_ia32_rndscalepd_mask:
4156   case X86::BI__builtin_ia32_reducepd128_mask:
4157   case X86::BI__builtin_ia32_reducepd256_mask:
4158   case X86::BI__builtin_ia32_reducepd512_mask:
4159   case X86::BI__builtin_ia32_reduceps128_mask:
4160   case X86::BI__builtin_ia32_reduceps256_mask:
4161   case X86::BI__builtin_ia32_reduceps512_mask:
4162   case X86::BI__builtin_ia32_prold512:
4163   case X86::BI__builtin_ia32_prolq512:
4164   case X86::BI__builtin_ia32_prold128:
4165   case X86::BI__builtin_ia32_prold256:
4166   case X86::BI__builtin_ia32_prolq128:
4167   case X86::BI__builtin_ia32_prolq256:
4168   case X86::BI__builtin_ia32_prord512:
4169   case X86::BI__builtin_ia32_prorq512:
4170   case X86::BI__builtin_ia32_prord128:
4171   case X86::BI__builtin_ia32_prord256:
4172   case X86::BI__builtin_ia32_prorq128:
4173   case X86::BI__builtin_ia32_prorq256:
4174   case X86::BI__builtin_ia32_fpclasspd128_mask:
4175   case X86::BI__builtin_ia32_fpclasspd256_mask:
4176   case X86::BI__builtin_ia32_fpclassps128_mask:
4177   case X86::BI__builtin_ia32_fpclassps256_mask:
4178   case X86::BI__builtin_ia32_fpclassps512_mask:
4179   case X86::BI__builtin_ia32_fpclasspd512_mask:
4180   case X86::BI__builtin_ia32_fpclasssd_mask:
4181   case X86::BI__builtin_ia32_fpclassss_mask:
4182   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4183   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4184   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4185   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4186   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4187   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4188   case X86::BI__builtin_ia32_kshiftliqi:
4189   case X86::BI__builtin_ia32_kshiftlihi:
4190   case X86::BI__builtin_ia32_kshiftlisi:
4191   case X86::BI__builtin_ia32_kshiftlidi:
4192   case X86::BI__builtin_ia32_kshiftriqi:
4193   case X86::BI__builtin_ia32_kshiftrihi:
4194   case X86::BI__builtin_ia32_kshiftrisi:
4195   case X86::BI__builtin_ia32_kshiftridi:
4196     i = 1; l = 0; u = 255;
4197     break;
4198   case X86::BI__builtin_ia32_vperm2f128_pd256:
4199   case X86::BI__builtin_ia32_vperm2f128_ps256:
4200   case X86::BI__builtin_ia32_vperm2f128_si256:
4201   case X86::BI__builtin_ia32_permti256:
4202   case X86::BI__builtin_ia32_pblendw128:
4203   case X86::BI__builtin_ia32_pblendw256:
4204   case X86::BI__builtin_ia32_blendps256:
4205   case X86::BI__builtin_ia32_pblendd256:
4206   case X86::BI__builtin_ia32_palignr128:
4207   case X86::BI__builtin_ia32_palignr256:
4208   case X86::BI__builtin_ia32_palignr512:
4209   case X86::BI__builtin_ia32_alignq512:
4210   case X86::BI__builtin_ia32_alignd512:
4211   case X86::BI__builtin_ia32_alignd128:
4212   case X86::BI__builtin_ia32_alignd256:
4213   case X86::BI__builtin_ia32_alignq128:
4214   case X86::BI__builtin_ia32_alignq256:
4215   case X86::BI__builtin_ia32_vcomisd:
4216   case X86::BI__builtin_ia32_vcomiss:
4217   case X86::BI__builtin_ia32_shuf_f32x4:
4218   case X86::BI__builtin_ia32_shuf_f64x2:
4219   case X86::BI__builtin_ia32_shuf_i32x4:
4220   case X86::BI__builtin_ia32_shuf_i64x2:
4221   case X86::BI__builtin_ia32_shufpd512:
4222   case X86::BI__builtin_ia32_shufps:
4223   case X86::BI__builtin_ia32_shufps256:
4224   case X86::BI__builtin_ia32_shufps512:
4225   case X86::BI__builtin_ia32_dbpsadbw128:
4226   case X86::BI__builtin_ia32_dbpsadbw256:
4227   case X86::BI__builtin_ia32_dbpsadbw512:
4228   case X86::BI__builtin_ia32_vpshldd128:
4229   case X86::BI__builtin_ia32_vpshldd256:
4230   case X86::BI__builtin_ia32_vpshldd512:
4231   case X86::BI__builtin_ia32_vpshldq128:
4232   case X86::BI__builtin_ia32_vpshldq256:
4233   case X86::BI__builtin_ia32_vpshldq512:
4234   case X86::BI__builtin_ia32_vpshldw128:
4235   case X86::BI__builtin_ia32_vpshldw256:
4236   case X86::BI__builtin_ia32_vpshldw512:
4237   case X86::BI__builtin_ia32_vpshrdd128:
4238   case X86::BI__builtin_ia32_vpshrdd256:
4239   case X86::BI__builtin_ia32_vpshrdd512:
4240   case X86::BI__builtin_ia32_vpshrdq128:
4241   case X86::BI__builtin_ia32_vpshrdq256:
4242   case X86::BI__builtin_ia32_vpshrdq512:
4243   case X86::BI__builtin_ia32_vpshrdw128:
4244   case X86::BI__builtin_ia32_vpshrdw256:
4245   case X86::BI__builtin_ia32_vpshrdw512:
4246     i = 2; l = 0; u = 255;
4247     break;
4248   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4249   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4250   case X86::BI__builtin_ia32_fixupimmps512_mask:
4251   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4252   case X86::BI__builtin_ia32_fixupimmsd_mask:
4253   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4254   case X86::BI__builtin_ia32_fixupimmss_mask:
4255   case X86::BI__builtin_ia32_fixupimmss_maskz:
4256   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4257   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4258   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4259   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4260   case X86::BI__builtin_ia32_fixupimmps128_mask:
4261   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4262   case X86::BI__builtin_ia32_fixupimmps256_mask:
4263   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4264   case X86::BI__builtin_ia32_pternlogd512_mask:
4265   case X86::BI__builtin_ia32_pternlogd512_maskz:
4266   case X86::BI__builtin_ia32_pternlogq512_mask:
4267   case X86::BI__builtin_ia32_pternlogq512_maskz:
4268   case X86::BI__builtin_ia32_pternlogd128_mask:
4269   case X86::BI__builtin_ia32_pternlogd128_maskz:
4270   case X86::BI__builtin_ia32_pternlogd256_mask:
4271   case X86::BI__builtin_ia32_pternlogd256_maskz:
4272   case X86::BI__builtin_ia32_pternlogq128_mask:
4273   case X86::BI__builtin_ia32_pternlogq128_maskz:
4274   case X86::BI__builtin_ia32_pternlogq256_mask:
4275   case X86::BI__builtin_ia32_pternlogq256_maskz:
4276     i = 3; l = 0; u = 255;
4277     break;
4278   case X86::BI__builtin_ia32_gatherpfdpd:
4279   case X86::BI__builtin_ia32_gatherpfdps:
4280   case X86::BI__builtin_ia32_gatherpfqpd:
4281   case X86::BI__builtin_ia32_gatherpfqps:
4282   case X86::BI__builtin_ia32_scatterpfdpd:
4283   case X86::BI__builtin_ia32_scatterpfdps:
4284   case X86::BI__builtin_ia32_scatterpfqpd:
4285   case X86::BI__builtin_ia32_scatterpfqps:
4286     i = 4; l = 2; u = 3;
4287     break;
4288   case X86::BI__builtin_ia32_reducesd_mask:
4289   case X86::BI__builtin_ia32_reducess_mask:
4290   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4291   case X86::BI__builtin_ia32_rndscaless_round_mask:
4292     i = 4; l = 0; u = 255;
4293     break;
4294   }
4295 
4296   // Note that we don't force a hard error on the range check here, allowing
4297   // template-generated or macro-generated dead code to potentially have out-of-
4298   // range values. These need to code generate, but don't need to necessarily
4299   // make any sense. We use a warning that defaults to an error.
4300   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4301 }
4302 
4303 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4304 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4305 /// Returns true when the format fits the function and the FormatStringInfo has
4306 /// been populated.
4307 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4308                                FormatStringInfo *FSI) {
4309   FSI->HasVAListArg = Format->getFirstArg() == 0;
4310   FSI->FormatIdx = Format->getFormatIdx() - 1;
4311   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4312 
4313   // The way the format attribute works in GCC, the implicit this argument
4314   // of member functions is counted. However, it doesn't appear in our own
4315   // lists, so decrement format_idx in that case.
4316   if (IsCXXMember) {
4317     if(FSI->FormatIdx == 0)
4318       return false;
4319     --FSI->FormatIdx;
4320     if (FSI->FirstDataArg != 0)
4321       --FSI->FirstDataArg;
4322   }
4323   return true;
4324 }
4325 
4326 /// Checks if a the given expression evaluates to null.
4327 ///
4328 /// Returns true if the value evaluates to null.
4329 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4330   // If the expression has non-null type, it doesn't evaluate to null.
4331   if (auto nullability
4332         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4333     if (*nullability == NullabilityKind::NonNull)
4334       return false;
4335   }
4336 
4337   // As a special case, transparent unions initialized with zero are
4338   // considered null for the purposes of the nonnull attribute.
4339   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4340     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4341       if (const CompoundLiteralExpr *CLE =
4342           dyn_cast<CompoundLiteralExpr>(Expr))
4343         if (const InitListExpr *ILE =
4344             dyn_cast<InitListExpr>(CLE->getInitializer()))
4345           Expr = ILE->getInit(0);
4346   }
4347 
4348   bool Result;
4349   return (!Expr->isValueDependent() &&
4350           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4351           !Result);
4352 }
4353 
4354 static void CheckNonNullArgument(Sema &S,
4355                                  const Expr *ArgExpr,
4356                                  SourceLocation CallSiteLoc) {
4357   if (CheckNonNullExpr(S, ArgExpr))
4358     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4359                           S.PDiag(diag::warn_null_arg)
4360                               << ArgExpr->getSourceRange());
4361 }
4362 
4363 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4364   FormatStringInfo FSI;
4365   if ((GetFormatStringType(Format) == FST_NSString) &&
4366       getFormatStringInfo(Format, false, &FSI)) {
4367     Idx = FSI.FormatIdx;
4368     return true;
4369   }
4370   return false;
4371 }
4372 
4373 /// Diagnose use of %s directive in an NSString which is being passed
4374 /// as formatting string to formatting method.
4375 static void
4376 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4377                                         const NamedDecl *FDecl,
4378                                         Expr **Args,
4379                                         unsigned NumArgs) {
4380   unsigned Idx = 0;
4381   bool Format = false;
4382   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4383   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4384     Idx = 2;
4385     Format = true;
4386   }
4387   else
4388     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4389       if (S.GetFormatNSStringIdx(I, Idx)) {
4390         Format = true;
4391         break;
4392       }
4393     }
4394   if (!Format || NumArgs <= Idx)
4395     return;
4396   const Expr *FormatExpr = Args[Idx];
4397   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4398     FormatExpr = CSCE->getSubExpr();
4399   const StringLiteral *FormatString;
4400   if (const ObjCStringLiteral *OSL =
4401       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4402     FormatString = OSL->getString();
4403   else
4404     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4405   if (!FormatString)
4406     return;
4407   if (S.FormatStringHasSArg(FormatString)) {
4408     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4409       << "%s" << 1 << 1;
4410     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4411       << FDecl->getDeclName();
4412   }
4413 }
4414 
4415 /// Determine whether the given type has a non-null nullability annotation.
4416 static bool isNonNullType(ASTContext &ctx, QualType type) {
4417   if (auto nullability = type->getNullability(ctx))
4418     return *nullability == NullabilityKind::NonNull;
4419 
4420   return false;
4421 }
4422 
4423 static void CheckNonNullArguments(Sema &S,
4424                                   const NamedDecl *FDecl,
4425                                   const FunctionProtoType *Proto,
4426                                   ArrayRef<const Expr *> Args,
4427                                   SourceLocation CallSiteLoc) {
4428   assert((FDecl || Proto) && "Need a function declaration or prototype");
4429 
4430   // Already checked by by constant evaluator.
4431   if (S.isConstantEvaluated())
4432     return;
4433   // Check the attributes attached to the method/function itself.
4434   llvm::SmallBitVector NonNullArgs;
4435   if (FDecl) {
4436     // Handle the nonnull attribute on the function/method declaration itself.
4437     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4438       if (!NonNull->args_size()) {
4439         // Easy case: all pointer arguments are nonnull.
4440         for (const auto *Arg : Args)
4441           if (S.isValidPointerAttrType(Arg->getType()))
4442             CheckNonNullArgument(S, Arg, CallSiteLoc);
4443         return;
4444       }
4445 
4446       for (const ParamIdx &Idx : NonNull->args()) {
4447         unsigned IdxAST = Idx.getASTIndex();
4448         if (IdxAST >= Args.size())
4449           continue;
4450         if (NonNullArgs.empty())
4451           NonNullArgs.resize(Args.size());
4452         NonNullArgs.set(IdxAST);
4453       }
4454     }
4455   }
4456 
4457   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4458     // Handle the nonnull attribute on the parameters of the
4459     // function/method.
4460     ArrayRef<ParmVarDecl*> parms;
4461     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4462       parms = FD->parameters();
4463     else
4464       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4465 
4466     unsigned ParamIndex = 0;
4467     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4468          I != E; ++I, ++ParamIndex) {
4469       const ParmVarDecl *PVD = *I;
4470       if (PVD->hasAttr<NonNullAttr>() ||
4471           isNonNullType(S.Context, PVD->getType())) {
4472         if (NonNullArgs.empty())
4473           NonNullArgs.resize(Args.size());
4474 
4475         NonNullArgs.set(ParamIndex);
4476       }
4477     }
4478   } else {
4479     // If we have a non-function, non-method declaration but no
4480     // function prototype, try to dig out the function prototype.
4481     if (!Proto) {
4482       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4483         QualType type = VD->getType().getNonReferenceType();
4484         if (auto pointerType = type->getAs<PointerType>())
4485           type = pointerType->getPointeeType();
4486         else if (auto blockType = type->getAs<BlockPointerType>())
4487           type = blockType->getPointeeType();
4488         // FIXME: data member pointers?
4489 
4490         // Dig out the function prototype, if there is one.
4491         Proto = type->getAs<FunctionProtoType>();
4492       }
4493     }
4494 
4495     // Fill in non-null argument information from the nullability
4496     // information on the parameter types (if we have them).
4497     if (Proto) {
4498       unsigned Index = 0;
4499       for (auto paramType : Proto->getParamTypes()) {
4500         if (isNonNullType(S.Context, paramType)) {
4501           if (NonNullArgs.empty())
4502             NonNullArgs.resize(Args.size());
4503 
4504           NonNullArgs.set(Index);
4505         }
4506 
4507         ++Index;
4508       }
4509     }
4510   }
4511 
4512   // Check for non-null arguments.
4513   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4514        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4515     if (NonNullArgs[ArgIndex])
4516       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4517   }
4518 }
4519 
4520 /// Warn if a pointer or reference argument passed to a function points to an
4521 /// object that is less aligned than the parameter. This can happen when
4522 /// creating a typedef with a lower alignment than the original type and then
4523 /// calling functions defined in terms of the original type.
4524 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4525                              StringRef ParamName, QualType ArgTy,
4526                              QualType ParamTy) {
4527 
4528   // If a function accepts a pointer or reference type
4529   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4530     return;
4531 
4532   // If the parameter is a pointer type, get the pointee type for the
4533   // argument too. If the parameter is a reference type, don't try to get
4534   // the pointee type for the argument.
4535   if (ParamTy->isPointerType())
4536     ArgTy = ArgTy->getPointeeType();
4537 
4538   // Remove reference or pointer
4539   ParamTy = ParamTy->getPointeeType();
4540 
4541   // Find expected alignment, and the actual alignment of the passed object.
4542   // getTypeAlignInChars requires complete types
4543   if (ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4544       ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4545     return;
4546 
4547   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4548   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4549 
4550   // If the argument is less aligned than the parameter, there is a
4551   // potential alignment issue.
4552   if (ArgAlign < ParamAlign)
4553     Diag(Loc, diag::warn_param_mismatched_alignment)
4554         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4555         << ParamName << FDecl;
4556 }
4557 
4558 /// Handles the checks for format strings, non-POD arguments to vararg
4559 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4560 /// attributes.
4561 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4562                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4563                      bool IsMemberFunction, SourceLocation Loc,
4564                      SourceRange Range, VariadicCallType CallType) {
4565   // FIXME: We should check as much as we can in the template definition.
4566   if (CurContext->isDependentContext())
4567     return;
4568 
4569   // Printf and scanf checking.
4570   llvm::SmallBitVector CheckedVarArgs;
4571   if (FDecl) {
4572     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4573       // Only create vector if there are format attributes.
4574       CheckedVarArgs.resize(Args.size());
4575 
4576       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4577                            CheckedVarArgs);
4578     }
4579   }
4580 
4581   // Refuse POD arguments that weren't caught by the format string
4582   // checks above.
4583   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4584   if (CallType != VariadicDoesNotApply &&
4585       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4586     unsigned NumParams = Proto ? Proto->getNumParams()
4587                        : FDecl && isa<FunctionDecl>(FDecl)
4588                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4589                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4590                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4591                        : 0;
4592 
4593     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4594       // Args[ArgIdx] can be null in malformed code.
4595       if (const Expr *Arg = Args[ArgIdx]) {
4596         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4597           checkVariadicArgument(Arg, CallType);
4598       }
4599     }
4600   }
4601 
4602   if (FDecl || Proto) {
4603     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4604 
4605     // Type safety checking.
4606     if (FDecl) {
4607       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4608         CheckArgumentWithTypeTag(I, Args, Loc);
4609     }
4610   }
4611 
4612   // Check that passed arguments match the alignment of original arguments.
4613   // Try to get the missing prototype from the declaration.
4614   if (!Proto && FDecl) {
4615     const auto *FT = FDecl->getFunctionType();
4616     if (isa_and_nonnull<FunctionProtoType>(FT))
4617       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4618   }
4619   if (Proto) {
4620     // For variadic functions, we may have more args than parameters.
4621     // For some K&R functions, we may have less args than parameters.
4622     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4623     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4624       // Args[ArgIdx] can be null in malformed code.
4625       if (const Expr *Arg = Args[ArgIdx]) {
4626         QualType ParamTy = Proto->getParamType(ArgIdx);
4627         QualType ArgTy = Arg->getType();
4628         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4629                           ArgTy, ParamTy);
4630       }
4631     }
4632   }
4633 
4634   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4635     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4636     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4637     if (!Arg->isValueDependent()) {
4638       Expr::EvalResult Align;
4639       if (Arg->EvaluateAsInt(Align, Context)) {
4640         const llvm::APSInt &I = Align.Val.getInt();
4641         if (!I.isPowerOf2())
4642           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4643               << Arg->getSourceRange();
4644 
4645         if (I > Sema::MaximumAlignment)
4646           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4647               << Arg->getSourceRange() << Sema::MaximumAlignment;
4648       }
4649     }
4650   }
4651 
4652   if (FD)
4653     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4654 }
4655 
4656 /// CheckConstructorCall - Check a constructor call for correctness and safety
4657 /// properties not enforced by the C type system.
4658 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4659                                 ArrayRef<const Expr *> Args,
4660                                 const FunctionProtoType *Proto,
4661                                 SourceLocation Loc) {
4662   VariadicCallType CallType =
4663       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4664 
4665   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4666   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4667                     Context.getPointerType(Ctor->getThisObjectType()));
4668 
4669   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4670             Loc, SourceRange(), CallType);
4671 }
4672 
4673 /// CheckFunctionCall - Check a direct function call for various correctness
4674 /// and safety properties not strictly enforced by the C type system.
4675 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4676                              const FunctionProtoType *Proto) {
4677   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4678                               isa<CXXMethodDecl>(FDecl);
4679   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4680                           IsMemberOperatorCall;
4681   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4682                                                   TheCall->getCallee());
4683   Expr** Args = TheCall->getArgs();
4684   unsigned NumArgs = TheCall->getNumArgs();
4685 
4686   Expr *ImplicitThis = nullptr;
4687   if (IsMemberOperatorCall) {
4688     // If this is a call to a member operator, hide the first argument
4689     // from checkCall.
4690     // FIXME: Our choice of AST representation here is less than ideal.
4691     ImplicitThis = Args[0];
4692     ++Args;
4693     --NumArgs;
4694   } else if (IsMemberFunction)
4695     ImplicitThis =
4696         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4697 
4698   if (ImplicitThis) {
4699     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4700     // used.
4701     QualType ThisType = ImplicitThis->getType();
4702     if (!ThisType->isPointerType()) {
4703       assert(!ThisType->isReferenceType());
4704       ThisType = Context.getPointerType(ThisType);
4705     }
4706 
4707     QualType ThisTypeFromDecl =
4708         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4709 
4710     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4711                       ThisTypeFromDecl);
4712   }
4713 
4714   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4715             IsMemberFunction, TheCall->getRParenLoc(),
4716             TheCall->getCallee()->getSourceRange(), CallType);
4717 
4718   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4719   // None of the checks below are needed for functions that don't have
4720   // simple names (e.g., C++ conversion functions).
4721   if (!FnInfo)
4722     return false;
4723 
4724   CheckTCBEnforcement(TheCall, FDecl);
4725 
4726   CheckAbsoluteValueFunction(TheCall, FDecl);
4727   CheckMaxUnsignedZero(TheCall, FDecl);
4728 
4729   if (getLangOpts().ObjC)
4730     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4731 
4732   unsigned CMId = FDecl->getMemoryFunctionKind();
4733 
4734   // Handle memory setting and copying functions.
4735   switch (CMId) {
4736   case 0:
4737     return false;
4738   case Builtin::BIstrlcpy: // fallthrough
4739   case Builtin::BIstrlcat:
4740     CheckStrlcpycatArguments(TheCall, FnInfo);
4741     break;
4742   case Builtin::BIstrncat:
4743     CheckStrncatArguments(TheCall, FnInfo);
4744     break;
4745   case Builtin::BIfree:
4746     CheckFreeArguments(TheCall);
4747     break;
4748   default:
4749     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4750   }
4751 
4752   return false;
4753 }
4754 
4755 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4756                                ArrayRef<const Expr *> Args) {
4757   VariadicCallType CallType =
4758       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4759 
4760   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4761             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4762             CallType);
4763 
4764   return false;
4765 }
4766 
4767 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4768                             const FunctionProtoType *Proto) {
4769   QualType Ty;
4770   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4771     Ty = V->getType().getNonReferenceType();
4772   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4773     Ty = F->getType().getNonReferenceType();
4774   else
4775     return false;
4776 
4777   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4778       !Ty->isFunctionProtoType())
4779     return false;
4780 
4781   VariadicCallType CallType;
4782   if (!Proto || !Proto->isVariadic()) {
4783     CallType = VariadicDoesNotApply;
4784   } else if (Ty->isBlockPointerType()) {
4785     CallType = VariadicBlock;
4786   } else { // Ty->isFunctionPointerType()
4787     CallType = VariadicFunction;
4788   }
4789 
4790   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4791             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4792             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4793             TheCall->getCallee()->getSourceRange(), CallType);
4794 
4795   return false;
4796 }
4797 
4798 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4799 /// such as function pointers returned from functions.
4800 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4801   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4802                                                   TheCall->getCallee());
4803   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4804             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4805             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4806             TheCall->getCallee()->getSourceRange(), CallType);
4807 
4808   return false;
4809 }
4810 
4811 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4812   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4813     return false;
4814 
4815   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4816   switch (Op) {
4817   case AtomicExpr::AO__c11_atomic_init:
4818   case AtomicExpr::AO__opencl_atomic_init:
4819     llvm_unreachable("There is no ordering argument for an init");
4820 
4821   case AtomicExpr::AO__c11_atomic_load:
4822   case AtomicExpr::AO__opencl_atomic_load:
4823   case AtomicExpr::AO__atomic_load_n:
4824   case AtomicExpr::AO__atomic_load:
4825     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4826            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4827 
4828   case AtomicExpr::AO__c11_atomic_store:
4829   case AtomicExpr::AO__opencl_atomic_store:
4830   case AtomicExpr::AO__atomic_store:
4831   case AtomicExpr::AO__atomic_store_n:
4832     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4833            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4834            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4835 
4836   default:
4837     return true;
4838   }
4839 }
4840 
4841 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4842                                          AtomicExpr::AtomicOp Op) {
4843   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4844   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4845   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4846   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4847                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4848                          Op);
4849 }
4850 
4851 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4852                                  SourceLocation RParenLoc, MultiExprArg Args,
4853                                  AtomicExpr::AtomicOp Op,
4854                                  AtomicArgumentOrder ArgOrder) {
4855   // All the non-OpenCL operations take one of the following forms.
4856   // The OpenCL operations take the __c11 forms with one extra argument for
4857   // synchronization scope.
4858   enum {
4859     // C    __c11_atomic_init(A *, C)
4860     Init,
4861 
4862     // C    __c11_atomic_load(A *, int)
4863     Load,
4864 
4865     // void __atomic_load(A *, CP, int)
4866     LoadCopy,
4867 
4868     // void __atomic_store(A *, CP, int)
4869     Copy,
4870 
4871     // C    __c11_atomic_add(A *, M, int)
4872     Arithmetic,
4873 
4874     // C    __atomic_exchange_n(A *, CP, int)
4875     Xchg,
4876 
4877     // void __atomic_exchange(A *, C *, CP, int)
4878     GNUXchg,
4879 
4880     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4881     C11CmpXchg,
4882 
4883     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4884     GNUCmpXchg
4885   } Form = Init;
4886 
4887   const unsigned NumForm = GNUCmpXchg + 1;
4888   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4889   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4890   // where:
4891   //   C is an appropriate type,
4892   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4893   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4894   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4895   //   the int parameters are for orderings.
4896 
4897   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4898       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4899       "need to update code for modified forms");
4900   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4901                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4902                         AtomicExpr::AO__atomic_load,
4903                 "need to update code for modified C11 atomics");
4904   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4905                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4906   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4907                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4908                IsOpenCL;
4909   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4910              Op == AtomicExpr::AO__atomic_store_n ||
4911              Op == AtomicExpr::AO__atomic_exchange_n ||
4912              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4913   bool IsAddSub = false;
4914 
4915   switch (Op) {
4916   case AtomicExpr::AO__c11_atomic_init:
4917   case AtomicExpr::AO__opencl_atomic_init:
4918     Form = Init;
4919     break;
4920 
4921   case AtomicExpr::AO__c11_atomic_load:
4922   case AtomicExpr::AO__opencl_atomic_load:
4923   case AtomicExpr::AO__atomic_load_n:
4924     Form = Load;
4925     break;
4926 
4927   case AtomicExpr::AO__atomic_load:
4928     Form = LoadCopy;
4929     break;
4930 
4931   case AtomicExpr::AO__c11_atomic_store:
4932   case AtomicExpr::AO__opencl_atomic_store:
4933   case AtomicExpr::AO__atomic_store:
4934   case AtomicExpr::AO__atomic_store_n:
4935     Form = Copy;
4936     break;
4937 
4938   case AtomicExpr::AO__c11_atomic_fetch_add:
4939   case AtomicExpr::AO__c11_atomic_fetch_sub:
4940   case AtomicExpr::AO__opencl_atomic_fetch_add:
4941   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4942   case AtomicExpr::AO__atomic_fetch_add:
4943   case AtomicExpr::AO__atomic_fetch_sub:
4944   case AtomicExpr::AO__atomic_add_fetch:
4945   case AtomicExpr::AO__atomic_sub_fetch:
4946     IsAddSub = true;
4947     Form = Arithmetic;
4948     break;
4949   case AtomicExpr::AO__c11_atomic_fetch_and:
4950   case AtomicExpr::AO__c11_atomic_fetch_or:
4951   case AtomicExpr::AO__c11_atomic_fetch_xor:
4952   case AtomicExpr::AO__opencl_atomic_fetch_and:
4953   case AtomicExpr::AO__opencl_atomic_fetch_or:
4954   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4955   case AtomicExpr::AO__atomic_fetch_and:
4956   case AtomicExpr::AO__atomic_fetch_or:
4957   case AtomicExpr::AO__atomic_fetch_xor:
4958   case AtomicExpr::AO__atomic_fetch_nand:
4959   case AtomicExpr::AO__atomic_and_fetch:
4960   case AtomicExpr::AO__atomic_or_fetch:
4961   case AtomicExpr::AO__atomic_xor_fetch:
4962   case AtomicExpr::AO__atomic_nand_fetch:
4963     Form = Arithmetic;
4964     break;
4965   case AtomicExpr::AO__c11_atomic_fetch_min:
4966   case AtomicExpr::AO__c11_atomic_fetch_max:
4967   case AtomicExpr::AO__opencl_atomic_fetch_min:
4968   case AtomicExpr::AO__opencl_atomic_fetch_max:
4969   case AtomicExpr::AO__atomic_min_fetch:
4970   case AtomicExpr::AO__atomic_max_fetch:
4971   case AtomicExpr::AO__atomic_fetch_min:
4972   case AtomicExpr::AO__atomic_fetch_max:
4973     Form = Arithmetic;
4974     break;
4975 
4976   case AtomicExpr::AO__c11_atomic_exchange:
4977   case AtomicExpr::AO__opencl_atomic_exchange:
4978   case AtomicExpr::AO__atomic_exchange_n:
4979     Form = Xchg;
4980     break;
4981 
4982   case AtomicExpr::AO__atomic_exchange:
4983     Form = GNUXchg;
4984     break;
4985 
4986   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4987   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4988   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4989   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4990     Form = C11CmpXchg;
4991     break;
4992 
4993   case AtomicExpr::AO__atomic_compare_exchange:
4994   case AtomicExpr::AO__atomic_compare_exchange_n:
4995     Form = GNUCmpXchg;
4996     break;
4997   }
4998 
4999   unsigned AdjustedNumArgs = NumArgs[Form];
5000   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5001     ++AdjustedNumArgs;
5002   // Check we have the right number of arguments.
5003   if (Args.size() < AdjustedNumArgs) {
5004     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5005         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5006         << ExprRange;
5007     return ExprError();
5008   } else if (Args.size() > AdjustedNumArgs) {
5009     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5010          diag::err_typecheck_call_too_many_args)
5011         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5012         << ExprRange;
5013     return ExprError();
5014   }
5015 
5016   // Inspect the first argument of the atomic operation.
5017   Expr *Ptr = Args[0];
5018   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5019   if (ConvertedPtr.isInvalid())
5020     return ExprError();
5021 
5022   Ptr = ConvertedPtr.get();
5023   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5024   if (!pointerType) {
5025     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5026         << Ptr->getType() << Ptr->getSourceRange();
5027     return ExprError();
5028   }
5029 
5030   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5031   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5032   QualType ValType = AtomTy; // 'C'
5033   if (IsC11) {
5034     if (!AtomTy->isAtomicType()) {
5035       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5036           << Ptr->getType() << Ptr->getSourceRange();
5037       return ExprError();
5038     }
5039     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5040         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5041       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5042           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5043           << Ptr->getSourceRange();
5044       return ExprError();
5045     }
5046     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5047   } else if (Form != Load && Form != LoadCopy) {
5048     if (ValType.isConstQualified()) {
5049       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5050           << Ptr->getType() << Ptr->getSourceRange();
5051       return ExprError();
5052     }
5053   }
5054 
5055   // For an arithmetic operation, the implied arithmetic must be well-formed.
5056   if (Form == Arithmetic) {
5057     // gcc does not enforce these rules for GNU atomics, but we do so for
5058     // sanity.
5059     auto IsAllowedValueType = [&](QualType ValType) {
5060       if (ValType->isIntegerType())
5061         return true;
5062       if (ValType->isPointerType())
5063         return true;
5064       if (!ValType->isFloatingType())
5065         return false;
5066       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5067       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5068           &Context.getTargetInfo().getLongDoubleFormat() ==
5069               &llvm::APFloat::x87DoubleExtended())
5070         return false;
5071       return true;
5072     };
5073     if (IsAddSub && !IsAllowedValueType(ValType)) {
5074       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5075           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5076       return ExprError();
5077     }
5078     if (!IsAddSub && !ValType->isIntegerType()) {
5079       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5080           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5081       return ExprError();
5082     }
5083     if (IsC11 && ValType->isPointerType() &&
5084         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5085                             diag::err_incomplete_type)) {
5086       return ExprError();
5087     }
5088   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5089     // For __atomic_*_n operations, the value type must be a scalar integral or
5090     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5091     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5092         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5093     return ExprError();
5094   }
5095 
5096   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5097       !AtomTy->isScalarType()) {
5098     // For GNU atomics, require a trivially-copyable type. This is not part of
5099     // the GNU atomics specification, but we enforce it for sanity.
5100     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5101         << Ptr->getType() << Ptr->getSourceRange();
5102     return ExprError();
5103   }
5104 
5105   switch (ValType.getObjCLifetime()) {
5106   case Qualifiers::OCL_None:
5107   case Qualifiers::OCL_ExplicitNone:
5108     // okay
5109     break;
5110 
5111   case Qualifiers::OCL_Weak:
5112   case Qualifiers::OCL_Strong:
5113   case Qualifiers::OCL_Autoreleasing:
5114     // FIXME: Can this happen? By this point, ValType should be known
5115     // to be trivially copyable.
5116     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5117         << ValType << Ptr->getSourceRange();
5118     return ExprError();
5119   }
5120 
5121   // All atomic operations have an overload which takes a pointer to a volatile
5122   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5123   // into the result or the other operands. Similarly atomic_load takes a
5124   // pointer to a const 'A'.
5125   ValType.removeLocalVolatile();
5126   ValType.removeLocalConst();
5127   QualType ResultType = ValType;
5128   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5129       Form == Init)
5130     ResultType = Context.VoidTy;
5131   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5132     ResultType = Context.BoolTy;
5133 
5134   // The type of a parameter passed 'by value'. In the GNU atomics, such
5135   // arguments are actually passed as pointers.
5136   QualType ByValType = ValType; // 'CP'
5137   bool IsPassedByAddress = false;
5138   if (!IsC11 && !IsN) {
5139     ByValType = Ptr->getType();
5140     IsPassedByAddress = true;
5141   }
5142 
5143   SmallVector<Expr *, 5> APIOrderedArgs;
5144   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5145     APIOrderedArgs.push_back(Args[0]);
5146     switch (Form) {
5147     case Init:
5148     case Load:
5149       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5150       break;
5151     case LoadCopy:
5152     case Copy:
5153     case Arithmetic:
5154     case Xchg:
5155       APIOrderedArgs.push_back(Args[2]); // Val1
5156       APIOrderedArgs.push_back(Args[1]); // Order
5157       break;
5158     case GNUXchg:
5159       APIOrderedArgs.push_back(Args[2]); // Val1
5160       APIOrderedArgs.push_back(Args[3]); // Val2
5161       APIOrderedArgs.push_back(Args[1]); // Order
5162       break;
5163     case C11CmpXchg:
5164       APIOrderedArgs.push_back(Args[2]); // Val1
5165       APIOrderedArgs.push_back(Args[4]); // Val2
5166       APIOrderedArgs.push_back(Args[1]); // Order
5167       APIOrderedArgs.push_back(Args[3]); // OrderFail
5168       break;
5169     case GNUCmpXchg:
5170       APIOrderedArgs.push_back(Args[2]); // Val1
5171       APIOrderedArgs.push_back(Args[4]); // Val2
5172       APIOrderedArgs.push_back(Args[5]); // Weak
5173       APIOrderedArgs.push_back(Args[1]); // Order
5174       APIOrderedArgs.push_back(Args[3]); // OrderFail
5175       break;
5176     }
5177   } else
5178     APIOrderedArgs.append(Args.begin(), Args.end());
5179 
5180   // The first argument's non-CV pointer type is used to deduce the type of
5181   // subsequent arguments, except for:
5182   //  - weak flag (always converted to bool)
5183   //  - memory order (always converted to int)
5184   //  - scope  (always converted to int)
5185   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5186     QualType Ty;
5187     if (i < NumVals[Form] + 1) {
5188       switch (i) {
5189       case 0:
5190         // The first argument is always a pointer. It has a fixed type.
5191         // It is always dereferenced, a nullptr is undefined.
5192         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5193         // Nothing else to do: we already know all we want about this pointer.
5194         continue;
5195       case 1:
5196         // The second argument is the non-atomic operand. For arithmetic, this
5197         // is always passed by value, and for a compare_exchange it is always
5198         // passed by address. For the rest, GNU uses by-address and C11 uses
5199         // by-value.
5200         assert(Form != Load);
5201         if (Form == Arithmetic && ValType->isPointerType())
5202           Ty = Context.getPointerDiffType();
5203         else if (Form == Init || Form == Arithmetic)
5204           Ty = ValType;
5205         else if (Form == Copy || Form == Xchg) {
5206           if (IsPassedByAddress) {
5207             // The value pointer is always dereferenced, a nullptr is undefined.
5208             CheckNonNullArgument(*this, APIOrderedArgs[i],
5209                                  ExprRange.getBegin());
5210           }
5211           Ty = ByValType;
5212         } else {
5213           Expr *ValArg = APIOrderedArgs[i];
5214           // The value pointer is always dereferenced, a nullptr is undefined.
5215           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5216           LangAS AS = LangAS::Default;
5217           // Keep address space of non-atomic pointer type.
5218           if (const PointerType *PtrTy =
5219                   ValArg->getType()->getAs<PointerType>()) {
5220             AS = PtrTy->getPointeeType().getAddressSpace();
5221           }
5222           Ty = Context.getPointerType(
5223               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5224         }
5225         break;
5226       case 2:
5227         // The third argument to compare_exchange / GNU exchange is the desired
5228         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5229         if (IsPassedByAddress)
5230           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5231         Ty = ByValType;
5232         break;
5233       case 3:
5234         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5235         Ty = Context.BoolTy;
5236         break;
5237       }
5238     } else {
5239       // The order(s) and scope are always converted to int.
5240       Ty = Context.IntTy;
5241     }
5242 
5243     InitializedEntity Entity =
5244         InitializedEntity::InitializeParameter(Context, Ty, false);
5245     ExprResult Arg = APIOrderedArgs[i];
5246     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5247     if (Arg.isInvalid())
5248       return true;
5249     APIOrderedArgs[i] = Arg.get();
5250   }
5251 
5252   // Permute the arguments into a 'consistent' order.
5253   SmallVector<Expr*, 5> SubExprs;
5254   SubExprs.push_back(Ptr);
5255   switch (Form) {
5256   case Init:
5257     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5258     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5259     break;
5260   case Load:
5261     SubExprs.push_back(APIOrderedArgs[1]); // Order
5262     break;
5263   case LoadCopy:
5264   case Copy:
5265   case Arithmetic:
5266   case Xchg:
5267     SubExprs.push_back(APIOrderedArgs[2]); // Order
5268     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5269     break;
5270   case GNUXchg:
5271     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5272     SubExprs.push_back(APIOrderedArgs[3]); // Order
5273     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5274     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5275     break;
5276   case C11CmpXchg:
5277     SubExprs.push_back(APIOrderedArgs[3]); // Order
5278     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5279     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5280     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5281     break;
5282   case GNUCmpXchg:
5283     SubExprs.push_back(APIOrderedArgs[4]); // Order
5284     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5285     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5286     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5287     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5288     break;
5289   }
5290 
5291   if (SubExprs.size() >= 2 && Form != Init) {
5292     if (Optional<llvm::APSInt> Result =
5293             SubExprs[1]->getIntegerConstantExpr(Context))
5294       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5295         Diag(SubExprs[1]->getBeginLoc(),
5296              diag::warn_atomic_op_has_invalid_memory_order)
5297             << SubExprs[1]->getSourceRange();
5298   }
5299 
5300   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5301     auto *Scope = Args[Args.size() - 1];
5302     if (Optional<llvm::APSInt> Result =
5303             Scope->getIntegerConstantExpr(Context)) {
5304       if (!ScopeModel->isValid(Result->getZExtValue()))
5305         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5306             << Scope->getSourceRange();
5307     }
5308     SubExprs.push_back(Scope);
5309   }
5310 
5311   AtomicExpr *AE = new (Context)
5312       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5313 
5314   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5315        Op == AtomicExpr::AO__c11_atomic_store ||
5316        Op == AtomicExpr::AO__opencl_atomic_load ||
5317        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5318       Context.AtomicUsesUnsupportedLibcall(AE))
5319     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5320         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5321              Op == AtomicExpr::AO__opencl_atomic_load)
5322                 ? 0
5323                 : 1);
5324 
5325   if (ValType->isExtIntType()) {
5326     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5327     return ExprError();
5328   }
5329 
5330   return AE;
5331 }
5332 
5333 /// checkBuiltinArgument - Given a call to a builtin function, perform
5334 /// normal type-checking on the given argument, updating the call in
5335 /// place.  This is useful when a builtin function requires custom
5336 /// type-checking for some of its arguments but not necessarily all of
5337 /// them.
5338 ///
5339 /// Returns true on error.
5340 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5341   FunctionDecl *Fn = E->getDirectCallee();
5342   assert(Fn && "builtin call without direct callee!");
5343 
5344   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5345   InitializedEntity Entity =
5346     InitializedEntity::InitializeParameter(S.Context, Param);
5347 
5348   ExprResult Arg = E->getArg(0);
5349   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5350   if (Arg.isInvalid())
5351     return true;
5352 
5353   E->setArg(ArgIndex, Arg.get());
5354   return false;
5355 }
5356 
5357 /// We have a call to a function like __sync_fetch_and_add, which is an
5358 /// overloaded function based on the pointer type of its first argument.
5359 /// The main BuildCallExpr routines have already promoted the types of
5360 /// arguments because all of these calls are prototyped as void(...).
5361 ///
5362 /// This function goes through and does final semantic checking for these
5363 /// builtins, as well as generating any warnings.
5364 ExprResult
5365 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5366   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5367   Expr *Callee = TheCall->getCallee();
5368   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5369   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5370 
5371   // Ensure that we have at least one argument to do type inference from.
5372   if (TheCall->getNumArgs() < 1) {
5373     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5374         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5375     return ExprError();
5376   }
5377 
5378   // Inspect the first argument of the atomic builtin.  This should always be
5379   // a pointer type, whose element is an integral scalar or pointer type.
5380   // Because it is a pointer type, we don't have to worry about any implicit
5381   // casts here.
5382   // FIXME: We don't allow floating point scalars as input.
5383   Expr *FirstArg = TheCall->getArg(0);
5384   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5385   if (FirstArgResult.isInvalid())
5386     return ExprError();
5387   FirstArg = FirstArgResult.get();
5388   TheCall->setArg(0, FirstArg);
5389 
5390   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5391   if (!pointerType) {
5392     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5393         << FirstArg->getType() << FirstArg->getSourceRange();
5394     return ExprError();
5395   }
5396 
5397   QualType ValType = pointerType->getPointeeType();
5398   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5399       !ValType->isBlockPointerType()) {
5400     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5401         << FirstArg->getType() << FirstArg->getSourceRange();
5402     return ExprError();
5403   }
5404 
5405   if (ValType.isConstQualified()) {
5406     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5407         << FirstArg->getType() << FirstArg->getSourceRange();
5408     return ExprError();
5409   }
5410 
5411   switch (ValType.getObjCLifetime()) {
5412   case Qualifiers::OCL_None:
5413   case Qualifiers::OCL_ExplicitNone:
5414     // okay
5415     break;
5416 
5417   case Qualifiers::OCL_Weak:
5418   case Qualifiers::OCL_Strong:
5419   case Qualifiers::OCL_Autoreleasing:
5420     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5421         << ValType << FirstArg->getSourceRange();
5422     return ExprError();
5423   }
5424 
5425   // Strip any qualifiers off ValType.
5426   ValType = ValType.getUnqualifiedType();
5427 
5428   // The majority of builtins return a value, but a few have special return
5429   // types, so allow them to override appropriately below.
5430   QualType ResultType = ValType;
5431 
5432   // We need to figure out which concrete builtin this maps onto.  For example,
5433   // __sync_fetch_and_add with a 2 byte object turns into
5434   // __sync_fetch_and_add_2.
5435 #define BUILTIN_ROW(x) \
5436   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5437     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5438 
5439   static const unsigned BuiltinIndices[][5] = {
5440     BUILTIN_ROW(__sync_fetch_and_add),
5441     BUILTIN_ROW(__sync_fetch_and_sub),
5442     BUILTIN_ROW(__sync_fetch_and_or),
5443     BUILTIN_ROW(__sync_fetch_and_and),
5444     BUILTIN_ROW(__sync_fetch_and_xor),
5445     BUILTIN_ROW(__sync_fetch_and_nand),
5446 
5447     BUILTIN_ROW(__sync_add_and_fetch),
5448     BUILTIN_ROW(__sync_sub_and_fetch),
5449     BUILTIN_ROW(__sync_and_and_fetch),
5450     BUILTIN_ROW(__sync_or_and_fetch),
5451     BUILTIN_ROW(__sync_xor_and_fetch),
5452     BUILTIN_ROW(__sync_nand_and_fetch),
5453 
5454     BUILTIN_ROW(__sync_val_compare_and_swap),
5455     BUILTIN_ROW(__sync_bool_compare_and_swap),
5456     BUILTIN_ROW(__sync_lock_test_and_set),
5457     BUILTIN_ROW(__sync_lock_release),
5458     BUILTIN_ROW(__sync_swap)
5459   };
5460 #undef BUILTIN_ROW
5461 
5462   // Determine the index of the size.
5463   unsigned SizeIndex;
5464   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5465   case 1: SizeIndex = 0; break;
5466   case 2: SizeIndex = 1; break;
5467   case 4: SizeIndex = 2; break;
5468   case 8: SizeIndex = 3; break;
5469   case 16: SizeIndex = 4; break;
5470   default:
5471     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5472         << FirstArg->getType() << FirstArg->getSourceRange();
5473     return ExprError();
5474   }
5475 
5476   // Each of these builtins has one pointer argument, followed by some number of
5477   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5478   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5479   // as the number of fixed args.
5480   unsigned BuiltinID = FDecl->getBuiltinID();
5481   unsigned BuiltinIndex, NumFixed = 1;
5482   bool WarnAboutSemanticsChange = false;
5483   switch (BuiltinID) {
5484   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5485   case Builtin::BI__sync_fetch_and_add:
5486   case Builtin::BI__sync_fetch_and_add_1:
5487   case Builtin::BI__sync_fetch_and_add_2:
5488   case Builtin::BI__sync_fetch_and_add_4:
5489   case Builtin::BI__sync_fetch_and_add_8:
5490   case Builtin::BI__sync_fetch_and_add_16:
5491     BuiltinIndex = 0;
5492     break;
5493 
5494   case Builtin::BI__sync_fetch_and_sub:
5495   case Builtin::BI__sync_fetch_and_sub_1:
5496   case Builtin::BI__sync_fetch_and_sub_2:
5497   case Builtin::BI__sync_fetch_and_sub_4:
5498   case Builtin::BI__sync_fetch_and_sub_8:
5499   case Builtin::BI__sync_fetch_and_sub_16:
5500     BuiltinIndex = 1;
5501     break;
5502 
5503   case Builtin::BI__sync_fetch_and_or:
5504   case Builtin::BI__sync_fetch_and_or_1:
5505   case Builtin::BI__sync_fetch_and_or_2:
5506   case Builtin::BI__sync_fetch_and_or_4:
5507   case Builtin::BI__sync_fetch_and_or_8:
5508   case Builtin::BI__sync_fetch_and_or_16:
5509     BuiltinIndex = 2;
5510     break;
5511 
5512   case Builtin::BI__sync_fetch_and_and:
5513   case Builtin::BI__sync_fetch_and_and_1:
5514   case Builtin::BI__sync_fetch_and_and_2:
5515   case Builtin::BI__sync_fetch_and_and_4:
5516   case Builtin::BI__sync_fetch_and_and_8:
5517   case Builtin::BI__sync_fetch_and_and_16:
5518     BuiltinIndex = 3;
5519     break;
5520 
5521   case Builtin::BI__sync_fetch_and_xor:
5522   case Builtin::BI__sync_fetch_and_xor_1:
5523   case Builtin::BI__sync_fetch_and_xor_2:
5524   case Builtin::BI__sync_fetch_and_xor_4:
5525   case Builtin::BI__sync_fetch_and_xor_8:
5526   case Builtin::BI__sync_fetch_and_xor_16:
5527     BuiltinIndex = 4;
5528     break;
5529 
5530   case Builtin::BI__sync_fetch_and_nand:
5531   case Builtin::BI__sync_fetch_and_nand_1:
5532   case Builtin::BI__sync_fetch_and_nand_2:
5533   case Builtin::BI__sync_fetch_and_nand_4:
5534   case Builtin::BI__sync_fetch_and_nand_8:
5535   case Builtin::BI__sync_fetch_and_nand_16:
5536     BuiltinIndex = 5;
5537     WarnAboutSemanticsChange = true;
5538     break;
5539 
5540   case Builtin::BI__sync_add_and_fetch:
5541   case Builtin::BI__sync_add_and_fetch_1:
5542   case Builtin::BI__sync_add_and_fetch_2:
5543   case Builtin::BI__sync_add_and_fetch_4:
5544   case Builtin::BI__sync_add_and_fetch_8:
5545   case Builtin::BI__sync_add_and_fetch_16:
5546     BuiltinIndex = 6;
5547     break;
5548 
5549   case Builtin::BI__sync_sub_and_fetch:
5550   case Builtin::BI__sync_sub_and_fetch_1:
5551   case Builtin::BI__sync_sub_and_fetch_2:
5552   case Builtin::BI__sync_sub_and_fetch_4:
5553   case Builtin::BI__sync_sub_and_fetch_8:
5554   case Builtin::BI__sync_sub_and_fetch_16:
5555     BuiltinIndex = 7;
5556     break;
5557 
5558   case Builtin::BI__sync_and_and_fetch:
5559   case Builtin::BI__sync_and_and_fetch_1:
5560   case Builtin::BI__sync_and_and_fetch_2:
5561   case Builtin::BI__sync_and_and_fetch_4:
5562   case Builtin::BI__sync_and_and_fetch_8:
5563   case Builtin::BI__sync_and_and_fetch_16:
5564     BuiltinIndex = 8;
5565     break;
5566 
5567   case Builtin::BI__sync_or_and_fetch:
5568   case Builtin::BI__sync_or_and_fetch_1:
5569   case Builtin::BI__sync_or_and_fetch_2:
5570   case Builtin::BI__sync_or_and_fetch_4:
5571   case Builtin::BI__sync_or_and_fetch_8:
5572   case Builtin::BI__sync_or_and_fetch_16:
5573     BuiltinIndex = 9;
5574     break;
5575 
5576   case Builtin::BI__sync_xor_and_fetch:
5577   case Builtin::BI__sync_xor_and_fetch_1:
5578   case Builtin::BI__sync_xor_and_fetch_2:
5579   case Builtin::BI__sync_xor_and_fetch_4:
5580   case Builtin::BI__sync_xor_and_fetch_8:
5581   case Builtin::BI__sync_xor_and_fetch_16:
5582     BuiltinIndex = 10;
5583     break;
5584 
5585   case Builtin::BI__sync_nand_and_fetch:
5586   case Builtin::BI__sync_nand_and_fetch_1:
5587   case Builtin::BI__sync_nand_and_fetch_2:
5588   case Builtin::BI__sync_nand_and_fetch_4:
5589   case Builtin::BI__sync_nand_and_fetch_8:
5590   case Builtin::BI__sync_nand_and_fetch_16:
5591     BuiltinIndex = 11;
5592     WarnAboutSemanticsChange = true;
5593     break;
5594 
5595   case Builtin::BI__sync_val_compare_and_swap:
5596   case Builtin::BI__sync_val_compare_and_swap_1:
5597   case Builtin::BI__sync_val_compare_and_swap_2:
5598   case Builtin::BI__sync_val_compare_and_swap_4:
5599   case Builtin::BI__sync_val_compare_and_swap_8:
5600   case Builtin::BI__sync_val_compare_and_swap_16:
5601     BuiltinIndex = 12;
5602     NumFixed = 2;
5603     break;
5604 
5605   case Builtin::BI__sync_bool_compare_and_swap:
5606   case Builtin::BI__sync_bool_compare_and_swap_1:
5607   case Builtin::BI__sync_bool_compare_and_swap_2:
5608   case Builtin::BI__sync_bool_compare_and_swap_4:
5609   case Builtin::BI__sync_bool_compare_and_swap_8:
5610   case Builtin::BI__sync_bool_compare_and_swap_16:
5611     BuiltinIndex = 13;
5612     NumFixed = 2;
5613     ResultType = Context.BoolTy;
5614     break;
5615 
5616   case Builtin::BI__sync_lock_test_and_set:
5617   case Builtin::BI__sync_lock_test_and_set_1:
5618   case Builtin::BI__sync_lock_test_and_set_2:
5619   case Builtin::BI__sync_lock_test_and_set_4:
5620   case Builtin::BI__sync_lock_test_and_set_8:
5621   case Builtin::BI__sync_lock_test_and_set_16:
5622     BuiltinIndex = 14;
5623     break;
5624 
5625   case Builtin::BI__sync_lock_release:
5626   case Builtin::BI__sync_lock_release_1:
5627   case Builtin::BI__sync_lock_release_2:
5628   case Builtin::BI__sync_lock_release_4:
5629   case Builtin::BI__sync_lock_release_8:
5630   case Builtin::BI__sync_lock_release_16:
5631     BuiltinIndex = 15;
5632     NumFixed = 0;
5633     ResultType = Context.VoidTy;
5634     break;
5635 
5636   case Builtin::BI__sync_swap:
5637   case Builtin::BI__sync_swap_1:
5638   case Builtin::BI__sync_swap_2:
5639   case Builtin::BI__sync_swap_4:
5640   case Builtin::BI__sync_swap_8:
5641   case Builtin::BI__sync_swap_16:
5642     BuiltinIndex = 16;
5643     break;
5644   }
5645 
5646   // Now that we know how many fixed arguments we expect, first check that we
5647   // have at least that many.
5648   if (TheCall->getNumArgs() < 1+NumFixed) {
5649     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5650         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5651         << Callee->getSourceRange();
5652     return ExprError();
5653   }
5654 
5655   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5656       << Callee->getSourceRange();
5657 
5658   if (WarnAboutSemanticsChange) {
5659     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5660         << Callee->getSourceRange();
5661   }
5662 
5663   // Get the decl for the concrete builtin from this, we can tell what the
5664   // concrete integer type we should convert to is.
5665   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5666   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5667   FunctionDecl *NewBuiltinDecl;
5668   if (NewBuiltinID == BuiltinID)
5669     NewBuiltinDecl = FDecl;
5670   else {
5671     // Perform builtin lookup to avoid redeclaring it.
5672     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5673     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5674     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5675     assert(Res.getFoundDecl());
5676     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5677     if (!NewBuiltinDecl)
5678       return ExprError();
5679   }
5680 
5681   // The first argument --- the pointer --- has a fixed type; we
5682   // deduce the types of the rest of the arguments accordingly.  Walk
5683   // the remaining arguments, converting them to the deduced value type.
5684   for (unsigned i = 0; i != NumFixed; ++i) {
5685     ExprResult Arg = TheCall->getArg(i+1);
5686 
5687     // GCC does an implicit conversion to the pointer or integer ValType.  This
5688     // can fail in some cases (1i -> int**), check for this error case now.
5689     // Initialize the argument.
5690     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5691                                                    ValType, /*consume*/ false);
5692     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5693     if (Arg.isInvalid())
5694       return ExprError();
5695 
5696     // Okay, we have something that *can* be converted to the right type.  Check
5697     // to see if there is a potentially weird extension going on here.  This can
5698     // happen when you do an atomic operation on something like an char* and
5699     // pass in 42.  The 42 gets converted to char.  This is even more strange
5700     // for things like 45.123 -> char, etc.
5701     // FIXME: Do this check.
5702     TheCall->setArg(i+1, Arg.get());
5703   }
5704 
5705   // Create a new DeclRefExpr to refer to the new decl.
5706   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5707       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5708       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5709       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5710 
5711   // Set the callee in the CallExpr.
5712   // FIXME: This loses syntactic information.
5713   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5714   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5715                                               CK_BuiltinFnToFnPtr);
5716   TheCall->setCallee(PromotedCall.get());
5717 
5718   // Change the result type of the call to match the original value type. This
5719   // is arbitrary, but the codegen for these builtins ins design to handle it
5720   // gracefully.
5721   TheCall->setType(ResultType);
5722 
5723   // Prohibit use of _ExtInt with atomic builtins.
5724   // The arguments would have already been converted to the first argument's
5725   // type, so only need to check the first argument.
5726   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5727   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5728     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5729     return ExprError();
5730   }
5731 
5732   return TheCallResult;
5733 }
5734 
5735 /// SemaBuiltinNontemporalOverloaded - We have a call to
5736 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5737 /// overloaded function based on the pointer type of its last argument.
5738 ///
5739 /// This function goes through and does final semantic checking for these
5740 /// builtins.
5741 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5742   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5743   DeclRefExpr *DRE =
5744       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5745   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5746   unsigned BuiltinID = FDecl->getBuiltinID();
5747   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5748           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5749          "Unexpected nontemporal load/store builtin!");
5750   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5751   unsigned numArgs = isStore ? 2 : 1;
5752 
5753   // Ensure that we have the proper number of arguments.
5754   if (checkArgCount(*this, TheCall, numArgs))
5755     return ExprError();
5756 
5757   // Inspect the last argument of the nontemporal builtin.  This should always
5758   // be a pointer type, from which we imply the type of the memory access.
5759   // Because it is a pointer type, we don't have to worry about any implicit
5760   // casts here.
5761   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5762   ExprResult PointerArgResult =
5763       DefaultFunctionArrayLvalueConversion(PointerArg);
5764 
5765   if (PointerArgResult.isInvalid())
5766     return ExprError();
5767   PointerArg = PointerArgResult.get();
5768   TheCall->setArg(numArgs - 1, PointerArg);
5769 
5770   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5771   if (!pointerType) {
5772     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5773         << PointerArg->getType() << PointerArg->getSourceRange();
5774     return ExprError();
5775   }
5776 
5777   QualType ValType = pointerType->getPointeeType();
5778 
5779   // Strip any qualifiers off ValType.
5780   ValType = ValType.getUnqualifiedType();
5781   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5782       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5783       !ValType->isVectorType()) {
5784     Diag(DRE->getBeginLoc(),
5785          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5786         << PointerArg->getType() << PointerArg->getSourceRange();
5787     return ExprError();
5788   }
5789 
5790   if (!isStore) {
5791     TheCall->setType(ValType);
5792     return TheCallResult;
5793   }
5794 
5795   ExprResult ValArg = TheCall->getArg(0);
5796   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5797       Context, ValType, /*consume*/ false);
5798   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5799   if (ValArg.isInvalid())
5800     return ExprError();
5801 
5802   TheCall->setArg(0, ValArg.get());
5803   TheCall->setType(Context.VoidTy);
5804   return TheCallResult;
5805 }
5806 
5807 /// CheckObjCString - Checks that the argument to the builtin
5808 /// CFString constructor is correct
5809 /// Note: It might also make sense to do the UTF-16 conversion here (would
5810 /// simplify the backend).
5811 bool Sema::CheckObjCString(Expr *Arg) {
5812   Arg = Arg->IgnoreParenCasts();
5813   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5814 
5815   if (!Literal || !Literal->isAscii()) {
5816     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5817         << Arg->getSourceRange();
5818     return true;
5819   }
5820 
5821   if (Literal->containsNonAsciiOrNull()) {
5822     StringRef String = Literal->getString();
5823     unsigned NumBytes = String.size();
5824     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5825     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5826     llvm::UTF16 *ToPtr = &ToBuf[0];
5827 
5828     llvm::ConversionResult Result =
5829         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5830                                  ToPtr + NumBytes, llvm::strictConversion);
5831     // Check for conversion failure.
5832     if (Result != llvm::conversionOK)
5833       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5834           << Arg->getSourceRange();
5835   }
5836   return false;
5837 }
5838 
5839 /// CheckObjCString - Checks that the format string argument to the os_log()
5840 /// and os_trace() functions is correct, and converts it to const char *.
5841 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5842   Arg = Arg->IgnoreParenCasts();
5843   auto *Literal = dyn_cast<StringLiteral>(Arg);
5844   if (!Literal) {
5845     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5846       Literal = ObjcLiteral->getString();
5847     }
5848   }
5849 
5850   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5851     return ExprError(
5852         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5853         << Arg->getSourceRange());
5854   }
5855 
5856   ExprResult Result(Literal);
5857   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5858   InitializedEntity Entity =
5859       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5860   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5861   return Result;
5862 }
5863 
5864 /// Check that the user is calling the appropriate va_start builtin for the
5865 /// target and calling convention.
5866 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5867   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5868   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5869   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5870                     TT.getArch() == llvm::Triple::aarch64_32);
5871   bool IsWindows = TT.isOSWindows();
5872   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5873   if (IsX64 || IsAArch64) {
5874     CallingConv CC = CC_C;
5875     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5876       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5877     if (IsMSVAStart) {
5878       // Don't allow this in System V ABI functions.
5879       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5880         return S.Diag(Fn->getBeginLoc(),
5881                       diag::err_ms_va_start_used_in_sysv_function);
5882     } else {
5883       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5884       // On x64 Windows, don't allow this in System V ABI functions.
5885       // (Yes, that means there's no corresponding way to support variadic
5886       // System V ABI functions on Windows.)
5887       if ((IsWindows && CC == CC_X86_64SysV) ||
5888           (!IsWindows && CC == CC_Win64))
5889         return S.Diag(Fn->getBeginLoc(),
5890                       diag::err_va_start_used_in_wrong_abi_function)
5891                << !IsWindows;
5892     }
5893     return false;
5894   }
5895 
5896   if (IsMSVAStart)
5897     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5898   return false;
5899 }
5900 
5901 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5902                                              ParmVarDecl **LastParam = nullptr) {
5903   // Determine whether the current function, block, or obj-c method is variadic
5904   // and get its parameter list.
5905   bool IsVariadic = false;
5906   ArrayRef<ParmVarDecl *> Params;
5907   DeclContext *Caller = S.CurContext;
5908   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5909     IsVariadic = Block->isVariadic();
5910     Params = Block->parameters();
5911   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5912     IsVariadic = FD->isVariadic();
5913     Params = FD->parameters();
5914   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5915     IsVariadic = MD->isVariadic();
5916     // FIXME: This isn't correct for methods (results in bogus warning).
5917     Params = MD->parameters();
5918   } else if (isa<CapturedDecl>(Caller)) {
5919     // We don't support va_start in a CapturedDecl.
5920     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5921     return true;
5922   } else {
5923     // This must be some other declcontext that parses exprs.
5924     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5925     return true;
5926   }
5927 
5928   if (!IsVariadic) {
5929     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5930     return true;
5931   }
5932 
5933   if (LastParam)
5934     *LastParam = Params.empty() ? nullptr : Params.back();
5935 
5936   return false;
5937 }
5938 
5939 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5940 /// for validity.  Emit an error and return true on failure; return false
5941 /// on success.
5942 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5943   Expr *Fn = TheCall->getCallee();
5944 
5945   if (checkVAStartABI(*this, BuiltinID, Fn))
5946     return true;
5947 
5948   if (checkArgCount(*this, TheCall, 2))
5949     return true;
5950 
5951   // Type-check the first argument normally.
5952   if (checkBuiltinArgument(*this, TheCall, 0))
5953     return true;
5954 
5955   // Check that the current function is variadic, and get its last parameter.
5956   ParmVarDecl *LastParam;
5957   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5958     return true;
5959 
5960   // Verify that the second argument to the builtin is the last argument of the
5961   // current function or method.
5962   bool SecondArgIsLastNamedArgument = false;
5963   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5964 
5965   // These are valid if SecondArgIsLastNamedArgument is false after the next
5966   // block.
5967   QualType Type;
5968   SourceLocation ParamLoc;
5969   bool IsCRegister = false;
5970 
5971   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5972     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5973       SecondArgIsLastNamedArgument = PV == LastParam;
5974 
5975       Type = PV->getType();
5976       ParamLoc = PV->getLocation();
5977       IsCRegister =
5978           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5979     }
5980   }
5981 
5982   if (!SecondArgIsLastNamedArgument)
5983     Diag(TheCall->getArg(1)->getBeginLoc(),
5984          diag::warn_second_arg_of_va_start_not_last_named_param);
5985   else if (IsCRegister || Type->isReferenceType() ||
5986            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5987              // Promotable integers are UB, but enumerations need a bit of
5988              // extra checking to see what their promotable type actually is.
5989              if (!Type->isPromotableIntegerType())
5990                return false;
5991              if (!Type->isEnumeralType())
5992                return true;
5993              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5994              return !(ED &&
5995                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5996            }()) {
5997     unsigned Reason = 0;
5998     if (Type->isReferenceType())  Reason = 1;
5999     else if (IsCRegister)         Reason = 2;
6000     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6001     Diag(ParamLoc, diag::note_parameter_type) << Type;
6002   }
6003 
6004   TheCall->setType(Context.VoidTy);
6005   return false;
6006 }
6007 
6008 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6009   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6010   //                 const char *named_addr);
6011 
6012   Expr *Func = Call->getCallee();
6013 
6014   if (Call->getNumArgs() < 3)
6015     return Diag(Call->getEndLoc(),
6016                 diag::err_typecheck_call_too_few_args_at_least)
6017            << 0 /*function call*/ << 3 << Call->getNumArgs();
6018 
6019   // Type-check the first argument normally.
6020   if (checkBuiltinArgument(*this, Call, 0))
6021     return true;
6022 
6023   // Check that the current function is variadic.
6024   if (checkVAStartIsInVariadicFunction(*this, Func))
6025     return true;
6026 
6027   // __va_start on Windows does not validate the parameter qualifiers
6028 
6029   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6030   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6031 
6032   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6033   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6034 
6035   const QualType &ConstCharPtrTy =
6036       Context.getPointerType(Context.CharTy.withConst());
6037   if (!Arg1Ty->isPointerType() ||
6038       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6039     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6040         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6041         << 0                                      /* qualifier difference */
6042         << 3                                      /* parameter mismatch */
6043         << 2 << Arg1->getType() << ConstCharPtrTy;
6044 
6045   const QualType SizeTy = Context.getSizeType();
6046   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6047     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6048         << Arg2->getType() << SizeTy << 1 /* different class */
6049         << 0                              /* qualifier difference */
6050         << 3                              /* parameter mismatch */
6051         << 3 << Arg2->getType() << SizeTy;
6052 
6053   return false;
6054 }
6055 
6056 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6057 /// friends.  This is declared to take (...), so we have to check everything.
6058 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6059   if (checkArgCount(*this, TheCall, 2))
6060     return true;
6061 
6062   ExprResult OrigArg0 = TheCall->getArg(0);
6063   ExprResult OrigArg1 = TheCall->getArg(1);
6064 
6065   // Do standard promotions between the two arguments, returning their common
6066   // type.
6067   QualType Res = UsualArithmeticConversions(
6068       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6069   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6070     return true;
6071 
6072   // Make sure any conversions are pushed back into the call; this is
6073   // type safe since unordered compare builtins are declared as "_Bool
6074   // foo(...)".
6075   TheCall->setArg(0, OrigArg0.get());
6076   TheCall->setArg(1, OrigArg1.get());
6077 
6078   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6079     return false;
6080 
6081   // If the common type isn't a real floating type, then the arguments were
6082   // invalid for this operation.
6083   if (Res.isNull() || !Res->isRealFloatingType())
6084     return Diag(OrigArg0.get()->getBeginLoc(),
6085                 diag::err_typecheck_call_invalid_ordered_compare)
6086            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6087            << SourceRange(OrigArg0.get()->getBeginLoc(),
6088                           OrigArg1.get()->getEndLoc());
6089 
6090   return false;
6091 }
6092 
6093 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6094 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6095 /// to check everything. We expect the last argument to be a floating point
6096 /// value.
6097 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6098   if (checkArgCount(*this, TheCall, NumArgs))
6099     return true;
6100 
6101   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6102   // on all preceding parameters just being int.  Try all of those.
6103   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6104     Expr *Arg = TheCall->getArg(i);
6105 
6106     if (Arg->isTypeDependent())
6107       return false;
6108 
6109     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6110 
6111     if (Res.isInvalid())
6112       return true;
6113     TheCall->setArg(i, Res.get());
6114   }
6115 
6116   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6117 
6118   if (OrigArg->isTypeDependent())
6119     return false;
6120 
6121   // Usual Unary Conversions will convert half to float, which we want for
6122   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6123   // type how it is, but do normal L->Rvalue conversions.
6124   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6125     OrigArg = UsualUnaryConversions(OrigArg).get();
6126   else
6127     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6128   TheCall->setArg(NumArgs - 1, OrigArg);
6129 
6130   // This operation requires a non-_Complex floating-point number.
6131   if (!OrigArg->getType()->isRealFloatingType())
6132     return Diag(OrigArg->getBeginLoc(),
6133                 diag::err_typecheck_call_invalid_unary_fp)
6134            << OrigArg->getType() << OrigArg->getSourceRange();
6135 
6136   return false;
6137 }
6138 
6139 /// Perform semantic analysis for a call to __builtin_complex.
6140 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6141   if (checkArgCount(*this, TheCall, 2))
6142     return true;
6143 
6144   bool Dependent = false;
6145   for (unsigned I = 0; I != 2; ++I) {
6146     Expr *Arg = TheCall->getArg(I);
6147     QualType T = Arg->getType();
6148     if (T->isDependentType()) {
6149       Dependent = true;
6150       continue;
6151     }
6152 
6153     // Despite supporting _Complex int, GCC requires a real floating point type
6154     // for the operands of __builtin_complex.
6155     if (!T->isRealFloatingType()) {
6156       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6157              << Arg->getType() << Arg->getSourceRange();
6158     }
6159 
6160     ExprResult Converted = DefaultLvalueConversion(Arg);
6161     if (Converted.isInvalid())
6162       return true;
6163     TheCall->setArg(I, Converted.get());
6164   }
6165 
6166   if (Dependent) {
6167     TheCall->setType(Context.DependentTy);
6168     return false;
6169   }
6170 
6171   Expr *Real = TheCall->getArg(0);
6172   Expr *Imag = TheCall->getArg(1);
6173   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6174     return Diag(Real->getBeginLoc(),
6175                 diag::err_typecheck_call_different_arg_types)
6176            << Real->getType() << Imag->getType()
6177            << Real->getSourceRange() << Imag->getSourceRange();
6178   }
6179 
6180   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6181   // don't allow this builtin to form those types either.
6182   // FIXME: Should we allow these types?
6183   if (Real->getType()->isFloat16Type())
6184     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6185            << "_Float16";
6186   if (Real->getType()->isHalfType())
6187     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6188            << "half";
6189 
6190   TheCall->setType(Context.getComplexType(Real->getType()));
6191   return false;
6192 }
6193 
6194 // Customized Sema Checking for VSX builtins that have the following signature:
6195 // vector [...] builtinName(vector [...], vector [...], const int);
6196 // Which takes the same type of vectors (any legal vector type) for the first
6197 // two arguments and takes compile time constant for the third argument.
6198 // Example builtins are :
6199 // vector double vec_xxpermdi(vector double, vector double, int);
6200 // vector short vec_xxsldwi(vector short, vector short, int);
6201 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6202   unsigned ExpectedNumArgs = 3;
6203   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6204     return true;
6205 
6206   // Check the third argument is a compile time constant
6207   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6208     return Diag(TheCall->getBeginLoc(),
6209                 diag::err_vsx_builtin_nonconstant_argument)
6210            << 3 /* argument index */ << TheCall->getDirectCallee()
6211            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6212                           TheCall->getArg(2)->getEndLoc());
6213 
6214   QualType Arg1Ty = TheCall->getArg(0)->getType();
6215   QualType Arg2Ty = TheCall->getArg(1)->getType();
6216 
6217   // Check the type of argument 1 and argument 2 are vectors.
6218   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6219   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6220       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6221     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6222            << TheCall->getDirectCallee()
6223            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6224                           TheCall->getArg(1)->getEndLoc());
6225   }
6226 
6227   // Check the first two arguments are the same type.
6228   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6229     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6230            << TheCall->getDirectCallee()
6231            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6232                           TheCall->getArg(1)->getEndLoc());
6233   }
6234 
6235   // When default clang type checking is turned off and the customized type
6236   // checking is used, the returning type of the function must be explicitly
6237   // set. Otherwise it is _Bool by default.
6238   TheCall->setType(Arg1Ty);
6239 
6240   return false;
6241 }
6242 
6243 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6244 // This is declared to take (...), so we have to check everything.
6245 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6246   if (TheCall->getNumArgs() < 2)
6247     return ExprError(Diag(TheCall->getEndLoc(),
6248                           diag::err_typecheck_call_too_few_args_at_least)
6249                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6250                      << TheCall->getSourceRange());
6251 
6252   // Determine which of the following types of shufflevector we're checking:
6253   // 1) unary, vector mask: (lhs, mask)
6254   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6255   QualType resType = TheCall->getArg(0)->getType();
6256   unsigned numElements = 0;
6257 
6258   if (!TheCall->getArg(0)->isTypeDependent() &&
6259       !TheCall->getArg(1)->isTypeDependent()) {
6260     QualType LHSType = TheCall->getArg(0)->getType();
6261     QualType RHSType = TheCall->getArg(1)->getType();
6262 
6263     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6264       return ExprError(
6265           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6266           << TheCall->getDirectCallee()
6267           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6268                          TheCall->getArg(1)->getEndLoc()));
6269 
6270     numElements = LHSType->castAs<VectorType>()->getNumElements();
6271     unsigned numResElements = TheCall->getNumArgs() - 2;
6272 
6273     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6274     // with mask.  If so, verify that RHS is an integer vector type with the
6275     // same number of elts as lhs.
6276     if (TheCall->getNumArgs() == 2) {
6277       if (!RHSType->hasIntegerRepresentation() ||
6278           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6279         return ExprError(Diag(TheCall->getBeginLoc(),
6280                               diag::err_vec_builtin_incompatible_vector)
6281                          << TheCall->getDirectCallee()
6282                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6283                                         TheCall->getArg(1)->getEndLoc()));
6284     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6285       return ExprError(Diag(TheCall->getBeginLoc(),
6286                             diag::err_vec_builtin_incompatible_vector)
6287                        << TheCall->getDirectCallee()
6288                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6289                                       TheCall->getArg(1)->getEndLoc()));
6290     } else if (numElements != numResElements) {
6291       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6292       resType = Context.getVectorType(eltType, numResElements,
6293                                       VectorType::GenericVector);
6294     }
6295   }
6296 
6297   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6298     if (TheCall->getArg(i)->isTypeDependent() ||
6299         TheCall->getArg(i)->isValueDependent())
6300       continue;
6301 
6302     Optional<llvm::APSInt> Result;
6303     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6304       return ExprError(Diag(TheCall->getBeginLoc(),
6305                             diag::err_shufflevector_nonconstant_argument)
6306                        << TheCall->getArg(i)->getSourceRange());
6307 
6308     // Allow -1 which will be translated to undef in the IR.
6309     if (Result->isSigned() && Result->isAllOnesValue())
6310       continue;
6311 
6312     if (Result->getActiveBits() > 64 ||
6313         Result->getZExtValue() >= numElements * 2)
6314       return ExprError(Diag(TheCall->getBeginLoc(),
6315                             diag::err_shufflevector_argument_too_large)
6316                        << TheCall->getArg(i)->getSourceRange());
6317   }
6318 
6319   SmallVector<Expr*, 32> exprs;
6320 
6321   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6322     exprs.push_back(TheCall->getArg(i));
6323     TheCall->setArg(i, nullptr);
6324   }
6325 
6326   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6327                                          TheCall->getCallee()->getBeginLoc(),
6328                                          TheCall->getRParenLoc());
6329 }
6330 
6331 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6332 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6333                                        SourceLocation BuiltinLoc,
6334                                        SourceLocation RParenLoc) {
6335   ExprValueKind VK = VK_RValue;
6336   ExprObjectKind OK = OK_Ordinary;
6337   QualType DstTy = TInfo->getType();
6338   QualType SrcTy = E->getType();
6339 
6340   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6341     return ExprError(Diag(BuiltinLoc,
6342                           diag::err_convertvector_non_vector)
6343                      << E->getSourceRange());
6344   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6345     return ExprError(Diag(BuiltinLoc,
6346                           diag::err_convertvector_non_vector_type));
6347 
6348   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6349     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6350     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6351     if (SrcElts != DstElts)
6352       return ExprError(Diag(BuiltinLoc,
6353                             diag::err_convertvector_incompatible_vector)
6354                        << E->getSourceRange());
6355   }
6356 
6357   return new (Context)
6358       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6359 }
6360 
6361 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6362 // This is declared to take (const void*, ...) and can take two
6363 // optional constant int args.
6364 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6365   unsigned NumArgs = TheCall->getNumArgs();
6366 
6367   if (NumArgs > 3)
6368     return Diag(TheCall->getEndLoc(),
6369                 diag::err_typecheck_call_too_many_args_at_most)
6370            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6371 
6372   // Argument 0 is checked for us and the remaining arguments must be
6373   // constant integers.
6374   for (unsigned i = 1; i != NumArgs; ++i)
6375     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6376       return true;
6377 
6378   return false;
6379 }
6380 
6381 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6382 // __assume does not evaluate its arguments, and should warn if its argument
6383 // has side effects.
6384 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6385   Expr *Arg = TheCall->getArg(0);
6386   if (Arg->isInstantiationDependent()) return false;
6387 
6388   if (Arg->HasSideEffects(Context))
6389     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6390         << Arg->getSourceRange()
6391         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6392 
6393   return false;
6394 }
6395 
6396 /// Handle __builtin_alloca_with_align. This is declared
6397 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6398 /// than 8.
6399 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6400   // The alignment must be a constant integer.
6401   Expr *Arg = TheCall->getArg(1);
6402 
6403   // We can't check the value of a dependent argument.
6404   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6405     if (const auto *UE =
6406             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6407       if (UE->getKind() == UETT_AlignOf ||
6408           UE->getKind() == UETT_PreferredAlignOf)
6409         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6410             << Arg->getSourceRange();
6411 
6412     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6413 
6414     if (!Result.isPowerOf2())
6415       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6416              << Arg->getSourceRange();
6417 
6418     if (Result < Context.getCharWidth())
6419       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6420              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6421 
6422     if (Result > std::numeric_limits<int32_t>::max())
6423       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6424              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6425   }
6426 
6427   return false;
6428 }
6429 
6430 /// Handle __builtin_assume_aligned. This is declared
6431 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6432 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6433   unsigned NumArgs = TheCall->getNumArgs();
6434 
6435   if (NumArgs > 3)
6436     return Diag(TheCall->getEndLoc(),
6437                 diag::err_typecheck_call_too_many_args_at_most)
6438            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6439 
6440   // The alignment must be a constant integer.
6441   Expr *Arg = TheCall->getArg(1);
6442 
6443   // We can't check the value of a dependent argument.
6444   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6445     llvm::APSInt Result;
6446     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6447       return true;
6448 
6449     if (!Result.isPowerOf2())
6450       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6451              << Arg->getSourceRange();
6452 
6453     if (Result > Sema::MaximumAlignment)
6454       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6455           << Arg->getSourceRange() << Sema::MaximumAlignment;
6456   }
6457 
6458   if (NumArgs > 2) {
6459     ExprResult Arg(TheCall->getArg(2));
6460     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6461       Context.getSizeType(), false);
6462     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6463     if (Arg.isInvalid()) return true;
6464     TheCall->setArg(2, Arg.get());
6465   }
6466 
6467   return false;
6468 }
6469 
6470 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6471   unsigned BuiltinID =
6472       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6473   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6474 
6475   unsigned NumArgs = TheCall->getNumArgs();
6476   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6477   if (NumArgs < NumRequiredArgs) {
6478     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6479            << 0 /* function call */ << NumRequiredArgs << NumArgs
6480            << TheCall->getSourceRange();
6481   }
6482   if (NumArgs >= NumRequiredArgs + 0x100) {
6483     return Diag(TheCall->getEndLoc(),
6484                 diag::err_typecheck_call_too_many_args_at_most)
6485            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6486            << TheCall->getSourceRange();
6487   }
6488   unsigned i = 0;
6489 
6490   // For formatting call, check buffer arg.
6491   if (!IsSizeCall) {
6492     ExprResult Arg(TheCall->getArg(i));
6493     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6494         Context, Context.VoidPtrTy, false);
6495     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6496     if (Arg.isInvalid())
6497       return true;
6498     TheCall->setArg(i, Arg.get());
6499     i++;
6500   }
6501 
6502   // Check string literal arg.
6503   unsigned FormatIdx = i;
6504   {
6505     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6506     if (Arg.isInvalid())
6507       return true;
6508     TheCall->setArg(i, Arg.get());
6509     i++;
6510   }
6511 
6512   // Make sure variadic args are scalar.
6513   unsigned FirstDataArg = i;
6514   while (i < NumArgs) {
6515     ExprResult Arg = DefaultVariadicArgumentPromotion(
6516         TheCall->getArg(i), VariadicFunction, nullptr);
6517     if (Arg.isInvalid())
6518       return true;
6519     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6520     if (ArgSize.getQuantity() >= 0x100) {
6521       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6522              << i << (int)ArgSize.getQuantity() << 0xff
6523              << TheCall->getSourceRange();
6524     }
6525     TheCall->setArg(i, Arg.get());
6526     i++;
6527   }
6528 
6529   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6530   // call to avoid duplicate diagnostics.
6531   if (!IsSizeCall) {
6532     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6533     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6534     bool Success = CheckFormatArguments(
6535         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6536         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6537         CheckedVarArgs);
6538     if (!Success)
6539       return true;
6540   }
6541 
6542   if (IsSizeCall) {
6543     TheCall->setType(Context.getSizeType());
6544   } else {
6545     TheCall->setType(Context.VoidPtrTy);
6546   }
6547   return false;
6548 }
6549 
6550 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6551 /// TheCall is a constant expression.
6552 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6553                                   llvm::APSInt &Result) {
6554   Expr *Arg = TheCall->getArg(ArgNum);
6555   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6556   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6557 
6558   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6559 
6560   Optional<llvm::APSInt> R;
6561   if (!(R = Arg->getIntegerConstantExpr(Context)))
6562     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6563            << FDecl->getDeclName() << Arg->getSourceRange();
6564   Result = *R;
6565   return false;
6566 }
6567 
6568 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6569 /// TheCall is a constant expression in the range [Low, High].
6570 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6571                                        int Low, int High, bool RangeIsError) {
6572   if (isConstantEvaluated())
6573     return false;
6574   llvm::APSInt Result;
6575 
6576   // We can't check the value of a dependent argument.
6577   Expr *Arg = TheCall->getArg(ArgNum);
6578   if (Arg->isTypeDependent() || Arg->isValueDependent())
6579     return false;
6580 
6581   // Check constant-ness first.
6582   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6583     return true;
6584 
6585   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6586     if (RangeIsError)
6587       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6588              << Result.toString(10) << Low << High << Arg->getSourceRange();
6589     else
6590       // Defer the warning until we know if the code will be emitted so that
6591       // dead code can ignore this.
6592       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6593                           PDiag(diag::warn_argument_invalid_range)
6594                               << Result.toString(10) << Low << High
6595                               << Arg->getSourceRange());
6596   }
6597 
6598   return false;
6599 }
6600 
6601 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6602 /// TheCall is a constant expression is a multiple of Num..
6603 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6604                                           unsigned Num) {
6605   llvm::APSInt Result;
6606 
6607   // We can't check the value of a dependent argument.
6608   Expr *Arg = TheCall->getArg(ArgNum);
6609   if (Arg->isTypeDependent() || Arg->isValueDependent())
6610     return false;
6611 
6612   // Check constant-ness first.
6613   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6614     return true;
6615 
6616   if (Result.getSExtValue() % Num != 0)
6617     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6618            << Num << Arg->getSourceRange();
6619 
6620   return false;
6621 }
6622 
6623 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6624 /// constant expression representing a power of 2.
6625 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6626   llvm::APSInt Result;
6627 
6628   // We can't check the value of a dependent argument.
6629   Expr *Arg = TheCall->getArg(ArgNum);
6630   if (Arg->isTypeDependent() || Arg->isValueDependent())
6631     return false;
6632 
6633   // Check constant-ness first.
6634   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6635     return true;
6636 
6637   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6638   // and only if x is a power of 2.
6639   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6640     return false;
6641 
6642   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6643          << Arg->getSourceRange();
6644 }
6645 
6646 static bool IsShiftedByte(llvm::APSInt Value) {
6647   if (Value.isNegative())
6648     return false;
6649 
6650   // Check if it's a shifted byte, by shifting it down
6651   while (true) {
6652     // If the value fits in the bottom byte, the check passes.
6653     if (Value < 0x100)
6654       return true;
6655 
6656     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6657     // fails.
6658     if ((Value & 0xFF) != 0)
6659       return false;
6660 
6661     // If the bottom 8 bits are all 0, but something above that is nonzero,
6662     // then shifting the value right by 8 bits won't affect whether it's a
6663     // shifted byte or not. So do that, and go round again.
6664     Value >>= 8;
6665   }
6666 }
6667 
6668 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6669 /// a constant expression representing an arbitrary byte value shifted left by
6670 /// a multiple of 8 bits.
6671 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6672                                              unsigned ArgBits) {
6673   llvm::APSInt Result;
6674 
6675   // We can't check the value of a dependent argument.
6676   Expr *Arg = TheCall->getArg(ArgNum);
6677   if (Arg->isTypeDependent() || Arg->isValueDependent())
6678     return false;
6679 
6680   // Check constant-ness first.
6681   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6682     return true;
6683 
6684   // Truncate to the given size.
6685   Result = Result.getLoBits(ArgBits);
6686   Result.setIsUnsigned(true);
6687 
6688   if (IsShiftedByte(Result))
6689     return false;
6690 
6691   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6692          << Arg->getSourceRange();
6693 }
6694 
6695 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6696 /// TheCall is a constant expression representing either a shifted byte value,
6697 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6698 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6699 /// Arm MVE intrinsics.
6700 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6701                                                    int ArgNum,
6702                                                    unsigned ArgBits) {
6703   llvm::APSInt Result;
6704 
6705   // We can't check the value of a dependent argument.
6706   Expr *Arg = TheCall->getArg(ArgNum);
6707   if (Arg->isTypeDependent() || Arg->isValueDependent())
6708     return false;
6709 
6710   // Check constant-ness first.
6711   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6712     return true;
6713 
6714   // Truncate to the given size.
6715   Result = Result.getLoBits(ArgBits);
6716   Result.setIsUnsigned(true);
6717 
6718   // Check to see if it's in either of the required forms.
6719   if (IsShiftedByte(Result) ||
6720       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6721     return false;
6722 
6723   return Diag(TheCall->getBeginLoc(),
6724               diag::err_argument_not_shifted_byte_or_xxff)
6725          << Arg->getSourceRange();
6726 }
6727 
6728 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6729 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6730   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6731     if (checkArgCount(*this, TheCall, 2))
6732       return true;
6733     Expr *Arg0 = TheCall->getArg(0);
6734     Expr *Arg1 = TheCall->getArg(1);
6735 
6736     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6737     if (FirstArg.isInvalid())
6738       return true;
6739     QualType FirstArgType = FirstArg.get()->getType();
6740     if (!FirstArgType->isAnyPointerType())
6741       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6742                << "first" << FirstArgType << Arg0->getSourceRange();
6743     TheCall->setArg(0, FirstArg.get());
6744 
6745     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6746     if (SecArg.isInvalid())
6747       return true;
6748     QualType SecArgType = SecArg.get()->getType();
6749     if (!SecArgType->isIntegerType())
6750       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6751                << "second" << SecArgType << Arg1->getSourceRange();
6752 
6753     // Derive the return type from the pointer argument.
6754     TheCall->setType(FirstArgType);
6755     return false;
6756   }
6757 
6758   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6759     if (checkArgCount(*this, TheCall, 2))
6760       return true;
6761 
6762     Expr *Arg0 = TheCall->getArg(0);
6763     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6764     if (FirstArg.isInvalid())
6765       return true;
6766     QualType FirstArgType = FirstArg.get()->getType();
6767     if (!FirstArgType->isAnyPointerType())
6768       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6769                << "first" << FirstArgType << Arg0->getSourceRange();
6770     TheCall->setArg(0, FirstArg.get());
6771 
6772     // Derive the return type from the pointer argument.
6773     TheCall->setType(FirstArgType);
6774 
6775     // Second arg must be an constant in range [0,15]
6776     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6777   }
6778 
6779   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6780     if (checkArgCount(*this, TheCall, 2))
6781       return true;
6782     Expr *Arg0 = TheCall->getArg(0);
6783     Expr *Arg1 = TheCall->getArg(1);
6784 
6785     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6786     if (FirstArg.isInvalid())
6787       return true;
6788     QualType FirstArgType = FirstArg.get()->getType();
6789     if (!FirstArgType->isAnyPointerType())
6790       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6791                << "first" << FirstArgType << Arg0->getSourceRange();
6792 
6793     QualType SecArgType = Arg1->getType();
6794     if (!SecArgType->isIntegerType())
6795       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6796                << "second" << SecArgType << Arg1->getSourceRange();
6797     TheCall->setType(Context.IntTy);
6798     return false;
6799   }
6800 
6801   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6802       BuiltinID == AArch64::BI__builtin_arm_stg) {
6803     if (checkArgCount(*this, TheCall, 1))
6804       return true;
6805     Expr *Arg0 = TheCall->getArg(0);
6806     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6807     if (FirstArg.isInvalid())
6808       return true;
6809 
6810     QualType FirstArgType = FirstArg.get()->getType();
6811     if (!FirstArgType->isAnyPointerType())
6812       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6813                << "first" << FirstArgType << Arg0->getSourceRange();
6814     TheCall->setArg(0, FirstArg.get());
6815 
6816     // Derive the return type from the pointer argument.
6817     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6818       TheCall->setType(FirstArgType);
6819     return false;
6820   }
6821 
6822   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6823     Expr *ArgA = TheCall->getArg(0);
6824     Expr *ArgB = TheCall->getArg(1);
6825 
6826     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6827     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6828 
6829     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6830       return true;
6831 
6832     QualType ArgTypeA = ArgExprA.get()->getType();
6833     QualType ArgTypeB = ArgExprB.get()->getType();
6834 
6835     auto isNull = [&] (Expr *E) -> bool {
6836       return E->isNullPointerConstant(
6837                         Context, Expr::NPC_ValueDependentIsNotNull); };
6838 
6839     // argument should be either a pointer or null
6840     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6841       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6842         << "first" << ArgTypeA << ArgA->getSourceRange();
6843 
6844     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6845       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6846         << "second" << ArgTypeB << ArgB->getSourceRange();
6847 
6848     // Ensure Pointee types are compatible
6849     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6850         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6851       QualType pointeeA = ArgTypeA->getPointeeType();
6852       QualType pointeeB = ArgTypeB->getPointeeType();
6853       if (!Context.typesAreCompatible(
6854              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6855              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6856         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6857           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6858           << ArgB->getSourceRange();
6859       }
6860     }
6861 
6862     // at least one argument should be pointer type
6863     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6864       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6865         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6866 
6867     if (isNull(ArgA)) // adopt type of the other pointer
6868       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6869 
6870     if (isNull(ArgB))
6871       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6872 
6873     TheCall->setArg(0, ArgExprA.get());
6874     TheCall->setArg(1, ArgExprB.get());
6875     TheCall->setType(Context.LongLongTy);
6876     return false;
6877   }
6878   assert(false && "Unhandled ARM MTE intrinsic");
6879   return true;
6880 }
6881 
6882 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6883 /// TheCall is an ARM/AArch64 special register string literal.
6884 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6885                                     int ArgNum, unsigned ExpectedFieldNum,
6886                                     bool AllowName) {
6887   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6888                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6889                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6890                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6891                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6892                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6893   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6894                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6895                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6896                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6897                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6898                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6899   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6900 
6901   // We can't check the value of a dependent argument.
6902   Expr *Arg = TheCall->getArg(ArgNum);
6903   if (Arg->isTypeDependent() || Arg->isValueDependent())
6904     return false;
6905 
6906   // Check if the argument is a string literal.
6907   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6908     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6909            << Arg->getSourceRange();
6910 
6911   // Check the type of special register given.
6912   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6913   SmallVector<StringRef, 6> Fields;
6914   Reg.split(Fields, ":");
6915 
6916   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6917     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6918            << Arg->getSourceRange();
6919 
6920   // If the string is the name of a register then we cannot check that it is
6921   // valid here but if the string is of one the forms described in ACLE then we
6922   // can check that the supplied fields are integers and within the valid
6923   // ranges.
6924   if (Fields.size() > 1) {
6925     bool FiveFields = Fields.size() == 5;
6926 
6927     bool ValidString = true;
6928     if (IsARMBuiltin) {
6929       ValidString &= Fields[0].startswith_lower("cp") ||
6930                      Fields[0].startswith_lower("p");
6931       if (ValidString)
6932         Fields[0] =
6933           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6934 
6935       ValidString &= Fields[2].startswith_lower("c");
6936       if (ValidString)
6937         Fields[2] = Fields[2].drop_front(1);
6938 
6939       if (FiveFields) {
6940         ValidString &= Fields[3].startswith_lower("c");
6941         if (ValidString)
6942           Fields[3] = Fields[3].drop_front(1);
6943       }
6944     }
6945 
6946     SmallVector<int, 5> Ranges;
6947     if (FiveFields)
6948       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6949     else
6950       Ranges.append({15, 7, 15});
6951 
6952     for (unsigned i=0; i<Fields.size(); ++i) {
6953       int IntField;
6954       ValidString &= !Fields[i].getAsInteger(10, IntField);
6955       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6956     }
6957 
6958     if (!ValidString)
6959       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6960              << Arg->getSourceRange();
6961   } else if (IsAArch64Builtin && Fields.size() == 1) {
6962     // If the register name is one of those that appear in the condition below
6963     // and the special register builtin being used is one of the write builtins,
6964     // then we require that the argument provided for writing to the register
6965     // is an integer constant expression. This is because it will be lowered to
6966     // an MSR (immediate) instruction, so we need to know the immediate at
6967     // compile time.
6968     if (TheCall->getNumArgs() != 2)
6969       return false;
6970 
6971     std::string RegLower = Reg.lower();
6972     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6973         RegLower != "pan" && RegLower != "uao")
6974       return false;
6975 
6976     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6977   }
6978 
6979   return false;
6980 }
6981 
6982 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
6983 /// Emit an error and return true on failure; return false on success.
6984 /// TypeStr is a string containing the type descriptor of the value returned by
6985 /// the builtin and the descriptors of the expected type of the arguments.
6986 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
6987 
6988   assert((TypeStr[0] != '\0') &&
6989          "Invalid types in PPC MMA builtin declaration");
6990 
6991   unsigned Mask = 0;
6992   unsigned ArgNum = 0;
6993 
6994   // The first type in TypeStr is the type of the value returned by the
6995   // builtin. So we first read that type and change the type of TheCall.
6996   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6997   TheCall->setType(type);
6998 
6999   while (*TypeStr != '\0') {
7000     Mask = 0;
7001     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7002     if (ArgNum >= TheCall->getNumArgs()) {
7003       ArgNum++;
7004       break;
7005     }
7006 
7007     Expr *Arg = TheCall->getArg(ArgNum);
7008     QualType ArgType = Arg->getType();
7009 
7010     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7011         (!ExpectedType->isVoidPointerType() &&
7012            ArgType.getCanonicalType() != ExpectedType))
7013       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7014              << ArgType << ExpectedType << 1 << 0 << 0;
7015 
7016     // If the value of the Mask is not 0, we have a constraint in the size of
7017     // the integer argument so here we ensure the argument is a constant that
7018     // is in the valid range.
7019     if (Mask != 0 &&
7020         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7021       return true;
7022 
7023     ArgNum++;
7024   }
7025 
7026   // In case we exited early from the previous loop, there are other types to
7027   // read from TypeStr. So we need to read them all to ensure we have the right
7028   // number of arguments in TheCall and if it is not the case, to display a
7029   // better error message.
7030   while (*TypeStr != '\0') {
7031     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7032     ArgNum++;
7033   }
7034   if (checkArgCount(*this, TheCall, ArgNum))
7035     return true;
7036 
7037   return false;
7038 }
7039 
7040 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7041 /// This checks that the target supports __builtin_longjmp and
7042 /// that val is a constant 1.
7043 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7044   if (!Context.getTargetInfo().hasSjLjLowering())
7045     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7046            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7047 
7048   Expr *Arg = TheCall->getArg(1);
7049   llvm::APSInt Result;
7050 
7051   // TODO: This is less than ideal. Overload this to take a value.
7052   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7053     return true;
7054 
7055   if (Result != 1)
7056     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7057            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7058 
7059   return false;
7060 }
7061 
7062 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7063 /// This checks that the target supports __builtin_setjmp.
7064 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7065   if (!Context.getTargetInfo().hasSjLjLowering())
7066     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7067            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7068   return false;
7069 }
7070 
7071 namespace {
7072 
7073 class UncoveredArgHandler {
7074   enum { Unknown = -1, AllCovered = -2 };
7075 
7076   signed FirstUncoveredArg = Unknown;
7077   SmallVector<const Expr *, 4> DiagnosticExprs;
7078 
7079 public:
7080   UncoveredArgHandler() = default;
7081 
7082   bool hasUncoveredArg() const {
7083     return (FirstUncoveredArg >= 0);
7084   }
7085 
7086   unsigned getUncoveredArg() const {
7087     assert(hasUncoveredArg() && "no uncovered argument");
7088     return FirstUncoveredArg;
7089   }
7090 
7091   void setAllCovered() {
7092     // A string has been found with all arguments covered, so clear out
7093     // the diagnostics.
7094     DiagnosticExprs.clear();
7095     FirstUncoveredArg = AllCovered;
7096   }
7097 
7098   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7099     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7100 
7101     // Don't update if a previous string covers all arguments.
7102     if (FirstUncoveredArg == AllCovered)
7103       return;
7104 
7105     // UncoveredArgHandler tracks the highest uncovered argument index
7106     // and with it all the strings that match this index.
7107     if (NewFirstUncoveredArg == FirstUncoveredArg)
7108       DiagnosticExprs.push_back(StrExpr);
7109     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7110       DiagnosticExprs.clear();
7111       DiagnosticExprs.push_back(StrExpr);
7112       FirstUncoveredArg = NewFirstUncoveredArg;
7113     }
7114   }
7115 
7116   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7117 };
7118 
7119 enum StringLiteralCheckType {
7120   SLCT_NotALiteral,
7121   SLCT_UncheckedLiteral,
7122   SLCT_CheckedLiteral
7123 };
7124 
7125 } // namespace
7126 
7127 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7128                                      BinaryOperatorKind BinOpKind,
7129                                      bool AddendIsRight) {
7130   unsigned BitWidth = Offset.getBitWidth();
7131   unsigned AddendBitWidth = Addend.getBitWidth();
7132   // There might be negative interim results.
7133   if (Addend.isUnsigned()) {
7134     Addend = Addend.zext(++AddendBitWidth);
7135     Addend.setIsSigned(true);
7136   }
7137   // Adjust the bit width of the APSInts.
7138   if (AddendBitWidth > BitWidth) {
7139     Offset = Offset.sext(AddendBitWidth);
7140     BitWidth = AddendBitWidth;
7141   } else if (BitWidth > AddendBitWidth) {
7142     Addend = Addend.sext(BitWidth);
7143   }
7144 
7145   bool Ov = false;
7146   llvm::APSInt ResOffset = Offset;
7147   if (BinOpKind == BO_Add)
7148     ResOffset = Offset.sadd_ov(Addend, Ov);
7149   else {
7150     assert(AddendIsRight && BinOpKind == BO_Sub &&
7151            "operator must be add or sub with addend on the right");
7152     ResOffset = Offset.ssub_ov(Addend, Ov);
7153   }
7154 
7155   // We add an offset to a pointer here so we should support an offset as big as
7156   // possible.
7157   if (Ov) {
7158     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7159            "index (intermediate) result too big");
7160     Offset = Offset.sext(2 * BitWidth);
7161     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7162     return;
7163   }
7164 
7165   Offset = ResOffset;
7166 }
7167 
7168 namespace {
7169 
7170 // This is a wrapper class around StringLiteral to support offsetted string
7171 // literals as format strings. It takes the offset into account when returning
7172 // the string and its length or the source locations to display notes correctly.
7173 class FormatStringLiteral {
7174   const StringLiteral *FExpr;
7175   int64_t Offset;
7176 
7177  public:
7178   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7179       : FExpr(fexpr), Offset(Offset) {}
7180 
7181   StringRef getString() const {
7182     return FExpr->getString().drop_front(Offset);
7183   }
7184 
7185   unsigned getByteLength() const {
7186     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7187   }
7188 
7189   unsigned getLength() const { return FExpr->getLength() - Offset; }
7190   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7191 
7192   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7193 
7194   QualType getType() const { return FExpr->getType(); }
7195 
7196   bool isAscii() const { return FExpr->isAscii(); }
7197   bool isWide() const { return FExpr->isWide(); }
7198   bool isUTF8() const { return FExpr->isUTF8(); }
7199   bool isUTF16() const { return FExpr->isUTF16(); }
7200   bool isUTF32() const { return FExpr->isUTF32(); }
7201   bool isPascal() const { return FExpr->isPascal(); }
7202 
7203   SourceLocation getLocationOfByte(
7204       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7205       const TargetInfo &Target, unsigned *StartToken = nullptr,
7206       unsigned *StartTokenByteOffset = nullptr) const {
7207     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7208                                     StartToken, StartTokenByteOffset);
7209   }
7210 
7211   SourceLocation getBeginLoc() const LLVM_READONLY {
7212     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7213   }
7214 
7215   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7216 };
7217 
7218 }  // namespace
7219 
7220 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7221                               const Expr *OrigFormatExpr,
7222                               ArrayRef<const Expr *> Args,
7223                               bool HasVAListArg, unsigned format_idx,
7224                               unsigned firstDataArg,
7225                               Sema::FormatStringType Type,
7226                               bool inFunctionCall,
7227                               Sema::VariadicCallType CallType,
7228                               llvm::SmallBitVector &CheckedVarArgs,
7229                               UncoveredArgHandler &UncoveredArg,
7230                               bool IgnoreStringsWithoutSpecifiers);
7231 
7232 // Determine if an expression is a string literal or constant string.
7233 // If this function returns false on the arguments to a function expecting a
7234 // format string, we will usually need to emit a warning.
7235 // True string literals are then checked by CheckFormatString.
7236 static StringLiteralCheckType
7237 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7238                       bool HasVAListArg, unsigned format_idx,
7239                       unsigned firstDataArg, Sema::FormatStringType Type,
7240                       Sema::VariadicCallType CallType, bool InFunctionCall,
7241                       llvm::SmallBitVector &CheckedVarArgs,
7242                       UncoveredArgHandler &UncoveredArg,
7243                       llvm::APSInt Offset,
7244                       bool IgnoreStringsWithoutSpecifiers = false) {
7245   if (S.isConstantEvaluated())
7246     return SLCT_NotALiteral;
7247  tryAgain:
7248   assert(Offset.isSigned() && "invalid offset");
7249 
7250   if (E->isTypeDependent() || E->isValueDependent())
7251     return SLCT_NotALiteral;
7252 
7253   E = E->IgnoreParenCasts();
7254 
7255   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7256     // Technically -Wformat-nonliteral does not warn about this case.
7257     // The behavior of printf and friends in this case is implementation
7258     // dependent.  Ideally if the format string cannot be null then
7259     // it should have a 'nonnull' attribute in the function prototype.
7260     return SLCT_UncheckedLiteral;
7261 
7262   switch (E->getStmtClass()) {
7263   case Stmt::BinaryConditionalOperatorClass:
7264   case Stmt::ConditionalOperatorClass: {
7265     // The expression is a literal if both sub-expressions were, and it was
7266     // completely checked only if both sub-expressions were checked.
7267     const AbstractConditionalOperator *C =
7268         cast<AbstractConditionalOperator>(E);
7269 
7270     // Determine whether it is necessary to check both sub-expressions, for
7271     // example, because the condition expression is a constant that can be
7272     // evaluated at compile time.
7273     bool CheckLeft = true, CheckRight = true;
7274 
7275     bool Cond;
7276     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7277                                                  S.isConstantEvaluated())) {
7278       if (Cond)
7279         CheckRight = false;
7280       else
7281         CheckLeft = false;
7282     }
7283 
7284     // We need to maintain the offsets for the right and the left hand side
7285     // separately to check if every possible indexed expression is a valid
7286     // string literal. They might have different offsets for different string
7287     // literals in the end.
7288     StringLiteralCheckType Left;
7289     if (!CheckLeft)
7290       Left = SLCT_UncheckedLiteral;
7291     else {
7292       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7293                                    HasVAListArg, format_idx, firstDataArg,
7294                                    Type, CallType, InFunctionCall,
7295                                    CheckedVarArgs, UncoveredArg, Offset,
7296                                    IgnoreStringsWithoutSpecifiers);
7297       if (Left == SLCT_NotALiteral || !CheckRight) {
7298         return Left;
7299       }
7300     }
7301 
7302     StringLiteralCheckType Right = checkFormatStringExpr(
7303         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7304         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7305         IgnoreStringsWithoutSpecifiers);
7306 
7307     return (CheckLeft && Left < Right) ? Left : Right;
7308   }
7309 
7310   case Stmt::ImplicitCastExprClass:
7311     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7312     goto tryAgain;
7313 
7314   case Stmt::OpaqueValueExprClass:
7315     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7316       E = src;
7317       goto tryAgain;
7318     }
7319     return SLCT_NotALiteral;
7320 
7321   case Stmt::PredefinedExprClass:
7322     // While __func__, etc., are technically not string literals, they
7323     // cannot contain format specifiers and thus are not a security
7324     // liability.
7325     return SLCT_UncheckedLiteral;
7326 
7327   case Stmt::DeclRefExprClass: {
7328     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7329 
7330     // As an exception, do not flag errors for variables binding to
7331     // const string literals.
7332     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7333       bool isConstant = false;
7334       QualType T = DR->getType();
7335 
7336       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7337         isConstant = AT->getElementType().isConstant(S.Context);
7338       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7339         isConstant = T.isConstant(S.Context) &&
7340                      PT->getPointeeType().isConstant(S.Context);
7341       } else if (T->isObjCObjectPointerType()) {
7342         // In ObjC, there is usually no "const ObjectPointer" type,
7343         // so don't check if the pointee type is constant.
7344         isConstant = T.isConstant(S.Context);
7345       }
7346 
7347       if (isConstant) {
7348         if (const Expr *Init = VD->getAnyInitializer()) {
7349           // Look through initializers like const char c[] = { "foo" }
7350           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7351             if (InitList->isStringLiteralInit())
7352               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7353           }
7354           return checkFormatStringExpr(S, Init, Args,
7355                                        HasVAListArg, format_idx,
7356                                        firstDataArg, Type, CallType,
7357                                        /*InFunctionCall*/ false, CheckedVarArgs,
7358                                        UncoveredArg, Offset);
7359         }
7360       }
7361 
7362       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7363       // special check to see if the format string is a function parameter
7364       // of the function calling the printf function.  If the function
7365       // has an attribute indicating it is a printf-like function, then we
7366       // should suppress warnings concerning non-literals being used in a call
7367       // to a vprintf function.  For example:
7368       //
7369       // void
7370       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7371       //      va_list ap;
7372       //      va_start(ap, fmt);
7373       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7374       //      ...
7375       // }
7376       if (HasVAListArg) {
7377         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7378           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7379             int PVIndex = PV->getFunctionScopeIndex() + 1;
7380             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7381               // adjust for implicit parameter
7382               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7383                 if (MD->isInstance())
7384                   ++PVIndex;
7385               // We also check if the formats are compatible.
7386               // We can't pass a 'scanf' string to a 'printf' function.
7387               if (PVIndex == PVFormat->getFormatIdx() &&
7388                   Type == S.GetFormatStringType(PVFormat))
7389                 return SLCT_UncheckedLiteral;
7390             }
7391           }
7392         }
7393       }
7394     }
7395 
7396     return SLCT_NotALiteral;
7397   }
7398 
7399   case Stmt::CallExprClass:
7400   case Stmt::CXXMemberCallExprClass: {
7401     const CallExpr *CE = cast<CallExpr>(E);
7402     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7403       bool IsFirst = true;
7404       StringLiteralCheckType CommonResult;
7405       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7406         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7407         StringLiteralCheckType Result = checkFormatStringExpr(
7408             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7409             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7410             IgnoreStringsWithoutSpecifiers);
7411         if (IsFirst) {
7412           CommonResult = Result;
7413           IsFirst = false;
7414         }
7415       }
7416       if (!IsFirst)
7417         return CommonResult;
7418 
7419       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7420         unsigned BuiltinID = FD->getBuiltinID();
7421         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7422             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7423           const Expr *Arg = CE->getArg(0);
7424           return checkFormatStringExpr(S, Arg, Args,
7425                                        HasVAListArg, format_idx,
7426                                        firstDataArg, Type, CallType,
7427                                        InFunctionCall, CheckedVarArgs,
7428                                        UncoveredArg, Offset,
7429                                        IgnoreStringsWithoutSpecifiers);
7430         }
7431       }
7432     }
7433 
7434     return SLCT_NotALiteral;
7435   }
7436   case Stmt::ObjCMessageExprClass: {
7437     const auto *ME = cast<ObjCMessageExpr>(E);
7438     if (const auto *MD = ME->getMethodDecl()) {
7439       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7440         // As a special case heuristic, if we're using the method -[NSBundle
7441         // localizedStringForKey:value:table:], ignore any key strings that lack
7442         // format specifiers. The idea is that if the key doesn't have any
7443         // format specifiers then its probably just a key to map to the
7444         // localized strings. If it does have format specifiers though, then its
7445         // likely that the text of the key is the format string in the
7446         // programmer's language, and should be checked.
7447         const ObjCInterfaceDecl *IFace;
7448         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7449             IFace->getIdentifier()->isStr("NSBundle") &&
7450             MD->getSelector().isKeywordSelector(
7451                 {"localizedStringForKey", "value", "table"})) {
7452           IgnoreStringsWithoutSpecifiers = true;
7453         }
7454 
7455         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7456         return checkFormatStringExpr(
7457             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7458             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7459             IgnoreStringsWithoutSpecifiers);
7460       }
7461     }
7462 
7463     return SLCT_NotALiteral;
7464   }
7465   case Stmt::ObjCStringLiteralClass:
7466   case Stmt::StringLiteralClass: {
7467     const StringLiteral *StrE = nullptr;
7468 
7469     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7470       StrE = ObjCFExpr->getString();
7471     else
7472       StrE = cast<StringLiteral>(E);
7473 
7474     if (StrE) {
7475       if (Offset.isNegative() || Offset > StrE->getLength()) {
7476         // TODO: It would be better to have an explicit warning for out of
7477         // bounds literals.
7478         return SLCT_NotALiteral;
7479       }
7480       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7481       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7482                         firstDataArg, Type, InFunctionCall, CallType,
7483                         CheckedVarArgs, UncoveredArg,
7484                         IgnoreStringsWithoutSpecifiers);
7485       return SLCT_CheckedLiteral;
7486     }
7487 
7488     return SLCT_NotALiteral;
7489   }
7490   case Stmt::BinaryOperatorClass: {
7491     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7492 
7493     // A string literal + an int offset is still a string literal.
7494     if (BinOp->isAdditiveOp()) {
7495       Expr::EvalResult LResult, RResult;
7496 
7497       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7498           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7499       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7500           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7501 
7502       if (LIsInt != RIsInt) {
7503         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7504 
7505         if (LIsInt) {
7506           if (BinOpKind == BO_Add) {
7507             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7508             E = BinOp->getRHS();
7509             goto tryAgain;
7510           }
7511         } else {
7512           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7513           E = BinOp->getLHS();
7514           goto tryAgain;
7515         }
7516       }
7517     }
7518 
7519     return SLCT_NotALiteral;
7520   }
7521   case Stmt::UnaryOperatorClass: {
7522     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7523     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7524     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7525       Expr::EvalResult IndexResult;
7526       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7527                                        Expr::SE_NoSideEffects,
7528                                        S.isConstantEvaluated())) {
7529         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7530                    /*RHS is int*/ true);
7531         E = ASE->getBase();
7532         goto tryAgain;
7533       }
7534     }
7535 
7536     return SLCT_NotALiteral;
7537   }
7538 
7539   default:
7540     return SLCT_NotALiteral;
7541   }
7542 }
7543 
7544 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7545   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7546       .Case("scanf", FST_Scanf)
7547       .Cases("printf", "printf0", FST_Printf)
7548       .Cases("NSString", "CFString", FST_NSString)
7549       .Case("strftime", FST_Strftime)
7550       .Case("strfmon", FST_Strfmon)
7551       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7552       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7553       .Case("os_trace", FST_OSLog)
7554       .Case("os_log", FST_OSLog)
7555       .Default(FST_Unknown);
7556 }
7557 
7558 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7559 /// functions) for correct use of format strings.
7560 /// Returns true if a format string has been fully checked.
7561 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7562                                 ArrayRef<const Expr *> Args,
7563                                 bool IsCXXMember,
7564                                 VariadicCallType CallType,
7565                                 SourceLocation Loc, SourceRange Range,
7566                                 llvm::SmallBitVector &CheckedVarArgs) {
7567   FormatStringInfo FSI;
7568   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7569     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7570                                 FSI.FirstDataArg, GetFormatStringType(Format),
7571                                 CallType, Loc, Range, CheckedVarArgs);
7572   return false;
7573 }
7574 
7575 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7576                                 bool HasVAListArg, unsigned format_idx,
7577                                 unsigned firstDataArg, FormatStringType Type,
7578                                 VariadicCallType CallType,
7579                                 SourceLocation Loc, SourceRange Range,
7580                                 llvm::SmallBitVector &CheckedVarArgs) {
7581   // CHECK: printf/scanf-like function is called with no format string.
7582   if (format_idx >= Args.size()) {
7583     Diag(Loc, diag::warn_missing_format_string) << Range;
7584     return false;
7585   }
7586 
7587   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7588 
7589   // CHECK: format string is not a string literal.
7590   //
7591   // Dynamically generated format strings are difficult to
7592   // automatically vet at compile time.  Requiring that format strings
7593   // are string literals: (1) permits the checking of format strings by
7594   // the compiler and thereby (2) can practically remove the source of
7595   // many format string exploits.
7596 
7597   // Format string can be either ObjC string (e.g. @"%d") or
7598   // C string (e.g. "%d")
7599   // ObjC string uses the same format specifiers as C string, so we can use
7600   // the same format string checking logic for both ObjC and C strings.
7601   UncoveredArgHandler UncoveredArg;
7602   StringLiteralCheckType CT =
7603       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7604                             format_idx, firstDataArg, Type, CallType,
7605                             /*IsFunctionCall*/ true, CheckedVarArgs,
7606                             UncoveredArg,
7607                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7608 
7609   // Generate a diagnostic where an uncovered argument is detected.
7610   if (UncoveredArg.hasUncoveredArg()) {
7611     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7612     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7613     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7614   }
7615 
7616   if (CT != SLCT_NotALiteral)
7617     // Literal format string found, check done!
7618     return CT == SLCT_CheckedLiteral;
7619 
7620   // Strftime is particular as it always uses a single 'time' argument,
7621   // so it is safe to pass a non-literal string.
7622   if (Type == FST_Strftime)
7623     return false;
7624 
7625   // Do not emit diag when the string param is a macro expansion and the
7626   // format is either NSString or CFString. This is a hack to prevent
7627   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7628   // which are usually used in place of NS and CF string literals.
7629   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7630   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7631     return false;
7632 
7633   // If there are no arguments specified, warn with -Wformat-security, otherwise
7634   // warn only with -Wformat-nonliteral.
7635   if (Args.size() == firstDataArg) {
7636     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7637       << OrigFormatExpr->getSourceRange();
7638     switch (Type) {
7639     default:
7640       break;
7641     case FST_Kprintf:
7642     case FST_FreeBSDKPrintf:
7643     case FST_Printf:
7644       Diag(FormatLoc, diag::note_format_security_fixit)
7645         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7646       break;
7647     case FST_NSString:
7648       Diag(FormatLoc, diag::note_format_security_fixit)
7649         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7650       break;
7651     }
7652   } else {
7653     Diag(FormatLoc, diag::warn_format_nonliteral)
7654       << OrigFormatExpr->getSourceRange();
7655   }
7656   return false;
7657 }
7658 
7659 namespace {
7660 
7661 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7662 protected:
7663   Sema &S;
7664   const FormatStringLiteral *FExpr;
7665   const Expr *OrigFormatExpr;
7666   const Sema::FormatStringType FSType;
7667   const unsigned FirstDataArg;
7668   const unsigned NumDataArgs;
7669   const char *Beg; // Start of format string.
7670   const bool HasVAListArg;
7671   ArrayRef<const Expr *> Args;
7672   unsigned FormatIdx;
7673   llvm::SmallBitVector CoveredArgs;
7674   bool usesPositionalArgs = false;
7675   bool atFirstArg = true;
7676   bool inFunctionCall;
7677   Sema::VariadicCallType CallType;
7678   llvm::SmallBitVector &CheckedVarArgs;
7679   UncoveredArgHandler &UncoveredArg;
7680 
7681 public:
7682   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7683                      const Expr *origFormatExpr,
7684                      const Sema::FormatStringType type, unsigned firstDataArg,
7685                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7686                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7687                      bool inFunctionCall, Sema::VariadicCallType callType,
7688                      llvm::SmallBitVector &CheckedVarArgs,
7689                      UncoveredArgHandler &UncoveredArg)
7690       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7691         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7692         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7693         inFunctionCall(inFunctionCall), CallType(callType),
7694         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7695     CoveredArgs.resize(numDataArgs);
7696     CoveredArgs.reset();
7697   }
7698 
7699   void DoneProcessing();
7700 
7701   void HandleIncompleteSpecifier(const char *startSpecifier,
7702                                  unsigned specifierLen) override;
7703 
7704   void HandleInvalidLengthModifier(
7705                            const analyze_format_string::FormatSpecifier &FS,
7706                            const analyze_format_string::ConversionSpecifier &CS,
7707                            const char *startSpecifier, unsigned specifierLen,
7708                            unsigned DiagID);
7709 
7710   void HandleNonStandardLengthModifier(
7711                     const analyze_format_string::FormatSpecifier &FS,
7712                     const char *startSpecifier, unsigned specifierLen);
7713 
7714   void HandleNonStandardConversionSpecifier(
7715                     const analyze_format_string::ConversionSpecifier &CS,
7716                     const char *startSpecifier, unsigned specifierLen);
7717 
7718   void HandlePosition(const char *startPos, unsigned posLen) override;
7719 
7720   void HandleInvalidPosition(const char *startSpecifier,
7721                              unsigned specifierLen,
7722                              analyze_format_string::PositionContext p) override;
7723 
7724   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7725 
7726   void HandleNullChar(const char *nullCharacter) override;
7727 
7728   template <typename Range>
7729   static void
7730   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7731                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7732                        bool IsStringLocation, Range StringRange,
7733                        ArrayRef<FixItHint> Fixit = None);
7734 
7735 protected:
7736   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7737                                         const char *startSpec,
7738                                         unsigned specifierLen,
7739                                         const char *csStart, unsigned csLen);
7740 
7741   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7742                                          const char *startSpec,
7743                                          unsigned specifierLen);
7744 
7745   SourceRange getFormatStringRange();
7746   CharSourceRange getSpecifierRange(const char *startSpecifier,
7747                                     unsigned specifierLen);
7748   SourceLocation getLocationOfByte(const char *x);
7749 
7750   const Expr *getDataArg(unsigned i) const;
7751 
7752   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7753                     const analyze_format_string::ConversionSpecifier &CS,
7754                     const char *startSpecifier, unsigned specifierLen,
7755                     unsigned argIndex);
7756 
7757   template <typename Range>
7758   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7759                             bool IsStringLocation, Range StringRange,
7760                             ArrayRef<FixItHint> Fixit = None);
7761 };
7762 
7763 } // namespace
7764 
7765 SourceRange CheckFormatHandler::getFormatStringRange() {
7766   return OrigFormatExpr->getSourceRange();
7767 }
7768 
7769 CharSourceRange CheckFormatHandler::
7770 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7771   SourceLocation Start = getLocationOfByte(startSpecifier);
7772   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7773 
7774   // Advance the end SourceLocation by one due to half-open ranges.
7775   End = End.getLocWithOffset(1);
7776 
7777   return CharSourceRange::getCharRange(Start, End);
7778 }
7779 
7780 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7781   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7782                                   S.getLangOpts(), S.Context.getTargetInfo());
7783 }
7784 
7785 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7786                                                    unsigned specifierLen){
7787   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7788                        getLocationOfByte(startSpecifier),
7789                        /*IsStringLocation*/true,
7790                        getSpecifierRange(startSpecifier, specifierLen));
7791 }
7792 
7793 void CheckFormatHandler::HandleInvalidLengthModifier(
7794     const analyze_format_string::FormatSpecifier &FS,
7795     const analyze_format_string::ConversionSpecifier &CS,
7796     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7797   using namespace analyze_format_string;
7798 
7799   const LengthModifier &LM = FS.getLengthModifier();
7800   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7801 
7802   // See if we know how to fix this length modifier.
7803   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7804   if (FixedLM) {
7805     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7806                          getLocationOfByte(LM.getStart()),
7807                          /*IsStringLocation*/true,
7808                          getSpecifierRange(startSpecifier, specifierLen));
7809 
7810     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7811       << FixedLM->toString()
7812       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7813 
7814   } else {
7815     FixItHint Hint;
7816     if (DiagID == diag::warn_format_nonsensical_length)
7817       Hint = FixItHint::CreateRemoval(LMRange);
7818 
7819     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7820                          getLocationOfByte(LM.getStart()),
7821                          /*IsStringLocation*/true,
7822                          getSpecifierRange(startSpecifier, specifierLen),
7823                          Hint);
7824   }
7825 }
7826 
7827 void CheckFormatHandler::HandleNonStandardLengthModifier(
7828     const analyze_format_string::FormatSpecifier &FS,
7829     const char *startSpecifier, unsigned specifierLen) {
7830   using namespace analyze_format_string;
7831 
7832   const LengthModifier &LM = FS.getLengthModifier();
7833   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7834 
7835   // See if we know how to fix this length modifier.
7836   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7837   if (FixedLM) {
7838     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7839                            << LM.toString() << 0,
7840                          getLocationOfByte(LM.getStart()),
7841                          /*IsStringLocation*/true,
7842                          getSpecifierRange(startSpecifier, specifierLen));
7843 
7844     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7845       << FixedLM->toString()
7846       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7847 
7848   } else {
7849     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7850                            << LM.toString() << 0,
7851                          getLocationOfByte(LM.getStart()),
7852                          /*IsStringLocation*/true,
7853                          getSpecifierRange(startSpecifier, specifierLen));
7854   }
7855 }
7856 
7857 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7858     const analyze_format_string::ConversionSpecifier &CS,
7859     const char *startSpecifier, unsigned specifierLen) {
7860   using namespace analyze_format_string;
7861 
7862   // See if we know how to fix this conversion specifier.
7863   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7864   if (FixedCS) {
7865     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7866                           << CS.toString() << /*conversion specifier*/1,
7867                          getLocationOfByte(CS.getStart()),
7868                          /*IsStringLocation*/true,
7869                          getSpecifierRange(startSpecifier, specifierLen));
7870 
7871     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7872     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7873       << FixedCS->toString()
7874       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7875   } else {
7876     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7877                           << CS.toString() << /*conversion specifier*/1,
7878                          getLocationOfByte(CS.getStart()),
7879                          /*IsStringLocation*/true,
7880                          getSpecifierRange(startSpecifier, specifierLen));
7881   }
7882 }
7883 
7884 void CheckFormatHandler::HandlePosition(const char *startPos,
7885                                         unsigned posLen) {
7886   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7887                                getLocationOfByte(startPos),
7888                                /*IsStringLocation*/true,
7889                                getSpecifierRange(startPos, posLen));
7890 }
7891 
7892 void
7893 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7894                                      analyze_format_string::PositionContext p) {
7895   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7896                          << (unsigned) p,
7897                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7898                        getSpecifierRange(startPos, posLen));
7899 }
7900 
7901 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7902                                             unsigned posLen) {
7903   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7904                                getLocationOfByte(startPos),
7905                                /*IsStringLocation*/true,
7906                                getSpecifierRange(startPos, posLen));
7907 }
7908 
7909 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7910   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7911     // The presence of a null character is likely an error.
7912     EmitFormatDiagnostic(
7913       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7914       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7915       getFormatStringRange());
7916   }
7917 }
7918 
7919 // Note that this may return NULL if there was an error parsing or building
7920 // one of the argument expressions.
7921 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7922   return Args[FirstDataArg + i];
7923 }
7924 
7925 void CheckFormatHandler::DoneProcessing() {
7926   // Does the number of data arguments exceed the number of
7927   // format conversions in the format string?
7928   if (!HasVAListArg) {
7929       // Find any arguments that weren't covered.
7930     CoveredArgs.flip();
7931     signed notCoveredArg = CoveredArgs.find_first();
7932     if (notCoveredArg >= 0) {
7933       assert((unsigned)notCoveredArg < NumDataArgs);
7934       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7935     } else {
7936       UncoveredArg.setAllCovered();
7937     }
7938   }
7939 }
7940 
7941 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7942                                    const Expr *ArgExpr) {
7943   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7944          "Invalid state");
7945 
7946   if (!ArgExpr)
7947     return;
7948 
7949   SourceLocation Loc = ArgExpr->getBeginLoc();
7950 
7951   if (S.getSourceManager().isInSystemMacro(Loc))
7952     return;
7953 
7954   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7955   for (auto E : DiagnosticExprs)
7956     PDiag << E->getSourceRange();
7957 
7958   CheckFormatHandler::EmitFormatDiagnostic(
7959                                   S, IsFunctionCall, DiagnosticExprs[0],
7960                                   PDiag, Loc, /*IsStringLocation*/false,
7961                                   DiagnosticExprs[0]->getSourceRange());
7962 }
7963 
7964 bool
7965 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7966                                                      SourceLocation Loc,
7967                                                      const char *startSpec,
7968                                                      unsigned specifierLen,
7969                                                      const char *csStart,
7970                                                      unsigned csLen) {
7971   bool keepGoing = true;
7972   if (argIndex < NumDataArgs) {
7973     // Consider the argument coverered, even though the specifier doesn't
7974     // make sense.
7975     CoveredArgs.set(argIndex);
7976   }
7977   else {
7978     // If argIndex exceeds the number of data arguments we
7979     // don't issue a warning because that is just a cascade of warnings (and
7980     // they may have intended '%%' anyway). We don't want to continue processing
7981     // the format string after this point, however, as we will like just get
7982     // gibberish when trying to match arguments.
7983     keepGoing = false;
7984   }
7985 
7986   StringRef Specifier(csStart, csLen);
7987 
7988   // If the specifier in non-printable, it could be the first byte of a UTF-8
7989   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7990   // hex value.
7991   std::string CodePointStr;
7992   if (!llvm::sys::locale::isPrint(*csStart)) {
7993     llvm::UTF32 CodePoint;
7994     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7995     const llvm::UTF8 *E =
7996         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7997     llvm::ConversionResult Result =
7998         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7999 
8000     if (Result != llvm::conversionOK) {
8001       unsigned char FirstChar = *csStart;
8002       CodePoint = (llvm::UTF32)FirstChar;
8003     }
8004 
8005     llvm::raw_string_ostream OS(CodePointStr);
8006     if (CodePoint < 256)
8007       OS << "\\x" << llvm::format("%02x", CodePoint);
8008     else if (CodePoint <= 0xFFFF)
8009       OS << "\\u" << llvm::format("%04x", CodePoint);
8010     else
8011       OS << "\\U" << llvm::format("%08x", CodePoint);
8012     OS.flush();
8013     Specifier = CodePointStr;
8014   }
8015 
8016   EmitFormatDiagnostic(
8017       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8018       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8019 
8020   return keepGoing;
8021 }
8022 
8023 void
8024 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8025                                                       const char *startSpec,
8026                                                       unsigned specifierLen) {
8027   EmitFormatDiagnostic(
8028     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8029     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8030 }
8031 
8032 bool
8033 CheckFormatHandler::CheckNumArgs(
8034   const analyze_format_string::FormatSpecifier &FS,
8035   const analyze_format_string::ConversionSpecifier &CS,
8036   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8037 
8038   if (argIndex >= NumDataArgs) {
8039     PartialDiagnostic PDiag = FS.usesPositionalArg()
8040       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8041            << (argIndex+1) << NumDataArgs)
8042       : S.PDiag(diag::warn_printf_insufficient_data_args);
8043     EmitFormatDiagnostic(
8044       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8045       getSpecifierRange(startSpecifier, specifierLen));
8046 
8047     // Since more arguments than conversion tokens are given, by extension
8048     // all arguments are covered, so mark this as so.
8049     UncoveredArg.setAllCovered();
8050     return false;
8051   }
8052   return true;
8053 }
8054 
8055 template<typename Range>
8056 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8057                                               SourceLocation Loc,
8058                                               bool IsStringLocation,
8059                                               Range StringRange,
8060                                               ArrayRef<FixItHint> FixIt) {
8061   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8062                        Loc, IsStringLocation, StringRange, FixIt);
8063 }
8064 
8065 /// If the format string is not within the function call, emit a note
8066 /// so that the function call and string are in diagnostic messages.
8067 ///
8068 /// \param InFunctionCall if true, the format string is within the function
8069 /// call and only one diagnostic message will be produced.  Otherwise, an
8070 /// extra note will be emitted pointing to location of the format string.
8071 ///
8072 /// \param ArgumentExpr the expression that is passed as the format string
8073 /// argument in the function call.  Used for getting locations when two
8074 /// diagnostics are emitted.
8075 ///
8076 /// \param PDiag the callee should already have provided any strings for the
8077 /// diagnostic message.  This function only adds locations and fixits
8078 /// to diagnostics.
8079 ///
8080 /// \param Loc primary location for diagnostic.  If two diagnostics are
8081 /// required, one will be at Loc and a new SourceLocation will be created for
8082 /// the other one.
8083 ///
8084 /// \param IsStringLocation if true, Loc points to the format string should be
8085 /// used for the note.  Otherwise, Loc points to the argument list and will
8086 /// be used with PDiag.
8087 ///
8088 /// \param StringRange some or all of the string to highlight.  This is
8089 /// templated so it can accept either a CharSourceRange or a SourceRange.
8090 ///
8091 /// \param FixIt optional fix it hint for the format string.
8092 template <typename Range>
8093 void CheckFormatHandler::EmitFormatDiagnostic(
8094     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8095     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8096     Range StringRange, ArrayRef<FixItHint> FixIt) {
8097   if (InFunctionCall) {
8098     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8099     D << StringRange;
8100     D << FixIt;
8101   } else {
8102     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8103       << ArgumentExpr->getSourceRange();
8104 
8105     const Sema::SemaDiagnosticBuilder &Note =
8106       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8107              diag::note_format_string_defined);
8108 
8109     Note << StringRange;
8110     Note << FixIt;
8111   }
8112 }
8113 
8114 //===--- CHECK: Printf format string checking ------------------------------===//
8115 
8116 namespace {
8117 
8118 class CheckPrintfHandler : public CheckFormatHandler {
8119 public:
8120   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8121                      const Expr *origFormatExpr,
8122                      const Sema::FormatStringType type, unsigned firstDataArg,
8123                      unsigned numDataArgs, bool isObjC, const char *beg,
8124                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8125                      unsigned formatIdx, bool inFunctionCall,
8126                      Sema::VariadicCallType CallType,
8127                      llvm::SmallBitVector &CheckedVarArgs,
8128                      UncoveredArgHandler &UncoveredArg)
8129       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8130                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8131                            inFunctionCall, CallType, CheckedVarArgs,
8132                            UncoveredArg) {}
8133 
8134   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8135 
8136   /// Returns true if '%@' specifiers are allowed in the format string.
8137   bool allowsObjCArg() const {
8138     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8139            FSType == Sema::FST_OSTrace;
8140   }
8141 
8142   bool HandleInvalidPrintfConversionSpecifier(
8143                                       const analyze_printf::PrintfSpecifier &FS,
8144                                       const char *startSpecifier,
8145                                       unsigned specifierLen) override;
8146 
8147   void handleInvalidMaskType(StringRef MaskType) override;
8148 
8149   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8150                              const char *startSpecifier,
8151                              unsigned specifierLen) override;
8152   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8153                        const char *StartSpecifier,
8154                        unsigned SpecifierLen,
8155                        const Expr *E);
8156 
8157   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8158                     const char *startSpecifier, unsigned specifierLen);
8159   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8160                            const analyze_printf::OptionalAmount &Amt,
8161                            unsigned type,
8162                            const char *startSpecifier, unsigned specifierLen);
8163   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8164                   const analyze_printf::OptionalFlag &flag,
8165                   const char *startSpecifier, unsigned specifierLen);
8166   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8167                          const analyze_printf::OptionalFlag &ignoredFlag,
8168                          const analyze_printf::OptionalFlag &flag,
8169                          const char *startSpecifier, unsigned specifierLen);
8170   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8171                            const Expr *E);
8172 
8173   void HandleEmptyObjCModifierFlag(const char *startFlag,
8174                                    unsigned flagLen) override;
8175 
8176   void HandleInvalidObjCModifierFlag(const char *startFlag,
8177                                             unsigned flagLen) override;
8178 
8179   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8180                                            const char *flagsEnd,
8181                                            const char *conversionPosition)
8182                                              override;
8183 };
8184 
8185 } // namespace
8186 
8187 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8188                                       const analyze_printf::PrintfSpecifier &FS,
8189                                       const char *startSpecifier,
8190                                       unsigned specifierLen) {
8191   const analyze_printf::PrintfConversionSpecifier &CS =
8192     FS.getConversionSpecifier();
8193 
8194   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8195                                           getLocationOfByte(CS.getStart()),
8196                                           startSpecifier, specifierLen,
8197                                           CS.getStart(), CS.getLength());
8198 }
8199 
8200 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8201   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8202 }
8203 
8204 bool CheckPrintfHandler::HandleAmount(
8205                                const analyze_format_string::OptionalAmount &Amt,
8206                                unsigned k, const char *startSpecifier,
8207                                unsigned specifierLen) {
8208   if (Amt.hasDataArgument()) {
8209     if (!HasVAListArg) {
8210       unsigned argIndex = Amt.getArgIndex();
8211       if (argIndex >= NumDataArgs) {
8212         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8213                                << k,
8214                              getLocationOfByte(Amt.getStart()),
8215                              /*IsStringLocation*/true,
8216                              getSpecifierRange(startSpecifier, specifierLen));
8217         // Don't do any more checking.  We will just emit
8218         // spurious errors.
8219         return false;
8220       }
8221 
8222       // Type check the data argument.  It should be an 'int'.
8223       // Although not in conformance with C99, we also allow the argument to be
8224       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8225       // doesn't emit a warning for that case.
8226       CoveredArgs.set(argIndex);
8227       const Expr *Arg = getDataArg(argIndex);
8228       if (!Arg)
8229         return false;
8230 
8231       QualType T = Arg->getType();
8232 
8233       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8234       assert(AT.isValid());
8235 
8236       if (!AT.matchesType(S.Context, T)) {
8237         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8238                                << k << AT.getRepresentativeTypeName(S.Context)
8239                                << T << Arg->getSourceRange(),
8240                              getLocationOfByte(Amt.getStart()),
8241                              /*IsStringLocation*/true,
8242                              getSpecifierRange(startSpecifier, specifierLen));
8243         // Don't do any more checking.  We will just emit
8244         // spurious errors.
8245         return false;
8246       }
8247     }
8248   }
8249   return true;
8250 }
8251 
8252 void CheckPrintfHandler::HandleInvalidAmount(
8253                                       const analyze_printf::PrintfSpecifier &FS,
8254                                       const analyze_printf::OptionalAmount &Amt,
8255                                       unsigned type,
8256                                       const char *startSpecifier,
8257                                       unsigned specifierLen) {
8258   const analyze_printf::PrintfConversionSpecifier &CS =
8259     FS.getConversionSpecifier();
8260 
8261   FixItHint fixit =
8262     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8263       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8264                                  Amt.getConstantLength()))
8265       : FixItHint();
8266 
8267   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8268                          << type << CS.toString(),
8269                        getLocationOfByte(Amt.getStart()),
8270                        /*IsStringLocation*/true,
8271                        getSpecifierRange(startSpecifier, specifierLen),
8272                        fixit);
8273 }
8274 
8275 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8276                                     const analyze_printf::OptionalFlag &flag,
8277                                     const char *startSpecifier,
8278                                     unsigned specifierLen) {
8279   // Warn about pointless flag with a fixit removal.
8280   const analyze_printf::PrintfConversionSpecifier &CS =
8281     FS.getConversionSpecifier();
8282   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8283                          << flag.toString() << CS.toString(),
8284                        getLocationOfByte(flag.getPosition()),
8285                        /*IsStringLocation*/true,
8286                        getSpecifierRange(startSpecifier, specifierLen),
8287                        FixItHint::CreateRemoval(
8288                          getSpecifierRange(flag.getPosition(), 1)));
8289 }
8290 
8291 void CheckPrintfHandler::HandleIgnoredFlag(
8292                                 const analyze_printf::PrintfSpecifier &FS,
8293                                 const analyze_printf::OptionalFlag &ignoredFlag,
8294                                 const analyze_printf::OptionalFlag &flag,
8295                                 const char *startSpecifier,
8296                                 unsigned specifierLen) {
8297   // Warn about ignored flag with a fixit removal.
8298   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8299                          << ignoredFlag.toString() << flag.toString(),
8300                        getLocationOfByte(ignoredFlag.getPosition()),
8301                        /*IsStringLocation*/true,
8302                        getSpecifierRange(startSpecifier, specifierLen),
8303                        FixItHint::CreateRemoval(
8304                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8305 }
8306 
8307 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8308                                                      unsigned flagLen) {
8309   // Warn about an empty flag.
8310   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8311                        getLocationOfByte(startFlag),
8312                        /*IsStringLocation*/true,
8313                        getSpecifierRange(startFlag, flagLen));
8314 }
8315 
8316 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8317                                                        unsigned flagLen) {
8318   // Warn about an invalid flag.
8319   auto Range = getSpecifierRange(startFlag, flagLen);
8320   StringRef flag(startFlag, flagLen);
8321   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8322                       getLocationOfByte(startFlag),
8323                       /*IsStringLocation*/true,
8324                       Range, FixItHint::CreateRemoval(Range));
8325 }
8326 
8327 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8328     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8329     // Warn about using '[...]' without a '@' conversion.
8330     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8331     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8332     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8333                          getLocationOfByte(conversionPosition),
8334                          /*IsStringLocation*/true,
8335                          Range, FixItHint::CreateRemoval(Range));
8336 }
8337 
8338 // Determines if the specified is a C++ class or struct containing
8339 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8340 // "c_str()").
8341 template<typename MemberKind>
8342 static llvm::SmallPtrSet<MemberKind*, 1>
8343 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8344   const RecordType *RT = Ty->getAs<RecordType>();
8345   llvm::SmallPtrSet<MemberKind*, 1> Results;
8346 
8347   if (!RT)
8348     return Results;
8349   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8350   if (!RD || !RD->getDefinition())
8351     return Results;
8352 
8353   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8354                  Sema::LookupMemberName);
8355   R.suppressDiagnostics();
8356 
8357   // We just need to include all members of the right kind turned up by the
8358   // filter, at this point.
8359   if (S.LookupQualifiedName(R, RT->getDecl()))
8360     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8361       NamedDecl *decl = (*I)->getUnderlyingDecl();
8362       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8363         Results.insert(FK);
8364     }
8365   return Results;
8366 }
8367 
8368 /// Check if we could call '.c_str()' on an object.
8369 ///
8370 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8371 /// allow the call, or if it would be ambiguous).
8372 bool Sema::hasCStrMethod(const Expr *E) {
8373   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8374 
8375   MethodSet Results =
8376       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8377   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8378        MI != ME; ++MI)
8379     if ((*MI)->getMinRequiredArguments() == 0)
8380       return true;
8381   return false;
8382 }
8383 
8384 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8385 // better diagnostic if so. AT is assumed to be valid.
8386 // Returns true when a c_str() conversion method is found.
8387 bool CheckPrintfHandler::checkForCStrMembers(
8388     const analyze_printf::ArgType &AT, const Expr *E) {
8389   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8390 
8391   MethodSet Results =
8392       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8393 
8394   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8395        MI != ME; ++MI) {
8396     const CXXMethodDecl *Method = *MI;
8397     if (Method->getMinRequiredArguments() == 0 &&
8398         AT.matchesType(S.Context, Method->getReturnType())) {
8399       // FIXME: Suggest parens if the expression needs them.
8400       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8401       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8402           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8403       return true;
8404     }
8405   }
8406 
8407   return false;
8408 }
8409 
8410 bool
8411 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8412                                             &FS,
8413                                           const char *startSpecifier,
8414                                           unsigned specifierLen) {
8415   using namespace analyze_format_string;
8416   using namespace analyze_printf;
8417 
8418   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8419 
8420   if (FS.consumesDataArgument()) {
8421     if (atFirstArg) {
8422         atFirstArg = false;
8423         usesPositionalArgs = FS.usesPositionalArg();
8424     }
8425     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8426       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8427                                         startSpecifier, specifierLen);
8428       return false;
8429     }
8430   }
8431 
8432   // First check if the field width, precision, and conversion specifier
8433   // have matching data arguments.
8434   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8435                     startSpecifier, specifierLen)) {
8436     return false;
8437   }
8438 
8439   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8440                     startSpecifier, specifierLen)) {
8441     return false;
8442   }
8443 
8444   if (!CS.consumesDataArgument()) {
8445     // FIXME: Technically specifying a precision or field width here
8446     // makes no sense.  Worth issuing a warning at some point.
8447     return true;
8448   }
8449 
8450   // Consume the argument.
8451   unsigned argIndex = FS.getArgIndex();
8452   if (argIndex < NumDataArgs) {
8453     // The check to see if the argIndex is valid will come later.
8454     // We set the bit here because we may exit early from this
8455     // function if we encounter some other error.
8456     CoveredArgs.set(argIndex);
8457   }
8458 
8459   // FreeBSD kernel extensions.
8460   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8461       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8462     // We need at least two arguments.
8463     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8464       return false;
8465 
8466     // Claim the second argument.
8467     CoveredArgs.set(argIndex + 1);
8468 
8469     // Type check the first argument (int for %b, pointer for %D)
8470     const Expr *Ex = getDataArg(argIndex);
8471     const analyze_printf::ArgType &AT =
8472       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8473         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8474     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8475       EmitFormatDiagnostic(
8476           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8477               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8478               << false << Ex->getSourceRange(),
8479           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8480           getSpecifierRange(startSpecifier, specifierLen));
8481 
8482     // Type check the second argument (char * for both %b and %D)
8483     Ex = getDataArg(argIndex + 1);
8484     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8485     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8486       EmitFormatDiagnostic(
8487           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8488               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8489               << false << Ex->getSourceRange(),
8490           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8491           getSpecifierRange(startSpecifier, specifierLen));
8492 
8493      return true;
8494   }
8495 
8496   // Check for using an Objective-C specific conversion specifier
8497   // in a non-ObjC literal.
8498   if (!allowsObjCArg() && CS.isObjCArg()) {
8499     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8500                                                   specifierLen);
8501   }
8502 
8503   // %P can only be used with os_log.
8504   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8505     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8506                                                   specifierLen);
8507   }
8508 
8509   // %n is not allowed with os_log.
8510   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8511     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8512                          getLocationOfByte(CS.getStart()),
8513                          /*IsStringLocation*/ false,
8514                          getSpecifierRange(startSpecifier, specifierLen));
8515 
8516     return true;
8517   }
8518 
8519   // Only scalars are allowed for os_trace.
8520   if (FSType == Sema::FST_OSTrace &&
8521       (CS.getKind() == ConversionSpecifier::PArg ||
8522        CS.getKind() == ConversionSpecifier::sArg ||
8523        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8524     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8525                                                   specifierLen);
8526   }
8527 
8528   // Check for use of public/private annotation outside of os_log().
8529   if (FSType != Sema::FST_OSLog) {
8530     if (FS.isPublic().isSet()) {
8531       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8532                                << "public",
8533                            getLocationOfByte(FS.isPublic().getPosition()),
8534                            /*IsStringLocation*/ false,
8535                            getSpecifierRange(startSpecifier, specifierLen));
8536     }
8537     if (FS.isPrivate().isSet()) {
8538       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8539                                << "private",
8540                            getLocationOfByte(FS.isPrivate().getPosition()),
8541                            /*IsStringLocation*/ false,
8542                            getSpecifierRange(startSpecifier, specifierLen));
8543     }
8544   }
8545 
8546   // Check for invalid use of field width
8547   if (!FS.hasValidFieldWidth()) {
8548     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8549         startSpecifier, specifierLen);
8550   }
8551 
8552   // Check for invalid use of precision
8553   if (!FS.hasValidPrecision()) {
8554     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8555         startSpecifier, specifierLen);
8556   }
8557 
8558   // Precision is mandatory for %P specifier.
8559   if (CS.getKind() == ConversionSpecifier::PArg &&
8560       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8561     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8562                          getLocationOfByte(startSpecifier),
8563                          /*IsStringLocation*/ false,
8564                          getSpecifierRange(startSpecifier, specifierLen));
8565   }
8566 
8567   // Check each flag does not conflict with any other component.
8568   if (!FS.hasValidThousandsGroupingPrefix())
8569     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8570   if (!FS.hasValidLeadingZeros())
8571     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8572   if (!FS.hasValidPlusPrefix())
8573     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8574   if (!FS.hasValidSpacePrefix())
8575     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8576   if (!FS.hasValidAlternativeForm())
8577     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8578   if (!FS.hasValidLeftJustified())
8579     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8580 
8581   // Check that flags are not ignored by another flag
8582   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8583     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8584         startSpecifier, specifierLen);
8585   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8586     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8587             startSpecifier, specifierLen);
8588 
8589   // Check the length modifier is valid with the given conversion specifier.
8590   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8591                                  S.getLangOpts()))
8592     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8593                                 diag::warn_format_nonsensical_length);
8594   else if (!FS.hasStandardLengthModifier())
8595     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8596   else if (!FS.hasStandardLengthConversionCombination())
8597     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8598                                 diag::warn_format_non_standard_conversion_spec);
8599 
8600   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8601     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8602 
8603   // The remaining checks depend on the data arguments.
8604   if (HasVAListArg)
8605     return true;
8606 
8607   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8608     return false;
8609 
8610   const Expr *Arg = getDataArg(argIndex);
8611   if (!Arg)
8612     return true;
8613 
8614   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8615 }
8616 
8617 static bool requiresParensToAddCast(const Expr *E) {
8618   // FIXME: We should have a general way to reason about operator
8619   // precedence and whether parens are actually needed here.
8620   // Take care of a few common cases where they aren't.
8621   const Expr *Inside = E->IgnoreImpCasts();
8622   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8623     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8624 
8625   switch (Inside->getStmtClass()) {
8626   case Stmt::ArraySubscriptExprClass:
8627   case Stmt::CallExprClass:
8628   case Stmt::CharacterLiteralClass:
8629   case Stmt::CXXBoolLiteralExprClass:
8630   case Stmt::DeclRefExprClass:
8631   case Stmt::FloatingLiteralClass:
8632   case Stmt::IntegerLiteralClass:
8633   case Stmt::MemberExprClass:
8634   case Stmt::ObjCArrayLiteralClass:
8635   case Stmt::ObjCBoolLiteralExprClass:
8636   case Stmt::ObjCBoxedExprClass:
8637   case Stmt::ObjCDictionaryLiteralClass:
8638   case Stmt::ObjCEncodeExprClass:
8639   case Stmt::ObjCIvarRefExprClass:
8640   case Stmt::ObjCMessageExprClass:
8641   case Stmt::ObjCPropertyRefExprClass:
8642   case Stmt::ObjCStringLiteralClass:
8643   case Stmt::ObjCSubscriptRefExprClass:
8644   case Stmt::ParenExprClass:
8645   case Stmt::StringLiteralClass:
8646   case Stmt::UnaryOperatorClass:
8647     return false;
8648   default:
8649     return true;
8650   }
8651 }
8652 
8653 static std::pair<QualType, StringRef>
8654 shouldNotPrintDirectly(const ASTContext &Context,
8655                        QualType IntendedTy,
8656                        const Expr *E) {
8657   // Use a 'while' to peel off layers of typedefs.
8658   QualType TyTy = IntendedTy;
8659   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8660     StringRef Name = UserTy->getDecl()->getName();
8661     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8662       .Case("CFIndex", Context.getNSIntegerType())
8663       .Case("NSInteger", Context.getNSIntegerType())
8664       .Case("NSUInteger", Context.getNSUIntegerType())
8665       .Case("SInt32", Context.IntTy)
8666       .Case("UInt32", Context.UnsignedIntTy)
8667       .Default(QualType());
8668 
8669     if (!CastTy.isNull())
8670       return std::make_pair(CastTy, Name);
8671 
8672     TyTy = UserTy->desugar();
8673   }
8674 
8675   // Strip parens if necessary.
8676   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8677     return shouldNotPrintDirectly(Context,
8678                                   PE->getSubExpr()->getType(),
8679                                   PE->getSubExpr());
8680 
8681   // If this is a conditional expression, then its result type is constructed
8682   // via usual arithmetic conversions and thus there might be no necessary
8683   // typedef sugar there.  Recurse to operands to check for NSInteger &
8684   // Co. usage condition.
8685   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8686     QualType TrueTy, FalseTy;
8687     StringRef TrueName, FalseName;
8688 
8689     std::tie(TrueTy, TrueName) =
8690       shouldNotPrintDirectly(Context,
8691                              CO->getTrueExpr()->getType(),
8692                              CO->getTrueExpr());
8693     std::tie(FalseTy, FalseName) =
8694       shouldNotPrintDirectly(Context,
8695                              CO->getFalseExpr()->getType(),
8696                              CO->getFalseExpr());
8697 
8698     if (TrueTy == FalseTy)
8699       return std::make_pair(TrueTy, TrueName);
8700     else if (TrueTy.isNull())
8701       return std::make_pair(FalseTy, FalseName);
8702     else if (FalseTy.isNull())
8703       return std::make_pair(TrueTy, TrueName);
8704   }
8705 
8706   return std::make_pair(QualType(), StringRef());
8707 }
8708 
8709 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8710 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8711 /// type do not count.
8712 static bool
8713 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8714   QualType From = ICE->getSubExpr()->getType();
8715   QualType To = ICE->getType();
8716   // It's an integer promotion if the destination type is the promoted
8717   // source type.
8718   if (ICE->getCastKind() == CK_IntegralCast &&
8719       From->isPromotableIntegerType() &&
8720       S.Context.getPromotedIntegerType(From) == To)
8721     return true;
8722   // Look through vector types, since we do default argument promotion for
8723   // those in OpenCL.
8724   if (const auto *VecTy = From->getAs<ExtVectorType>())
8725     From = VecTy->getElementType();
8726   if (const auto *VecTy = To->getAs<ExtVectorType>())
8727     To = VecTy->getElementType();
8728   // It's a floating promotion if the source type is a lower rank.
8729   return ICE->getCastKind() == CK_FloatingCast &&
8730          S.Context.getFloatingTypeOrder(From, To) < 0;
8731 }
8732 
8733 bool
8734 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8735                                     const char *StartSpecifier,
8736                                     unsigned SpecifierLen,
8737                                     const Expr *E) {
8738   using namespace analyze_format_string;
8739   using namespace analyze_printf;
8740 
8741   // Now type check the data expression that matches the
8742   // format specifier.
8743   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8744   if (!AT.isValid())
8745     return true;
8746 
8747   QualType ExprTy = E->getType();
8748   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8749     ExprTy = TET->getUnderlyingExpr()->getType();
8750   }
8751 
8752   // Diagnose attempts to print a boolean value as a character. Unlike other
8753   // -Wformat diagnostics, this is fine from a type perspective, but it still
8754   // doesn't make sense.
8755   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8756       E->isKnownToHaveBooleanValue()) {
8757     const CharSourceRange &CSR =
8758         getSpecifierRange(StartSpecifier, SpecifierLen);
8759     SmallString<4> FSString;
8760     llvm::raw_svector_ostream os(FSString);
8761     FS.toString(os);
8762     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8763                              << FSString,
8764                          E->getExprLoc(), false, CSR);
8765     return true;
8766   }
8767 
8768   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8769   if (Match == analyze_printf::ArgType::Match)
8770     return true;
8771 
8772   // Look through argument promotions for our error message's reported type.
8773   // This includes the integral and floating promotions, but excludes array
8774   // and function pointer decay (seeing that an argument intended to be a
8775   // string has type 'char [6]' is probably more confusing than 'char *') and
8776   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8777   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8778     if (isArithmeticArgumentPromotion(S, ICE)) {
8779       E = ICE->getSubExpr();
8780       ExprTy = E->getType();
8781 
8782       // Check if we didn't match because of an implicit cast from a 'char'
8783       // or 'short' to an 'int'.  This is done because printf is a varargs
8784       // function.
8785       if (ICE->getType() == S.Context.IntTy ||
8786           ICE->getType() == S.Context.UnsignedIntTy) {
8787         // All further checking is done on the subexpression
8788         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8789             AT.matchesType(S.Context, ExprTy);
8790         if (ImplicitMatch == analyze_printf::ArgType::Match)
8791           return true;
8792         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8793             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8794           Match = ImplicitMatch;
8795       }
8796     }
8797   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8798     // Special case for 'a', which has type 'int' in C.
8799     // Note, however, that we do /not/ want to treat multibyte constants like
8800     // 'MooV' as characters! This form is deprecated but still exists. In
8801     // addition, don't treat expressions as of type 'char' if one byte length
8802     // modifier is provided.
8803     if (ExprTy == S.Context.IntTy &&
8804         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
8805       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8806         ExprTy = S.Context.CharTy;
8807   }
8808 
8809   // Look through enums to their underlying type.
8810   bool IsEnum = false;
8811   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8812     ExprTy = EnumTy->getDecl()->getIntegerType();
8813     IsEnum = true;
8814   }
8815 
8816   // %C in an Objective-C context prints a unichar, not a wchar_t.
8817   // If the argument is an integer of some kind, believe the %C and suggest
8818   // a cast instead of changing the conversion specifier.
8819   QualType IntendedTy = ExprTy;
8820   if (isObjCContext() &&
8821       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8822     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8823         !ExprTy->isCharType()) {
8824       // 'unichar' is defined as a typedef of unsigned short, but we should
8825       // prefer using the typedef if it is visible.
8826       IntendedTy = S.Context.UnsignedShortTy;
8827 
8828       // While we are here, check if the value is an IntegerLiteral that happens
8829       // to be within the valid range.
8830       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8831         const llvm::APInt &V = IL->getValue();
8832         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8833           return true;
8834       }
8835 
8836       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8837                           Sema::LookupOrdinaryName);
8838       if (S.LookupName(Result, S.getCurScope())) {
8839         NamedDecl *ND = Result.getFoundDecl();
8840         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8841           if (TD->getUnderlyingType() == IntendedTy)
8842             IntendedTy = S.Context.getTypedefType(TD);
8843       }
8844     }
8845   }
8846 
8847   // Special-case some of Darwin's platform-independence types by suggesting
8848   // casts to primitive types that are known to be large enough.
8849   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8850   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8851     QualType CastTy;
8852     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8853     if (!CastTy.isNull()) {
8854       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8855       // (long in ASTContext). Only complain to pedants.
8856       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8857           (AT.isSizeT() || AT.isPtrdiffT()) &&
8858           AT.matchesType(S.Context, CastTy))
8859         Match = ArgType::NoMatchPedantic;
8860       IntendedTy = CastTy;
8861       ShouldNotPrintDirectly = true;
8862     }
8863   }
8864 
8865   // We may be able to offer a FixItHint if it is a supported type.
8866   PrintfSpecifier fixedFS = FS;
8867   bool Success =
8868       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8869 
8870   if (Success) {
8871     // Get the fix string from the fixed format specifier
8872     SmallString<16> buf;
8873     llvm::raw_svector_ostream os(buf);
8874     fixedFS.toString(os);
8875 
8876     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8877 
8878     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8879       unsigned Diag;
8880       switch (Match) {
8881       case ArgType::Match: llvm_unreachable("expected non-matching");
8882       case ArgType::NoMatchPedantic:
8883         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8884         break;
8885       case ArgType::NoMatchTypeConfusion:
8886         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8887         break;
8888       case ArgType::NoMatch:
8889         Diag = diag::warn_format_conversion_argument_type_mismatch;
8890         break;
8891       }
8892 
8893       // In this case, the specifier is wrong and should be changed to match
8894       // the argument.
8895       EmitFormatDiagnostic(S.PDiag(Diag)
8896                                << AT.getRepresentativeTypeName(S.Context)
8897                                << IntendedTy << IsEnum << E->getSourceRange(),
8898                            E->getBeginLoc(),
8899                            /*IsStringLocation*/ false, SpecRange,
8900                            FixItHint::CreateReplacement(SpecRange, os.str()));
8901     } else {
8902       // The canonical type for formatting this value is different from the
8903       // actual type of the expression. (This occurs, for example, with Darwin's
8904       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8905       // should be printed as 'long' for 64-bit compatibility.)
8906       // Rather than emitting a normal format/argument mismatch, we want to
8907       // add a cast to the recommended type (and correct the format string
8908       // if necessary).
8909       SmallString<16> CastBuf;
8910       llvm::raw_svector_ostream CastFix(CastBuf);
8911       CastFix << "(";
8912       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8913       CastFix << ")";
8914 
8915       SmallVector<FixItHint,4> Hints;
8916       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8917         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8918 
8919       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8920         // If there's already a cast present, just replace it.
8921         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8922         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8923 
8924       } else if (!requiresParensToAddCast(E)) {
8925         // If the expression has high enough precedence,
8926         // just write the C-style cast.
8927         Hints.push_back(
8928             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8929       } else {
8930         // Otherwise, add parens around the expression as well as the cast.
8931         CastFix << "(";
8932         Hints.push_back(
8933             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8934 
8935         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8936         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8937       }
8938 
8939       if (ShouldNotPrintDirectly) {
8940         // The expression has a type that should not be printed directly.
8941         // We extract the name from the typedef because we don't want to show
8942         // the underlying type in the diagnostic.
8943         StringRef Name;
8944         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8945           Name = TypedefTy->getDecl()->getName();
8946         else
8947           Name = CastTyName;
8948         unsigned Diag = Match == ArgType::NoMatchPedantic
8949                             ? diag::warn_format_argument_needs_cast_pedantic
8950                             : diag::warn_format_argument_needs_cast;
8951         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8952                                            << E->getSourceRange(),
8953                              E->getBeginLoc(), /*IsStringLocation=*/false,
8954                              SpecRange, Hints);
8955       } else {
8956         // In this case, the expression could be printed using a different
8957         // specifier, but we've decided that the specifier is probably correct
8958         // and we should cast instead. Just use the normal warning message.
8959         EmitFormatDiagnostic(
8960             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8961                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8962                 << E->getSourceRange(),
8963             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8964       }
8965     }
8966   } else {
8967     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8968                                                    SpecifierLen);
8969     // Since the warning for passing non-POD types to variadic functions
8970     // was deferred until now, we emit a warning for non-POD
8971     // arguments here.
8972     switch (S.isValidVarArgType(ExprTy)) {
8973     case Sema::VAK_Valid:
8974     case Sema::VAK_ValidInCXX11: {
8975       unsigned Diag;
8976       switch (Match) {
8977       case ArgType::Match: llvm_unreachable("expected non-matching");
8978       case ArgType::NoMatchPedantic:
8979         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8980         break;
8981       case ArgType::NoMatchTypeConfusion:
8982         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8983         break;
8984       case ArgType::NoMatch:
8985         Diag = diag::warn_format_conversion_argument_type_mismatch;
8986         break;
8987       }
8988 
8989       EmitFormatDiagnostic(
8990           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8991                         << IsEnum << CSR << E->getSourceRange(),
8992           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8993       break;
8994     }
8995     case Sema::VAK_Undefined:
8996     case Sema::VAK_MSVCUndefined:
8997       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8998                                << S.getLangOpts().CPlusPlus11 << ExprTy
8999                                << CallType
9000                                << AT.getRepresentativeTypeName(S.Context) << CSR
9001                                << E->getSourceRange(),
9002                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9003       checkForCStrMembers(AT, E);
9004       break;
9005 
9006     case Sema::VAK_Invalid:
9007       if (ExprTy->isObjCObjectType())
9008         EmitFormatDiagnostic(
9009             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9010                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9011                 << AT.getRepresentativeTypeName(S.Context) << CSR
9012                 << E->getSourceRange(),
9013             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9014       else
9015         // FIXME: If this is an initializer list, suggest removing the braces
9016         // or inserting a cast to the target type.
9017         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9018             << isa<InitListExpr>(E) << ExprTy << CallType
9019             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9020       break;
9021     }
9022 
9023     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9024            "format string specifier index out of range");
9025     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9026   }
9027 
9028   return true;
9029 }
9030 
9031 //===--- CHECK: Scanf format string checking ------------------------------===//
9032 
9033 namespace {
9034 
9035 class CheckScanfHandler : public CheckFormatHandler {
9036 public:
9037   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9038                     const Expr *origFormatExpr, Sema::FormatStringType type,
9039                     unsigned firstDataArg, unsigned numDataArgs,
9040                     const char *beg, bool hasVAListArg,
9041                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9042                     bool inFunctionCall, Sema::VariadicCallType CallType,
9043                     llvm::SmallBitVector &CheckedVarArgs,
9044                     UncoveredArgHandler &UncoveredArg)
9045       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9046                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9047                            inFunctionCall, CallType, CheckedVarArgs,
9048                            UncoveredArg) {}
9049 
9050   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9051                             const char *startSpecifier,
9052                             unsigned specifierLen) override;
9053 
9054   bool HandleInvalidScanfConversionSpecifier(
9055           const analyze_scanf::ScanfSpecifier &FS,
9056           const char *startSpecifier,
9057           unsigned specifierLen) override;
9058 
9059   void HandleIncompleteScanList(const char *start, const char *end) override;
9060 };
9061 
9062 } // namespace
9063 
9064 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9065                                                  const char *end) {
9066   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9067                        getLocationOfByte(end), /*IsStringLocation*/true,
9068                        getSpecifierRange(start, end - start));
9069 }
9070 
9071 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9072                                         const analyze_scanf::ScanfSpecifier &FS,
9073                                         const char *startSpecifier,
9074                                         unsigned specifierLen) {
9075   const analyze_scanf::ScanfConversionSpecifier &CS =
9076     FS.getConversionSpecifier();
9077 
9078   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9079                                           getLocationOfByte(CS.getStart()),
9080                                           startSpecifier, specifierLen,
9081                                           CS.getStart(), CS.getLength());
9082 }
9083 
9084 bool CheckScanfHandler::HandleScanfSpecifier(
9085                                        const analyze_scanf::ScanfSpecifier &FS,
9086                                        const char *startSpecifier,
9087                                        unsigned specifierLen) {
9088   using namespace analyze_scanf;
9089   using namespace analyze_format_string;
9090 
9091   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9092 
9093   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9094   // be used to decide if we are using positional arguments consistently.
9095   if (FS.consumesDataArgument()) {
9096     if (atFirstArg) {
9097       atFirstArg = false;
9098       usesPositionalArgs = FS.usesPositionalArg();
9099     }
9100     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9101       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9102                                         startSpecifier, specifierLen);
9103       return false;
9104     }
9105   }
9106 
9107   // Check if the field with is non-zero.
9108   const OptionalAmount &Amt = FS.getFieldWidth();
9109   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9110     if (Amt.getConstantAmount() == 0) {
9111       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9112                                                    Amt.getConstantLength());
9113       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9114                            getLocationOfByte(Amt.getStart()),
9115                            /*IsStringLocation*/true, R,
9116                            FixItHint::CreateRemoval(R));
9117     }
9118   }
9119 
9120   if (!FS.consumesDataArgument()) {
9121     // FIXME: Technically specifying a precision or field width here
9122     // makes no sense.  Worth issuing a warning at some point.
9123     return true;
9124   }
9125 
9126   // Consume the argument.
9127   unsigned argIndex = FS.getArgIndex();
9128   if (argIndex < NumDataArgs) {
9129       // The check to see if the argIndex is valid will come later.
9130       // We set the bit here because we may exit early from this
9131       // function if we encounter some other error.
9132     CoveredArgs.set(argIndex);
9133   }
9134 
9135   // Check the length modifier is valid with the given conversion specifier.
9136   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9137                                  S.getLangOpts()))
9138     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9139                                 diag::warn_format_nonsensical_length);
9140   else if (!FS.hasStandardLengthModifier())
9141     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9142   else if (!FS.hasStandardLengthConversionCombination())
9143     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9144                                 diag::warn_format_non_standard_conversion_spec);
9145 
9146   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9147     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9148 
9149   // The remaining checks depend on the data arguments.
9150   if (HasVAListArg)
9151     return true;
9152 
9153   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9154     return false;
9155 
9156   // Check that the argument type matches the format specifier.
9157   const Expr *Ex = getDataArg(argIndex);
9158   if (!Ex)
9159     return true;
9160 
9161   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9162 
9163   if (!AT.isValid()) {
9164     return true;
9165   }
9166 
9167   analyze_format_string::ArgType::MatchKind Match =
9168       AT.matchesType(S.Context, Ex->getType());
9169   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9170   if (Match == analyze_format_string::ArgType::Match)
9171     return true;
9172 
9173   ScanfSpecifier fixedFS = FS;
9174   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9175                                  S.getLangOpts(), S.Context);
9176 
9177   unsigned Diag =
9178       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9179                : diag::warn_format_conversion_argument_type_mismatch;
9180 
9181   if (Success) {
9182     // Get the fix string from the fixed format specifier.
9183     SmallString<128> buf;
9184     llvm::raw_svector_ostream os(buf);
9185     fixedFS.toString(os);
9186 
9187     EmitFormatDiagnostic(
9188         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9189                       << Ex->getType() << false << Ex->getSourceRange(),
9190         Ex->getBeginLoc(),
9191         /*IsStringLocation*/ false,
9192         getSpecifierRange(startSpecifier, specifierLen),
9193         FixItHint::CreateReplacement(
9194             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9195   } else {
9196     EmitFormatDiagnostic(S.PDiag(Diag)
9197                              << AT.getRepresentativeTypeName(S.Context)
9198                              << Ex->getType() << false << Ex->getSourceRange(),
9199                          Ex->getBeginLoc(),
9200                          /*IsStringLocation*/ false,
9201                          getSpecifierRange(startSpecifier, specifierLen));
9202   }
9203 
9204   return true;
9205 }
9206 
9207 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9208                               const Expr *OrigFormatExpr,
9209                               ArrayRef<const Expr *> Args,
9210                               bool HasVAListArg, unsigned format_idx,
9211                               unsigned firstDataArg,
9212                               Sema::FormatStringType Type,
9213                               bool inFunctionCall,
9214                               Sema::VariadicCallType CallType,
9215                               llvm::SmallBitVector &CheckedVarArgs,
9216                               UncoveredArgHandler &UncoveredArg,
9217                               bool IgnoreStringsWithoutSpecifiers) {
9218   // CHECK: is the format string a wide literal?
9219   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9220     CheckFormatHandler::EmitFormatDiagnostic(
9221         S, inFunctionCall, Args[format_idx],
9222         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9223         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9224     return;
9225   }
9226 
9227   // Str - The format string.  NOTE: this is NOT null-terminated!
9228   StringRef StrRef = FExpr->getString();
9229   const char *Str = StrRef.data();
9230   // Account for cases where the string literal is truncated in a declaration.
9231   const ConstantArrayType *T =
9232     S.Context.getAsConstantArrayType(FExpr->getType());
9233   assert(T && "String literal not of constant array type!");
9234   size_t TypeSize = T->getSize().getZExtValue();
9235   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9236   const unsigned numDataArgs = Args.size() - firstDataArg;
9237 
9238   if (IgnoreStringsWithoutSpecifiers &&
9239       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9240           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9241     return;
9242 
9243   // Emit a warning if the string literal is truncated and does not contain an
9244   // embedded null character.
9245   if (TypeSize <= StrRef.size() &&
9246       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9247     CheckFormatHandler::EmitFormatDiagnostic(
9248         S, inFunctionCall, Args[format_idx],
9249         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9250         FExpr->getBeginLoc(),
9251         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9252     return;
9253   }
9254 
9255   // CHECK: empty format string?
9256   if (StrLen == 0 && numDataArgs > 0) {
9257     CheckFormatHandler::EmitFormatDiagnostic(
9258         S, inFunctionCall, Args[format_idx],
9259         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9260         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9261     return;
9262   }
9263 
9264   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9265       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9266       Type == Sema::FST_OSTrace) {
9267     CheckPrintfHandler H(
9268         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9269         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9270         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9271         CheckedVarArgs, UncoveredArg);
9272 
9273     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9274                                                   S.getLangOpts(),
9275                                                   S.Context.getTargetInfo(),
9276                                             Type == Sema::FST_FreeBSDKPrintf))
9277       H.DoneProcessing();
9278   } else if (Type == Sema::FST_Scanf) {
9279     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9280                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9281                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9282 
9283     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9284                                                  S.getLangOpts(),
9285                                                  S.Context.getTargetInfo()))
9286       H.DoneProcessing();
9287   } // TODO: handle other formats
9288 }
9289 
9290 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9291   // Str - The format string.  NOTE: this is NOT null-terminated!
9292   StringRef StrRef = FExpr->getString();
9293   const char *Str = StrRef.data();
9294   // Account for cases where the string literal is truncated in a declaration.
9295   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9296   assert(T && "String literal not of constant array type!");
9297   size_t TypeSize = T->getSize().getZExtValue();
9298   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9299   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9300                                                          getLangOpts(),
9301                                                          Context.getTargetInfo());
9302 }
9303 
9304 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9305 
9306 // Returns the related absolute value function that is larger, of 0 if one
9307 // does not exist.
9308 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9309   switch (AbsFunction) {
9310   default:
9311     return 0;
9312 
9313   case Builtin::BI__builtin_abs:
9314     return Builtin::BI__builtin_labs;
9315   case Builtin::BI__builtin_labs:
9316     return Builtin::BI__builtin_llabs;
9317   case Builtin::BI__builtin_llabs:
9318     return 0;
9319 
9320   case Builtin::BI__builtin_fabsf:
9321     return Builtin::BI__builtin_fabs;
9322   case Builtin::BI__builtin_fabs:
9323     return Builtin::BI__builtin_fabsl;
9324   case Builtin::BI__builtin_fabsl:
9325     return 0;
9326 
9327   case Builtin::BI__builtin_cabsf:
9328     return Builtin::BI__builtin_cabs;
9329   case Builtin::BI__builtin_cabs:
9330     return Builtin::BI__builtin_cabsl;
9331   case Builtin::BI__builtin_cabsl:
9332     return 0;
9333 
9334   case Builtin::BIabs:
9335     return Builtin::BIlabs;
9336   case Builtin::BIlabs:
9337     return Builtin::BIllabs;
9338   case Builtin::BIllabs:
9339     return 0;
9340 
9341   case Builtin::BIfabsf:
9342     return Builtin::BIfabs;
9343   case Builtin::BIfabs:
9344     return Builtin::BIfabsl;
9345   case Builtin::BIfabsl:
9346     return 0;
9347 
9348   case Builtin::BIcabsf:
9349    return Builtin::BIcabs;
9350   case Builtin::BIcabs:
9351     return Builtin::BIcabsl;
9352   case Builtin::BIcabsl:
9353     return 0;
9354   }
9355 }
9356 
9357 // Returns the argument type of the absolute value function.
9358 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9359                                              unsigned AbsType) {
9360   if (AbsType == 0)
9361     return QualType();
9362 
9363   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9364   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9365   if (Error != ASTContext::GE_None)
9366     return QualType();
9367 
9368   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9369   if (!FT)
9370     return QualType();
9371 
9372   if (FT->getNumParams() != 1)
9373     return QualType();
9374 
9375   return FT->getParamType(0);
9376 }
9377 
9378 // Returns the best absolute value function, or zero, based on type and
9379 // current absolute value function.
9380 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9381                                    unsigned AbsFunctionKind) {
9382   unsigned BestKind = 0;
9383   uint64_t ArgSize = Context.getTypeSize(ArgType);
9384   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9385        Kind = getLargerAbsoluteValueFunction(Kind)) {
9386     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9387     if (Context.getTypeSize(ParamType) >= ArgSize) {
9388       if (BestKind == 0)
9389         BestKind = Kind;
9390       else if (Context.hasSameType(ParamType, ArgType)) {
9391         BestKind = Kind;
9392         break;
9393       }
9394     }
9395   }
9396   return BestKind;
9397 }
9398 
9399 enum AbsoluteValueKind {
9400   AVK_Integer,
9401   AVK_Floating,
9402   AVK_Complex
9403 };
9404 
9405 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9406   if (T->isIntegralOrEnumerationType())
9407     return AVK_Integer;
9408   if (T->isRealFloatingType())
9409     return AVK_Floating;
9410   if (T->isAnyComplexType())
9411     return AVK_Complex;
9412 
9413   llvm_unreachable("Type not integer, floating, or complex");
9414 }
9415 
9416 // Changes the absolute value function to a different type.  Preserves whether
9417 // the function is a builtin.
9418 static unsigned changeAbsFunction(unsigned AbsKind,
9419                                   AbsoluteValueKind ValueKind) {
9420   switch (ValueKind) {
9421   case AVK_Integer:
9422     switch (AbsKind) {
9423     default:
9424       return 0;
9425     case Builtin::BI__builtin_fabsf:
9426     case Builtin::BI__builtin_fabs:
9427     case Builtin::BI__builtin_fabsl:
9428     case Builtin::BI__builtin_cabsf:
9429     case Builtin::BI__builtin_cabs:
9430     case Builtin::BI__builtin_cabsl:
9431       return Builtin::BI__builtin_abs;
9432     case Builtin::BIfabsf:
9433     case Builtin::BIfabs:
9434     case Builtin::BIfabsl:
9435     case Builtin::BIcabsf:
9436     case Builtin::BIcabs:
9437     case Builtin::BIcabsl:
9438       return Builtin::BIabs;
9439     }
9440   case AVK_Floating:
9441     switch (AbsKind) {
9442     default:
9443       return 0;
9444     case Builtin::BI__builtin_abs:
9445     case Builtin::BI__builtin_labs:
9446     case Builtin::BI__builtin_llabs:
9447     case Builtin::BI__builtin_cabsf:
9448     case Builtin::BI__builtin_cabs:
9449     case Builtin::BI__builtin_cabsl:
9450       return Builtin::BI__builtin_fabsf;
9451     case Builtin::BIabs:
9452     case Builtin::BIlabs:
9453     case Builtin::BIllabs:
9454     case Builtin::BIcabsf:
9455     case Builtin::BIcabs:
9456     case Builtin::BIcabsl:
9457       return Builtin::BIfabsf;
9458     }
9459   case AVK_Complex:
9460     switch (AbsKind) {
9461     default:
9462       return 0;
9463     case Builtin::BI__builtin_abs:
9464     case Builtin::BI__builtin_labs:
9465     case Builtin::BI__builtin_llabs:
9466     case Builtin::BI__builtin_fabsf:
9467     case Builtin::BI__builtin_fabs:
9468     case Builtin::BI__builtin_fabsl:
9469       return Builtin::BI__builtin_cabsf;
9470     case Builtin::BIabs:
9471     case Builtin::BIlabs:
9472     case Builtin::BIllabs:
9473     case Builtin::BIfabsf:
9474     case Builtin::BIfabs:
9475     case Builtin::BIfabsl:
9476       return Builtin::BIcabsf;
9477     }
9478   }
9479   llvm_unreachable("Unable to convert function");
9480 }
9481 
9482 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9483   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9484   if (!FnInfo)
9485     return 0;
9486 
9487   switch (FDecl->getBuiltinID()) {
9488   default:
9489     return 0;
9490   case Builtin::BI__builtin_abs:
9491   case Builtin::BI__builtin_fabs:
9492   case Builtin::BI__builtin_fabsf:
9493   case Builtin::BI__builtin_fabsl:
9494   case Builtin::BI__builtin_labs:
9495   case Builtin::BI__builtin_llabs:
9496   case Builtin::BI__builtin_cabs:
9497   case Builtin::BI__builtin_cabsf:
9498   case Builtin::BI__builtin_cabsl:
9499   case Builtin::BIabs:
9500   case Builtin::BIlabs:
9501   case Builtin::BIllabs:
9502   case Builtin::BIfabs:
9503   case Builtin::BIfabsf:
9504   case Builtin::BIfabsl:
9505   case Builtin::BIcabs:
9506   case Builtin::BIcabsf:
9507   case Builtin::BIcabsl:
9508     return FDecl->getBuiltinID();
9509   }
9510   llvm_unreachable("Unknown Builtin type");
9511 }
9512 
9513 // If the replacement is valid, emit a note with replacement function.
9514 // Additionally, suggest including the proper header if not already included.
9515 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9516                             unsigned AbsKind, QualType ArgType) {
9517   bool EmitHeaderHint = true;
9518   const char *HeaderName = nullptr;
9519   const char *FunctionName = nullptr;
9520   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9521     FunctionName = "std::abs";
9522     if (ArgType->isIntegralOrEnumerationType()) {
9523       HeaderName = "cstdlib";
9524     } else if (ArgType->isRealFloatingType()) {
9525       HeaderName = "cmath";
9526     } else {
9527       llvm_unreachable("Invalid Type");
9528     }
9529 
9530     // Lookup all std::abs
9531     if (NamespaceDecl *Std = S.getStdNamespace()) {
9532       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9533       R.suppressDiagnostics();
9534       S.LookupQualifiedName(R, Std);
9535 
9536       for (const auto *I : R) {
9537         const FunctionDecl *FDecl = nullptr;
9538         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9539           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9540         } else {
9541           FDecl = dyn_cast<FunctionDecl>(I);
9542         }
9543         if (!FDecl)
9544           continue;
9545 
9546         // Found std::abs(), check that they are the right ones.
9547         if (FDecl->getNumParams() != 1)
9548           continue;
9549 
9550         // Check that the parameter type can handle the argument.
9551         QualType ParamType = FDecl->getParamDecl(0)->getType();
9552         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9553             S.Context.getTypeSize(ArgType) <=
9554                 S.Context.getTypeSize(ParamType)) {
9555           // Found a function, don't need the header hint.
9556           EmitHeaderHint = false;
9557           break;
9558         }
9559       }
9560     }
9561   } else {
9562     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9563     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9564 
9565     if (HeaderName) {
9566       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9567       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9568       R.suppressDiagnostics();
9569       S.LookupName(R, S.getCurScope());
9570 
9571       if (R.isSingleResult()) {
9572         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9573         if (FD && FD->getBuiltinID() == AbsKind) {
9574           EmitHeaderHint = false;
9575         } else {
9576           return;
9577         }
9578       } else if (!R.empty()) {
9579         return;
9580       }
9581     }
9582   }
9583 
9584   S.Diag(Loc, diag::note_replace_abs_function)
9585       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9586 
9587   if (!HeaderName)
9588     return;
9589 
9590   if (!EmitHeaderHint)
9591     return;
9592 
9593   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9594                                                     << FunctionName;
9595 }
9596 
9597 template <std::size_t StrLen>
9598 static bool IsStdFunction(const FunctionDecl *FDecl,
9599                           const char (&Str)[StrLen]) {
9600   if (!FDecl)
9601     return false;
9602   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9603     return false;
9604   if (!FDecl->isInStdNamespace())
9605     return false;
9606 
9607   return true;
9608 }
9609 
9610 // Warn when using the wrong abs() function.
9611 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9612                                       const FunctionDecl *FDecl) {
9613   if (Call->getNumArgs() != 1)
9614     return;
9615 
9616   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9617   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9618   if (AbsKind == 0 && !IsStdAbs)
9619     return;
9620 
9621   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9622   QualType ParamType = Call->getArg(0)->getType();
9623 
9624   // Unsigned types cannot be negative.  Suggest removing the absolute value
9625   // function call.
9626   if (ArgType->isUnsignedIntegerType()) {
9627     const char *FunctionName =
9628         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9629     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9630     Diag(Call->getExprLoc(), diag::note_remove_abs)
9631         << FunctionName
9632         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9633     return;
9634   }
9635 
9636   // Taking the absolute value of a pointer is very suspicious, they probably
9637   // wanted to index into an array, dereference a pointer, call a function, etc.
9638   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9639     unsigned DiagType = 0;
9640     if (ArgType->isFunctionType())
9641       DiagType = 1;
9642     else if (ArgType->isArrayType())
9643       DiagType = 2;
9644 
9645     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9646     return;
9647   }
9648 
9649   // std::abs has overloads which prevent most of the absolute value problems
9650   // from occurring.
9651   if (IsStdAbs)
9652     return;
9653 
9654   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9655   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9656 
9657   // The argument and parameter are the same kind.  Check if they are the right
9658   // size.
9659   if (ArgValueKind == ParamValueKind) {
9660     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9661       return;
9662 
9663     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9664     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9665         << FDecl << ArgType << ParamType;
9666 
9667     if (NewAbsKind == 0)
9668       return;
9669 
9670     emitReplacement(*this, Call->getExprLoc(),
9671                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9672     return;
9673   }
9674 
9675   // ArgValueKind != ParamValueKind
9676   // The wrong type of absolute value function was used.  Attempt to find the
9677   // proper one.
9678   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9679   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9680   if (NewAbsKind == 0)
9681     return;
9682 
9683   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9684       << FDecl << ParamValueKind << ArgValueKind;
9685 
9686   emitReplacement(*this, Call->getExprLoc(),
9687                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9688 }
9689 
9690 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9691 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9692                                 const FunctionDecl *FDecl) {
9693   if (!Call || !FDecl) return;
9694 
9695   // Ignore template specializations and macros.
9696   if (inTemplateInstantiation()) return;
9697   if (Call->getExprLoc().isMacroID()) return;
9698 
9699   // Only care about the one template argument, two function parameter std::max
9700   if (Call->getNumArgs() != 2) return;
9701   if (!IsStdFunction(FDecl, "max")) return;
9702   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9703   if (!ArgList) return;
9704   if (ArgList->size() != 1) return;
9705 
9706   // Check that template type argument is unsigned integer.
9707   const auto& TA = ArgList->get(0);
9708   if (TA.getKind() != TemplateArgument::Type) return;
9709   QualType ArgType = TA.getAsType();
9710   if (!ArgType->isUnsignedIntegerType()) return;
9711 
9712   // See if either argument is a literal zero.
9713   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9714     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9715     if (!MTE) return false;
9716     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9717     if (!Num) return false;
9718     if (Num->getValue() != 0) return false;
9719     return true;
9720   };
9721 
9722   const Expr *FirstArg = Call->getArg(0);
9723   const Expr *SecondArg = Call->getArg(1);
9724   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9725   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9726 
9727   // Only warn when exactly one argument is zero.
9728   if (IsFirstArgZero == IsSecondArgZero) return;
9729 
9730   SourceRange FirstRange = FirstArg->getSourceRange();
9731   SourceRange SecondRange = SecondArg->getSourceRange();
9732 
9733   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9734 
9735   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9736       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9737 
9738   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9739   SourceRange RemovalRange;
9740   if (IsFirstArgZero) {
9741     RemovalRange = SourceRange(FirstRange.getBegin(),
9742                                SecondRange.getBegin().getLocWithOffset(-1));
9743   } else {
9744     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9745                                SecondRange.getEnd());
9746   }
9747 
9748   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9749         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9750         << FixItHint::CreateRemoval(RemovalRange);
9751 }
9752 
9753 //===--- CHECK: Standard memory functions ---------------------------------===//
9754 
9755 /// Takes the expression passed to the size_t parameter of functions
9756 /// such as memcmp, strncat, etc and warns if it's a comparison.
9757 ///
9758 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9759 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9760                                            IdentifierInfo *FnName,
9761                                            SourceLocation FnLoc,
9762                                            SourceLocation RParenLoc) {
9763   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9764   if (!Size)
9765     return false;
9766 
9767   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9768   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9769     return false;
9770 
9771   SourceRange SizeRange = Size->getSourceRange();
9772   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9773       << SizeRange << FnName;
9774   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9775       << FnName
9776       << FixItHint::CreateInsertion(
9777              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9778       << FixItHint::CreateRemoval(RParenLoc);
9779   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9780       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9781       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9782                                     ")");
9783 
9784   return true;
9785 }
9786 
9787 /// Determine whether the given type is or contains a dynamic class type
9788 /// (e.g., whether it has a vtable).
9789 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9790                                                      bool &IsContained) {
9791   // Look through array types while ignoring qualifiers.
9792   const Type *Ty = T->getBaseElementTypeUnsafe();
9793   IsContained = false;
9794 
9795   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9796   RD = RD ? RD->getDefinition() : nullptr;
9797   if (!RD || RD->isInvalidDecl())
9798     return nullptr;
9799 
9800   if (RD->isDynamicClass())
9801     return RD;
9802 
9803   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9804   // It's impossible for a class to transitively contain itself by value, so
9805   // infinite recursion is impossible.
9806   for (auto *FD : RD->fields()) {
9807     bool SubContained;
9808     if (const CXXRecordDecl *ContainedRD =
9809             getContainedDynamicClass(FD->getType(), SubContained)) {
9810       IsContained = true;
9811       return ContainedRD;
9812     }
9813   }
9814 
9815   return nullptr;
9816 }
9817 
9818 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9819   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9820     if (Unary->getKind() == UETT_SizeOf)
9821       return Unary;
9822   return nullptr;
9823 }
9824 
9825 /// If E is a sizeof expression, returns its argument expression,
9826 /// otherwise returns NULL.
9827 static const Expr *getSizeOfExprArg(const Expr *E) {
9828   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9829     if (!SizeOf->isArgumentType())
9830       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9831   return nullptr;
9832 }
9833 
9834 /// If E is a sizeof expression, returns its argument type.
9835 static QualType getSizeOfArgType(const Expr *E) {
9836   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9837     return SizeOf->getTypeOfArgument();
9838   return QualType();
9839 }
9840 
9841 namespace {
9842 
9843 struct SearchNonTrivialToInitializeField
9844     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9845   using Super =
9846       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9847 
9848   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9849 
9850   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9851                      SourceLocation SL) {
9852     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9853       asDerived().visitArray(PDIK, AT, SL);
9854       return;
9855     }
9856 
9857     Super::visitWithKind(PDIK, FT, SL);
9858   }
9859 
9860   void visitARCStrong(QualType FT, SourceLocation SL) {
9861     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9862   }
9863   void visitARCWeak(QualType FT, SourceLocation SL) {
9864     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9865   }
9866   void visitStruct(QualType FT, SourceLocation SL) {
9867     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9868       visit(FD->getType(), FD->getLocation());
9869   }
9870   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9871                   const ArrayType *AT, SourceLocation SL) {
9872     visit(getContext().getBaseElementType(AT), SL);
9873   }
9874   void visitTrivial(QualType FT, SourceLocation SL) {}
9875 
9876   static void diag(QualType RT, const Expr *E, Sema &S) {
9877     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9878   }
9879 
9880   ASTContext &getContext() { return S.getASTContext(); }
9881 
9882   const Expr *E;
9883   Sema &S;
9884 };
9885 
9886 struct SearchNonTrivialToCopyField
9887     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9888   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9889 
9890   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9891 
9892   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9893                      SourceLocation SL) {
9894     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9895       asDerived().visitArray(PCK, AT, SL);
9896       return;
9897     }
9898 
9899     Super::visitWithKind(PCK, FT, SL);
9900   }
9901 
9902   void visitARCStrong(QualType FT, SourceLocation SL) {
9903     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9904   }
9905   void visitARCWeak(QualType FT, SourceLocation SL) {
9906     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9907   }
9908   void visitStruct(QualType FT, SourceLocation SL) {
9909     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9910       visit(FD->getType(), FD->getLocation());
9911   }
9912   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9913                   SourceLocation SL) {
9914     visit(getContext().getBaseElementType(AT), SL);
9915   }
9916   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9917                 SourceLocation SL) {}
9918   void visitTrivial(QualType FT, SourceLocation SL) {}
9919   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9920 
9921   static void diag(QualType RT, const Expr *E, Sema &S) {
9922     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9923   }
9924 
9925   ASTContext &getContext() { return S.getASTContext(); }
9926 
9927   const Expr *E;
9928   Sema &S;
9929 };
9930 
9931 }
9932 
9933 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9934 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9935   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9936 
9937   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9938     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9939       return false;
9940 
9941     return doesExprLikelyComputeSize(BO->getLHS()) ||
9942            doesExprLikelyComputeSize(BO->getRHS());
9943   }
9944 
9945   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9946 }
9947 
9948 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9949 ///
9950 /// \code
9951 ///   #define MACRO 0
9952 ///   foo(MACRO);
9953 ///   foo(0);
9954 /// \endcode
9955 ///
9956 /// This should return true for the first call to foo, but not for the second
9957 /// (regardless of whether foo is a macro or function).
9958 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9959                                         SourceLocation CallLoc,
9960                                         SourceLocation ArgLoc) {
9961   if (!CallLoc.isMacroID())
9962     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9963 
9964   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9965          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9966 }
9967 
9968 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9969 /// last two arguments transposed.
9970 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9971   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9972     return;
9973 
9974   const Expr *SizeArg =
9975     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9976 
9977   auto isLiteralZero = [](const Expr *E) {
9978     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9979   };
9980 
9981   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9982   SourceLocation CallLoc = Call->getRParenLoc();
9983   SourceManager &SM = S.getSourceManager();
9984   if (isLiteralZero(SizeArg) &&
9985       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9986 
9987     SourceLocation DiagLoc = SizeArg->getExprLoc();
9988 
9989     // Some platforms #define bzero to __builtin_memset. See if this is the
9990     // case, and if so, emit a better diagnostic.
9991     if (BId == Builtin::BIbzero ||
9992         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9993                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9994       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9995       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9996     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9997       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9998       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9999     }
10000     return;
10001   }
10002 
10003   // If the second argument to a memset is a sizeof expression and the third
10004   // isn't, this is also likely an error. This should catch
10005   // 'memset(buf, sizeof(buf), 0xff)'.
10006   if (BId == Builtin::BImemset &&
10007       doesExprLikelyComputeSize(Call->getArg(1)) &&
10008       !doesExprLikelyComputeSize(Call->getArg(2))) {
10009     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10010     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10011     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10012     return;
10013   }
10014 }
10015 
10016 /// Check for dangerous or invalid arguments to memset().
10017 ///
10018 /// This issues warnings on known problematic, dangerous or unspecified
10019 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10020 /// function calls.
10021 ///
10022 /// \param Call The call expression to diagnose.
10023 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10024                                    unsigned BId,
10025                                    IdentifierInfo *FnName) {
10026   assert(BId != 0);
10027 
10028   // It is possible to have a non-standard definition of memset.  Validate
10029   // we have enough arguments, and if not, abort further checking.
10030   unsigned ExpectedNumArgs =
10031       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10032   if (Call->getNumArgs() < ExpectedNumArgs)
10033     return;
10034 
10035   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10036                       BId == Builtin::BIstrndup ? 1 : 2);
10037   unsigned LenArg =
10038       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10039   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10040 
10041   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10042                                      Call->getBeginLoc(), Call->getRParenLoc()))
10043     return;
10044 
10045   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10046   CheckMemaccessSize(*this, BId, Call);
10047 
10048   // We have special checking when the length is a sizeof expression.
10049   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10050   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10051   llvm::FoldingSetNodeID SizeOfArgID;
10052 
10053   // Although widely used, 'bzero' is not a standard function. Be more strict
10054   // with the argument types before allowing diagnostics and only allow the
10055   // form bzero(ptr, sizeof(...)).
10056   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10057   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10058     return;
10059 
10060   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10061     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10062     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10063 
10064     QualType DestTy = Dest->getType();
10065     QualType PointeeTy;
10066     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10067       PointeeTy = DestPtrTy->getPointeeType();
10068 
10069       // Never warn about void type pointers. This can be used to suppress
10070       // false positives.
10071       if (PointeeTy->isVoidType())
10072         continue;
10073 
10074       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10075       // actually comparing the expressions for equality. Because computing the
10076       // expression IDs can be expensive, we only do this if the diagnostic is
10077       // enabled.
10078       if (SizeOfArg &&
10079           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10080                            SizeOfArg->getExprLoc())) {
10081         // We only compute IDs for expressions if the warning is enabled, and
10082         // cache the sizeof arg's ID.
10083         if (SizeOfArgID == llvm::FoldingSetNodeID())
10084           SizeOfArg->Profile(SizeOfArgID, Context, true);
10085         llvm::FoldingSetNodeID DestID;
10086         Dest->Profile(DestID, Context, true);
10087         if (DestID == SizeOfArgID) {
10088           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10089           //       over sizeof(src) as well.
10090           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10091           StringRef ReadableName = FnName->getName();
10092 
10093           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10094             if (UnaryOp->getOpcode() == UO_AddrOf)
10095               ActionIdx = 1; // If its an address-of operator, just remove it.
10096           if (!PointeeTy->isIncompleteType() &&
10097               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10098             ActionIdx = 2; // If the pointee's size is sizeof(char),
10099                            // suggest an explicit length.
10100 
10101           // If the function is defined as a builtin macro, do not show macro
10102           // expansion.
10103           SourceLocation SL = SizeOfArg->getExprLoc();
10104           SourceRange DSR = Dest->getSourceRange();
10105           SourceRange SSR = SizeOfArg->getSourceRange();
10106           SourceManager &SM = getSourceManager();
10107 
10108           if (SM.isMacroArgExpansion(SL)) {
10109             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10110             SL = SM.getSpellingLoc(SL);
10111             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10112                              SM.getSpellingLoc(DSR.getEnd()));
10113             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10114                              SM.getSpellingLoc(SSR.getEnd()));
10115           }
10116 
10117           DiagRuntimeBehavior(SL, SizeOfArg,
10118                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10119                                 << ReadableName
10120                                 << PointeeTy
10121                                 << DestTy
10122                                 << DSR
10123                                 << SSR);
10124           DiagRuntimeBehavior(SL, SizeOfArg,
10125                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10126                                 << ActionIdx
10127                                 << SSR);
10128 
10129           break;
10130         }
10131       }
10132 
10133       // Also check for cases where the sizeof argument is the exact same
10134       // type as the memory argument, and where it points to a user-defined
10135       // record type.
10136       if (SizeOfArgTy != QualType()) {
10137         if (PointeeTy->isRecordType() &&
10138             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10139           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10140                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10141                                 << FnName << SizeOfArgTy << ArgIdx
10142                                 << PointeeTy << Dest->getSourceRange()
10143                                 << LenExpr->getSourceRange());
10144           break;
10145         }
10146       }
10147     } else if (DestTy->isArrayType()) {
10148       PointeeTy = DestTy;
10149     }
10150 
10151     if (PointeeTy == QualType())
10152       continue;
10153 
10154     // Always complain about dynamic classes.
10155     bool IsContained;
10156     if (const CXXRecordDecl *ContainedRD =
10157             getContainedDynamicClass(PointeeTy, IsContained)) {
10158 
10159       unsigned OperationType = 0;
10160       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10161       // "overwritten" if we're warning about the destination for any call
10162       // but memcmp; otherwise a verb appropriate to the call.
10163       if (ArgIdx != 0 || IsCmp) {
10164         if (BId == Builtin::BImemcpy)
10165           OperationType = 1;
10166         else if(BId == Builtin::BImemmove)
10167           OperationType = 2;
10168         else if (IsCmp)
10169           OperationType = 3;
10170       }
10171 
10172       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10173                           PDiag(diag::warn_dyn_class_memaccess)
10174                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10175                               << IsContained << ContainedRD << OperationType
10176                               << Call->getCallee()->getSourceRange());
10177     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10178              BId != Builtin::BImemset)
10179       DiagRuntimeBehavior(
10180         Dest->getExprLoc(), Dest,
10181         PDiag(diag::warn_arc_object_memaccess)
10182           << ArgIdx << FnName << PointeeTy
10183           << Call->getCallee()->getSourceRange());
10184     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10185       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10186           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10187         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10188                             PDiag(diag::warn_cstruct_memaccess)
10189                                 << ArgIdx << FnName << PointeeTy << 0);
10190         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10191       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10192                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10193         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10194                             PDiag(diag::warn_cstruct_memaccess)
10195                                 << ArgIdx << FnName << PointeeTy << 1);
10196         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10197       } else {
10198         continue;
10199       }
10200     } else
10201       continue;
10202 
10203     DiagRuntimeBehavior(
10204       Dest->getExprLoc(), Dest,
10205       PDiag(diag::note_bad_memaccess_silence)
10206         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10207     break;
10208   }
10209 }
10210 
10211 // A little helper routine: ignore addition and subtraction of integer literals.
10212 // This intentionally does not ignore all integer constant expressions because
10213 // we don't want to remove sizeof().
10214 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10215   Ex = Ex->IgnoreParenCasts();
10216 
10217   while (true) {
10218     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10219     if (!BO || !BO->isAdditiveOp())
10220       break;
10221 
10222     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10223     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10224 
10225     if (isa<IntegerLiteral>(RHS))
10226       Ex = LHS;
10227     else if (isa<IntegerLiteral>(LHS))
10228       Ex = RHS;
10229     else
10230       break;
10231   }
10232 
10233   return Ex;
10234 }
10235 
10236 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10237                                                       ASTContext &Context) {
10238   // Only handle constant-sized or VLAs, but not flexible members.
10239   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10240     // Only issue the FIXIT for arrays of size > 1.
10241     if (CAT->getSize().getSExtValue() <= 1)
10242       return false;
10243   } else if (!Ty->isVariableArrayType()) {
10244     return false;
10245   }
10246   return true;
10247 }
10248 
10249 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10250 // be the size of the source, instead of the destination.
10251 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10252                                     IdentifierInfo *FnName) {
10253 
10254   // Don't crash if the user has the wrong number of arguments
10255   unsigned NumArgs = Call->getNumArgs();
10256   if ((NumArgs != 3) && (NumArgs != 4))
10257     return;
10258 
10259   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10260   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10261   const Expr *CompareWithSrc = nullptr;
10262 
10263   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10264                                      Call->getBeginLoc(), Call->getRParenLoc()))
10265     return;
10266 
10267   // Look for 'strlcpy(dst, x, sizeof(x))'
10268   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10269     CompareWithSrc = Ex;
10270   else {
10271     // Look for 'strlcpy(dst, x, strlen(x))'
10272     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10273       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10274           SizeCall->getNumArgs() == 1)
10275         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10276     }
10277   }
10278 
10279   if (!CompareWithSrc)
10280     return;
10281 
10282   // Determine if the argument to sizeof/strlen is equal to the source
10283   // argument.  In principle there's all kinds of things you could do
10284   // here, for instance creating an == expression and evaluating it with
10285   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10286   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10287   if (!SrcArgDRE)
10288     return;
10289 
10290   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10291   if (!CompareWithSrcDRE ||
10292       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10293     return;
10294 
10295   const Expr *OriginalSizeArg = Call->getArg(2);
10296   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10297       << OriginalSizeArg->getSourceRange() << FnName;
10298 
10299   // Output a FIXIT hint if the destination is an array (rather than a
10300   // pointer to an array).  This could be enhanced to handle some
10301   // pointers if we know the actual size, like if DstArg is 'array+2'
10302   // we could say 'sizeof(array)-2'.
10303   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10304   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10305     return;
10306 
10307   SmallString<128> sizeString;
10308   llvm::raw_svector_ostream OS(sizeString);
10309   OS << "sizeof(";
10310   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10311   OS << ")";
10312 
10313   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10314       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10315                                       OS.str());
10316 }
10317 
10318 /// Check if two expressions refer to the same declaration.
10319 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10320   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10321     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10322       return D1->getDecl() == D2->getDecl();
10323   return false;
10324 }
10325 
10326 static const Expr *getStrlenExprArg(const Expr *E) {
10327   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10328     const FunctionDecl *FD = CE->getDirectCallee();
10329     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10330       return nullptr;
10331     return CE->getArg(0)->IgnoreParenCasts();
10332   }
10333   return nullptr;
10334 }
10335 
10336 // Warn on anti-patterns as the 'size' argument to strncat.
10337 // The correct size argument should look like following:
10338 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10339 void Sema::CheckStrncatArguments(const CallExpr *CE,
10340                                  IdentifierInfo *FnName) {
10341   // Don't crash if the user has the wrong number of arguments.
10342   if (CE->getNumArgs() < 3)
10343     return;
10344   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10345   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10346   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10347 
10348   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10349                                      CE->getRParenLoc()))
10350     return;
10351 
10352   // Identify common expressions, which are wrongly used as the size argument
10353   // to strncat and may lead to buffer overflows.
10354   unsigned PatternType = 0;
10355   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10356     // - sizeof(dst)
10357     if (referToTheSameDecl(SizeOfArg, DstArg))
10358       PatternType = 1;
10359     // - sizeof(src)
10360     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10361       PatternType = 2;
10362   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10363     if (BE->getOpcode() == BO_Sub) {
10364       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10365       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10366       // - sizeof(dst) - strlen(dst)
10367       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10368           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10369         PatternType = 1;
10370       // - sizeof(src) - (anything)
10371       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10372         PatternType = 2;
10373     }
10374   }
10375 
10376   if (PatternType == 0)
10377     return;
10378 
10379   // Generate the diagnostic.
10380   SourceLocation SL = LenArg->getBeginLoc();
10381   SourceRange SR = LenArg->getSourceRange();
10382   SourceManager &SM = getSourceManager();
10383 
10384   // If the function is defined as a builtin macro, do not show macro expansion.
10385   if (SM.isMacroArgExpansion(SL)) {
10386     SL = SM.getSpellingLoc(SL);
10387     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10388                      SM.getSpellingLoc(SR.getEnd()));
10389   }
10390 
10391   // Check if the destination is an array (rather than a pointer to an array).
10392   QualType DstTy = DstArg->getType();
10393   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10394                                                                     Context);
10395   if (!isKnownSizeArray) {
10396     if (PatternType == 1)
10397       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10398     else
10399       Diag(SL, diag::warn_strncat_src_size) << SR;
10400     return;
10401   }
10402 
10403   if (PatternType == 1)
10404     Diag(SL, diag::warn_strncat_large_size) << SR;
10405   else
10406     Diag(SL, diag::warn_strncat_src_size) << SR;
10407 
10408   SmallString<128> sizeString;
10409   llvm::raw_svector_ostream OS(sizeString);
10410   OS << "sizeof(";
10411   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10412   OS << ") - ";
10413   OS << "strlen(";
10414   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10415   OS << ") - 1";
10416 
10417   Diag(SL, diag::note_strncat_wrong_size)
10418     << FixItHint::CreateReplacement(SR, OS.str());
10419 }
10420 
10421 namespace {
10422 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10423                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10424   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10425     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10426         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10427     return;
10428   }
10429 }
10430 
10431 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10432                                  const UnaryOperator *UnaryExpr) {
10433   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10434     const Decl *D = Lvalue->getDecl();
10435     if (isa<VarDecl, FunctionDecl>(D))
10436       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10437   }
10438 
10439   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10440     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10441                                       Lvalue->getMemberDecl());
10442 }
10443 
10444 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10445                             const UnaryOperator *UnaryExpr) {
10446   const auto *Lambda = dyn_cast<LambdaExpr>(
10447       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10448   if (!Lambda)
10449     return;
10450 
10451   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10452       << CalleeName << 2 /*object: lambda expression*/;
10453 }
10454 
10455 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10456                                   const DeclRefExpr *Lvalue) {
10457   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10458   if (Var == nullptr)
10459     return;
10460 
10461   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10462       << CalleeName << 0 /*object: */ << Var;
10463 }
10464 
10465 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10466                             const CastExpr *Cast) {
10467   SmallString<128> SizeString;
10468   llvm::raw_svector_ostream OS(SizeString);
10469 
10470   clang::CastKind Kind = Cast->getCastKind();
10471   if (Kind == clang::CK_BitCast &&
10472       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10473     return;
10474   if (Kind == clang::CK_IntegralToPointer &&
10475       !isa<IntegerLiteral>(
10476           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10477     return;
10478 
10479   switch (Cast->getCastKind()) {
10480   case clang::CK_BitCast:
10481   case clang::CK_IntegralToPointer:
10482   case clang::CK_FunctionToPointerDecay:
10483     OS << '\'';
10484     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10485     OS << '\'';
10486     break;
10487   default:
10488     return;
10489   }
10490 
10491   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10492       << CalleeName << 0 /*object: */ << OS.str();
10493 }
10494 } // namespace
10495 
10496 /// Alerts the user that they are attempting to free a non-malloc'd object.
10497 void Sema::CheckFreeArguments(const CallExpr *E) {
10498   const std::string CalleeName =
10499       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10500 
10501   { // Prefer something that doesn't involve a cast to make things simpler.
10502     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10503     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10504       switch (UnaryExpr->getOpcode()) {
10505       case UnaryOperator::Opcode::UO_AddrOf:
10506         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10507       case UnaryOperator::Opcode::UO_Plus:
10508         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10509       default:
10510         break;
10511       }
10512 
10513     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10514       if (Lvalue->getType()->isArrayType())
10515         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10516 
10517     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10518       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10519           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10520       return;
10521     }
10522 
10523     if (isa<BlockExpr>(Arg)) {
10524       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10525           << CalleeName << 1 /*object: block*/;
10526       return;
10527     }
10528   }
10529   // Maybe the cast was important, check after the other cases.
10530   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10531     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10532 }
10533 
10534 void
10535 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10536                          SourceLocation ReturnLoc,
10537                          bool isObjCMethod,
10538                          const AttrVec *Attrs,
10539                          const FunctionDecl *FD) {
10540   // Check if the return value is null but should not be.
10541   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10542        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10543       CheckNonNullExpr(*this, RetValExp))
10544     Diag(ReturnLoc, diag::warn_null_ret)
10545       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10546 
10547   // C++11 [basic.stc.dynamic.allocation]p4:
10548   //   If an allocation function declared with a non-throwing
10549   //   exception-specification fails to allocate storage, it shall return
10550   //   a null pointer. Any other allocation function that fails to allocate
10551   //   storage shall indicate failure only by throwing an exception [...]
10552   if (FD) {
10553     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10554     if (Op == OO_New || Op == OO_Array_New) {
10555       const FunctionProtoType *Proto
10556         = FD->getType()->castAs<FunctionProtoType>();
10557       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10558           CheckNonNullExpr(*this, RetValExp))
10559         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10560           << FD << getLangOpts().CPlusPlus11;
10561     }
10562   }
10563 
10564   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10565   // here prevent the user from using a PPC MMA type as trailing return type.
10566   if (Context.getTargetInfo().getTriple().isPPC64())
10567     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10568 }
10569 
10570 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10571 
10572 /// Check for comparisons of floating point operands using != and ==.
10573 /// Issue a warning if these are no self-comparisons, as they are not likely
10574 /// to do what the programmer intended.
10575 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10576   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10577   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10578 
10579   // Special case: check for x == x (which is OK).
10580   // Do not emit warnings for such cases.
10581   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10582     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10583       if (DRL->getDecl() == DRR->getDecl())
10584         return;
10585 
10586   // Special case: check for comparisons against literals that can be exactly
10587   //  represented by APFloat.  In such cases, do not emit a warning.  This
10588   //  is a heuristic: often comparison against such literals are used to
10589   //  detect if a value in a variable has not changed.  This clearly can
10590   //  lead to false negatives.
10591   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10592     if (FLL->isExact())
10593       return;
10594   } else
10595     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10596       if (FLR->isExact())
10597         return;
10598 
10599   // Check for comparisons with builtin types.
10600   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10601     if (CL->getBuiltinCallee())
10602       return;
10603 
10604   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10605     if (CR->getBuiltinCallee())
10606       return;
10607 
10608   // Emit the diagnostic.
10609   Diag(Loc, diag::warn_floatingpoint_eq)
10610     << LHS->getSourceRange() << RHS->getSourceRange();
10611 }
10612 
10613 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10614 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10615 
10616 namespace {
10617 
10618 /// Structure recording the 'active' range of an integer-valued
10619 /// expression.
10620 struct IntRange {
10621   /// The number of bits active in the int. Note that this includes exactly one
10622   /// sign bit if !NonNegative.
10623   unsigned Width;
10624 
10625   /// True if the int is known not to have negative values. If so, all leading
10626   /// bits before Width are known zero, otherwise they are known to be the
10627   /// same as the MSB within Width.
10628   bool NonNegative;
10629 
10630   IntRange(unsigned Width, bool NonNegative)
10631       : Width(Width), NonNegative(NonNegative) {}
10632 
10633   /// Number of bits excluding the sign bit.
10634   unsigned valueBits() const {
10635     return NonNegative ? Width : Width - 1;
10636   }
10637 
10638   /// Returns the range of the bool type.
10639   static IntRange forBoolType() {
10640     return IntRange(1, true);
10641   }
10642 
10643   /// Returns the range of an opaque value of the given integral type.
10644   static IntRange forValueOfType(ASTContext &C, QualType T) {
10645     return forValueOfCanonicalType(C,
10646                           T->getCanonicalTypeInternal().getTypePtr());
10647   }
10648 
10649   /// Returns the range of an opaque value of a canonical integral type.
10650   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10651     assert(T->isCanonicalUnqualified());
10652 
10653     if (const VectorType *VT = dyn_cast<VectorType>(T))
10654       T = VT->getElementType().getTypePtr();
10655     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10656       T = CT->getElementType().getTypePtr();
10657     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10658       T = AT->getValueType().getTypePtr();
10659 
10660     if (!C.getLangOpts().CPlusPlus) {
10661       // For enum types in C code, use the underlying datatype.
10662       if (const EnumType *ET = dyn_cast<EnumType>(T))
10663         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10664     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10665       // For enum types in C++, use the known bit width of the enumerators.
10666       EnumDecl *Enum = ET->getDecl();
10667       // In C++11, enums can have a fixed underlying type. Use this type to
10668       // compute the range.
10669       if (Enum->isFixed()) {
10670         return IntRange(C.getIntWidth(QualType(T, 0)),
10671                         !ET->isSignedIntegerOrEnumerationType());
10672       }
10673 
10674       unsigned NumPositive = Enum->getNumPositiveBits();
10675       unsigned NumNegative = Enum->getNumNegativeBits();
10676 
10677       if (NumNegative == 0)
10678         return IntRange(NumPositive, true/*NonNegative*/);
10679       else
10680         return IntRange(std::max(NumPositive + 1, NumNegative),
10681                         false/*NonNegative*/);
10682     }
10683 
10684     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10685       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10686 
10687     const BuiltinType *BT = cast<BuiltinType>(T);
10688     assert(BT->isInteger());
10689 
10690     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10691   }
10692 
10693   /// Returns the "target" range of a canonical integral type, i.e.
10694   /// the range of values expressible in the type.
10695   ///
10696   /// This matches forValueOfCanonicalType except that enums have the
10697   /// full range of their type, not the range of their enumerators.
10698   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10699     assert(T->isCanonicalUnqualified());
10700 
10701     if (const VectorType *VT = dyn_cast<VectorType>(T))
10702       T = VT->getElementType().getTypePtr();
10703     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10704       T = CT->getElementType().getTypePtr();
10705     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10706       T = AT->getValueType().getTypePtr();
10707     if (const EnumType *ET = dyn_cast<EnumType>(T))
10708       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10709 
10710     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10711       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10712 
10713     const BuiltinType *BT = cast<BuiltinType>(T);
10714     assert(BT->isInteger());
10715 
10716     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10717   }
10718 
10719   /// Returns the supremum of two ranges: i.e. their conservative merge.
10720   static IntRange join(IntRange L, IntRange R) {
10721     bool Unsigned = L.NonNegative && R.NonNegative;
10722     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10723                     L.NonNegative && R.NonNegative);
10724   }
10725 
10726   /// Return the range of a bitwise-AND of the two ranges.
10727   static IntRange bit_and(IntRange L, IntRange R) {
10728     unsigned Bits = std::max(L.Width, R.Width);
10729     bool NonNegative = false;
10730     if (L.NonNegative) {
10731       Bits = std::min(Bits, L.Width);
10732       NonNegative = true;
10733     }
10734     if (R.NonNegative) {
10735       Bits = std::min(Bits, R.Width);
10736       NonNegative = true;
10737     }
10738     return IntRange(Bits, NonNegative);
10739   }
10740 
10741   /// Return the range of a sum of the two ranges.
10742   static IntRange sum(IntRange L, IntRange R) {
10743     bool Unsigned = L.NonNegative && R.NonNegative;
10744     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10745                     Unsigned);
10746   }
10747 
10748   /// Return the range of a difference of the two ranges.
10749   static IntRange difference(IntRange L, IntRange R) {
10750     // We need a 1-bit-wider range if:
10751     //   1) LHS can be negative: least value can be reduced.
10752     //   2) RHS can be negative: greatest value can be increased.
10753     bool CanWiden = !L.NonNegative || !R.NonNegative;
10754     bool Unsigned = L.NonNegative && R.Width == 0;
10755     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10756                         !Unsigned,
10757                     Unsigned);
10758   }
10759 
10760   /// Return the range of a product of the two ranges.
10761   static IntRange product(IntRange L, IntRange R) {
10762     // If both LHS and RHS can be negative, we can form
10763     //   -2^L * -2^R = 2^(L + R)
10764     // which requires L + R + 1 value bits to represent.
10765     bool CanWiden = !L.NonNegative && !R.NonNegative;
10766     bool Unsigned = L.NonNegative && R.NonNegative;
10767     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10768                     Unsigned);
10769   }
10770 
10771   /// Return the range of a remainder operation between the two ranges.
10772   static IntRange rem(IntRange L, IntRange R) {
10773     // The result of a remainder can't be larger than the result of
10774     // either side. The sign of the result is the sign of the LHS.
10775     bool Unsigned = L.NonNegative;
10776     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10777                     Unsigned);
10778   }
10779 };
10780 
10781 } // namespace
10782 
10783 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10784                               unsigned MaxWidth) {
10785   if (value.isSigned() && value.isNegative())
10786     return IntRange(value.getMinSignedBits(), false);
10787 
10788   if (value.getBitWidth() > MaxWidth)
10789     value = value.trunc(MaxWidth);
10790 
10791   // isNonNegative() just checks the sign bit without considering
10792   // signedness.
10793   return IntRange(value.getActiveBits(), true);
10794 }
10795 
10796 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10797                               unsigned MaxWidth) {
10798   if (result.isInt())
10799     return GetValueRange(C, result.getInt(), MaxWidth);
10800 
10801   if (result.isVector()) {
10802     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10803     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10804       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10805       R = IntRange::join(R, El);
10806     }
10807     return R;
10808   }
10809 
10810   if (result.isComplexInt()) {
10811     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10812     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10813     return IntRange::join(R, I);
10814   }
10815 
10816   // This can happen with lossless casts to intptr_t of "based" lvalues.
10817   // Assume it might use arbitrary bits.
10818   // FIXME: The only reason we need to pass the type in here is to get
10819   // the sign right on this one case.  It would be nice if APValue
10820   // preserved this.
10821   assert(result.isLValue() || result.isAddrLabelDiff());
10822   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10823 }
10824 
10825 static QualType GetExprType(const Expr *E) {
10826   QualType Ty = E->getType();
10827   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10828     Ty = AtomicRHS->getValueType();
10829   return Ty;
10830 }
10831 
10832 /// Pseudo-evaluate the given integer expression, estimating the
10833 /// range of values it might take.
10834 ///
10835 /// \param MaxWidth The width to which the value will be truncated.
10836 /// \param Approximate If \c true, return a likely range for the result: in
10837 ///        particular, assume that aritmetic on narrower types doesn't leave
10838 ///        those types. If \c false, return a range including all possible
10839 ///        result values.
10840 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10841                              bool InConstantContext, bool Approximate) {
10842   E = E->IgnoreParens();
10843 
10844   // Try a full evaluation first.
10845   Expr::EvalResult result;
10846   if (E->EvaluateAsRValue(result, C, InConstantContext))
10847     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10848 
10849   // I think we only want to look through implicit casts here; if the
10850   // user has an explicit widening cast, we should treat the value as
10851   // being of the new, wider type.
10852   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10853     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10854       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10855                           Approximate);
10856 
10857     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10858 
10859     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10860                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10861 
10862     // Assume that non-integer casts can span the full range of the type.
10863     if (!isIntegerCast)
10864       return OutputTypeRange;
10865 
10866     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10867                                      std::min(MaxWidth, OutputTypeRange.Width),
10868                                      InConstantContext, Approximate);
10869 
10870     // Bail out if the subexpr's range is as wide as the cast type.
10871     if (SubRange.Width >= OutputTypeRange.Width)
10872       return OutputTypeRange;
10873 
10874     // Otherwise, we take the smaller width, and we're non-negative if
10875     // either the output type or the subexpr is.
10876     return IntRange(SubRange.Width,
10877                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10878   }
10879 
10880   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10881     // If we can fold the condition, just take that operand.
10882     bool CondResult;
10883     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10884       return GetExprRange(C,
10885                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10886                           MaxWidth, InConstantContext, Approximate);
10887 
10888     // Otherwise, conservatively merge.
10889     // GetExprRange requires an integer expression, but a throw expression
10890     // results in a void type.
10891     Expr *E = CO->getTrueExpr();
10892     IntRange L = E->getType()->isVoidType()
10893                      ? IntRange{0, true}
10894                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10895     E = CO->getFalseExpr();
10896     IntRange R = E->getType()->isVoidType()
10897                      ? IntRange{0, true}
10898                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10899     return IntRange::join(L, R);
10900   }
10901 
10902   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10903     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10904 
10905     switch (BO->getOpcode()) {
10906     case BO_Cmp:
10907       llvm_unreachable("builtin <=> should have class type");
10908 
10909     // Boolean-valued operations are single-bit and positive.
10910     case BO_LAnd:
10911     case BO_LOr:
10912     case BO_LT:
10913     case BO_GT:
10914     case BO_LE:
10915     case BO_GE:
10916     case BO_EQ:
10917     case BO_NE:
10918       return IntRange::forBoolType();
10919 
10920     // The type of the assignments is the type of the LHS, so the RHS
10921     // is not necessarily the same type.
10922     case BO_MulAssign:
10923     case BO_DivAssign:
10924     case BO_RemAssign:
10925     case BO_AddAssign:
10926     case BO_SubAssign:
10927     case BO_XorAssign:
10928     case BO_OrAssign:
10929       // TODO: bitfields?
10930       return IntRange::forValueOfType(C, GetExprType(E));
10931 
10932     // Simple assignments just pass through the RHS, which will have
10933     // been coerced to the LHS type.
10934     case BO_Assign:
10935       // TODO: bitfields?
10936       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10937                           Approximate);
10938 
10939     // Operations with opaque sources are black-listed.
10940     case BO_PtrMemD:
10941     case BO_PtrMemI:
10942       return IntRange::forValueOfType(C, GetExprType(E));
10943 
10944     // Bitwise-and uses the *infinum* of the two source ranges.
10945     case BO_And:
10946     case BO_AndAssign:
10947       Combine = IntRange::bit_and;
10948       break;
10949 
10950     // Left shift gets black-listed based on a judgement call.
10951     case BO_Shl:
10952       // ...except that we want to treat '1 << (blah)' as logically
10953       // positive.  It's an important idiom.
10954       if (IntegerLiteral *I
10955             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10956         if (I->getValue() == 1) {
10957           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10958           return IntRange(R.Width, /*NonNegative*/ true);
10959         }
10960       }
10961       LLVM_FALLTHROUGH;
10962 
10963     case BO_ShlAssign:
10964       return IntRange::forValueOfType(C, GetExprType(E));
10965 
10966     // Right shift by a constant can narrow its left argument.
10967     case BO_Shr:
10968     case BO_ShrAssign: {
10969       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10970                                 Approximate);
10971 
10972       // If the shift amount is a positive constant, drop the width by
10973       // that much.
10974       if (Optional<llvm::APSInt> shift =
10975               BO->getRHS()->getIntegerConstantExpr(C)) {
10976         if (shift->isNonNegative()) {
10977           unsigned zext = shift->getZExtValue();
10978           if (zext >= L.Width)
10979             L.Width = (L.NonNegative ? 0 : 1);
10980           else
10981             L.Width -= zext;
10982         }
10983       }
10984 
10985       return L;
10986     }
10987 
10988     // Comma acts as its right operand.
10989     case BO_Comma:
10990       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10991                           Approximate);
10992 
10993     case BO_Add:
10994       if (!Approximate)
10995         Combine = IntRange::sum;
10996       break;
10997 
10998     case BO_Sub:
10999       if (BO->getLHS()->getType()->isPointerType())
11000         return IntRange::forValueOfType(C, GetExprType(E));
11001       if (!Approximate)
11002         Combine = IntRange::difference;
11003       break;
11004 
11005     case BO_Mul:
11006       if (!Approximate)
11007         Combine = IntRange::product;
11008       break;
11009 
11010     // The width of a division result is mostly determined by the size
11011     // of the LHS.
11012     case BO_Div: {
11013       // Don't 'pre-truncate' the operands.
11014       unsigned opWidth = C.getIntWidth(GetExprType(E));
11015       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11016                                 Approximate);
11017 
11018       // If the divisor is constant, use that.
11019       if (Optional<llvm::APSInt> divisor =
11020               BO->getRHS()->getIntegerConstantExpr(C)) {
11021         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11022         if (log2 >= L.Width)
11023           L.Width = (L.NonNegative ? 0 : 1);
11024         else
11025           L.Width = std::min(L.Width - log2, MaxWidth);
11026         return L;
11027       }
11028 
11029       // Otherwise, just use the LHS's width.
11030       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11031       // could be -1.
11032       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11033                                 Approximate);
11034       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11035     }
11036 
11037     case BO_Rem:
11038       Combine = IntRange::rem;
11039       break;
11040 
11041     // The default behavior is okay for these.
11042     case BO_Xor:
11043     case BO_Or:
11044       break;
11045     }
11046 
11047     // Combine the two ranges, but limit the result to the type in which we
11048     // performed the computation.
11049     QualType T = GetExprType(E);
11050     unsigned opWidth = C.getIntWidth(T);
11051     IntRange L =
11052         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11053     IntRange R =
11054         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11055     IntRange C = Combine(L, R);
11056     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11057     C.Width = std::min(C.Width, MaxWidth);
11058     return C;
11059   }
11060 
11061   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11062     switch (UO->getOpcode()) {
11063     // Boolean-valued operations are white-listed.
11064     case UO_LNot:
11065       return IntRange::forBoolType();
11066 
11067     // Operations with opaque sources are black-listed.
11068     case UO_Deref:
11069     case UO_AddrOf: // should be impossible
11070       return IntRange::forValueOfType(C, GetExprType(E));
11071 
11072     default:
11073       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11074                           Approximate);
11075     }
11076   }
11077 
11078   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11079     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11080                         Approximate);
11081 
11082   if (const auto *BitField = E->getSourceBitField())
11083     return IntRange(BitField->getBitWidthValue(C),
11084                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11085 
11086   return IntRange::forValueOfType(C, GetExprType(E));
11087 }
11088 
11089 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11090                              bool InConstantContext, bool Approximate) {
11091   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11092                       Approximate);
11093 }
11094 
11095 /// Checks whether the given value, which currently has the given
11096 /// source semantics, has the same value when coerced through the
11097 /// target semantics.
11098 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11099                                  const llvm::fltSemantics &Src,
11100                                  const llvm::fltSemantics &Tgt) {
11101   llvm::APFloat truncated = value;
11102 
11103   bool ignored;
11104   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11105   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11106 
11107   return truncated.bitwiseIsEqual(value);
11108 }
11109 
11110 /// Checks whether the given value, which currently has the given
11111 /// source semantics, has the same value when coerced through the
11112 /// target semantics.
11113 ///
11114 /// The value might be a vector of floats (or a complex number).
11115 static bool IsSameFloatAfterCast(const APValue &value,
11116                                  const llvm::fltSemantics &Src,
11117                                  const llvm::fltSemantics &Tgt) {
11118   if (value.isFloat())
11119     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11120 
11121   if (value.isVector()) {
11122     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11123       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11124         return false;
11125     return true;
11126   }
11127 
11128   assert(value.isComplexFloat());
11129   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11130           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11131 }
11132 
11133 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11134                                        bool IsListInit = false);
11135 
11136 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11137   // Suppress cases where we are comparing against an enum constant.
11138   if (const DeclRefExpr *DR =
11139       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11140     if (isa<EnumConstantDecl>(DR->getDecl()))
11141       return true;
11142 
11143   // Suppress cases where the value is expanded from a macro, unless that macro
11144   // is how a language represents a boolean literal. This is the case in both C
11145   // and Objective-C.
11146   SourceLocation BeginLoc = E->getBeginLoc();
11147   if (BeginLoc.isMacroID()) {
11148     StringRef MacroName = Lexer::getImmediateMacroName(
11149         BeginLoc, S.getSourceManager(), S.getLangOpts());
11150     return MacroName != "YES" && MacroName != "NO" &&
11151            MacroName != "true" && MacroName != "false";
11152   }
11153 
11154   return false;
11155 }
11156 
11157 static bool isKnownToHaveUnsignedValue(Expr *E) {
11158   return E->getType()->isIntegerType() &&
11159          (!E->getType()->isSignedIntegerType() ||
11160           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11161 }
11162 
11163 namespace {
11164 /// The promoted range of values of a type. In general this has the
11165 /// following structure:
11166 ///
11167 ///     |-----------| . . . |-----------|
11168 ///     ^           ^       ^           ^
11169 ///    Min       HoleMin  HoleMax      Max
11170 ///
11171 /// ... where there is only a hole if a signed type is promoted to unsigned
11172 /// (in which case Min and Max are the smallest and largest representable
11173 /// values).
11174 struct PromotedRange {
11175   // Min, or HoleMax if there is a hole.
11176   llvm::APSInt PromotedMin;
11177   // Max, or HoleMin if there is a hole.
11178   llvm::APSInt PromotedMax;
11179 
11180   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11181     if (R.Width == 0)
11182       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11183     else if (R.Width >= BitWidth && !Unsigned) {
11184       // Promotion made the type *narrower*. This happens when promoting
11185       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11186       // Treat all values of 'signed int' as being in range for now.
11187       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11188       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11189     } else {
11190       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11191                         .extOrTrunc(BitWidth);
11192       PromotedMin.setIsUnsigned(Unsigned);
11193 
11194       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11195                         .extOrTrunc(BitWidth);
11196       PromotedMax.setIsUnsigned(Unsigned);
11197     }
11198   }
11199 
11200   // Determine whether this range is contiguous (has no hole).
11201   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11202 
11203   // Where a constant value is within the range.
11204   enum ComparisonResult {
11205     LT = 0x1,
11206     LE = 0x2,
11207     GT = 0x4,
11208     GE = 0x8,
11209     EQ = 0x10,
11210     NE = 0x20,
11211     InRangeFlag = 0x40,
11212 
11213     Less = LE | LT | NE,
11214     Min = LE | InRangeFlag,
11215     InRange = InRangeFlag,
11216     Max = GE | InRangeFlag,
11217     Greater = GE | GT | NE,
11218 
11219     OnlyValue = LE | GE | EQ | InRangeFlag,
11220     InHole = NE
11221   };
11222 
11223   ComparisonResult compare(const llvm::APSInt &Value) const {
11224     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11225            Value.isUnsigned() == PromotedMin.isUnsigned());
11226     if (!isContiguous()) {
11227       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11228       if (Value.isMinValue()) return Min;
11229       if (Value.isMaxValue()) return Max;
11230       if (Value >= PromotedMin) return InRange;
11231       if (Value <= PromotedMax) return InRange;
11232       return InHole;
11233     }
11234 
11235     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11236     case -1: return Less;
11237     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11238     case 1:
11239       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11240       case -1: return InRange;
11241       case 0: return Max;
11242       case 1: return Greater;
11243       }
11244     }
11245 
11246     llvm_unreachable("impossible compare result");
11247   }
11248 
11249   static llvm::Optional<StringRef>
11250   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11251     if (Op == BO_Cmp) {
11252       ComparisonResult LTFlag = LT, GTFlag = GT;
11253       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11254 
11255       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11256       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11257       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11258       return llvm::None;
11259     }
11260 
11261     ComparisonResult TrueFlag, FalseFlag;
11262     if (Op == BO_EQ) {
11263       TrueFlag = EQ;
11264       FalseFlag = NE;
11265     } else if (Op == BO_NE) {
11266       TrueFlag = NE;
11267       FalseFlag = EQ;
11268     } else {
11269       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11270         TrueFlag = LT;
11271         FalseFlag = GE;
11272       } else {
11273         TrueFlag = GT;
11274         FalseFlag = LE;
11275       }
11276       if (Op == BO_GE || Op == BO_LE)
11277         std::swap(TrueFlag, FalseFlag);
11278     }
11279     if (R & TrueFlag)
11280       return StringRef("true");
11281     if (R & FalseFlag)
11282       return StringRef("false");
11283     return llvm::None;
11284   }
11285 };
11286 }
11287 
11288 static bool HasEnumType(Expr *E) {
11289   // Strip off implicit integral promotions.
11290   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11291     if (ICE->getCastKind() != CK_IntegralCast &&
11292         ICE->getCastKind() != CK_NoOp)
11293       break;
11294     E = ICE->getSubExpr();
11295   }
11296 
11297   return E->getType()->isEnumeralType();
11298 }
11299 
11300 static int classifyConstantValue(Expr *Constant) {
11301   // The values of this enumeration are used in the diagnostics
11302   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11303   enum ConstantValueKind {
11304     Miscellaneous = 0,
11305     LiteralTrue,
11306     LiteralFalse
11307   };
11308   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11309     return BL->getValue() ? ConstantValueKind::LiteralTrue
11310                           : ConstantValueKind::LiteralFalse;
11311   return ConstantValueKind::Miscellaneous;
11312 }
11313 
11314 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11315                                         Expr *Constant, Expr *Other,
11316                                         const llvm::APSInt &Value,
11317                                         bool RhsConstant) {
11318   if (S.inTemplateInstantiation())
11319     return false;
11320 
11321   Expr *OriginalOther = Other;
11322 
11323   Constant = Constant->IgnoreParenImpCasts();
11324   Other = Other->IgnoreParenImpCasts();
11325 
11326   // Suppress warnings on tautological comparisons between values of the same
11327   // enumeration type. There are only two ways we could warn on this:
11328   //  - If the constant is outside the range of representable values of
11329   //    the enumeration. In such a case, we should warn about the cast
11330   //    to enumeration type, not about the comparison.
11331   //  - If the constant is the maximum / minimum in-range value. For an
11332   //    enumeratin type, such comparisons can be meaningful and useful.
11333   if (Constant->getType()->isEnumeralType() &&
11334       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11335     return false;
11336 
11337   IntRange OtherValueRange = GetExprRange(
11338       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11339 
11340   QualType OtherT = Other->getType();
11341   if (const auto *AT = OtherT->getAs<AtomicType>())
11342     OtherT = AT->getValueType();
11343   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11344 
11345   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11346   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11347   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11348                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11349                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11350 
11351   // Whether we're treating Other as being a bool because of the form of
11352   // expression despite it having another type (typically 'int' in C).
11353   bool OtherIsBooleanDespiteType =
11354       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11355   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11356     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11357 
11358   // Check if all values in the range of possible values of this expression
11359   // lead to the same comparison outcome.
11360   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11361                                         Value.isUnsigned());
11362   auto Cmp = OtherPromotedValueRange.compare(Value);
11363   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11364   if (!Result)
11365     return false;
11366 
11367   // Also consider the range determined by the type alone. This allows us to
11368   // classify the warning under the proper diagnostic group.
11369   bool TautologicalTypeCompare = false;
11370   {
11371     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11372                                          Value.isUnsigned());
11373     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11374     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11375                                                        RhsConstant)) {
11376       TautologicalTypeCompare = true;
11377       Cmp = TypeCmp;
11378       Result = TypeResult;
11379     }
11380   }
11381 
11382   // Don't warn if the non-constant operand actually always evaluates to the
11383   // same value.
11384   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11385     return false;
11386 
11387   // Suppress the diagnostic for an in-range comparison if the constant comes
11388   // from a macro or enumerator. We don't want to diagnose
11389   //
11390   //   some_long_value <= INT_MAX
11391   //
11392   // when sizeof(int) == sizeof(long).
11393   bool InRange = Cmp & PromotedRange::InRangeFlag;
11394   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11395     return false;
11396 
11397   // A comparison of an unsigned bit-field against 0 is really a type problem,
11398   // even though at the type level the bit-field might promote to 'signed int'.
11399   if (Other->refersToBitField() && InRange && Value == 0 &&
11400       Other->getType()->isUnsignedIntegerOrEnumerationType())
11401     TautologicalTypeCompare = true;
11402 
11403   // If this is a comparison to an enum constant, include that
11404   // constant in the diagnostic.
11405   const EnumConstantDecl *ED = nullptr;
11406   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11407     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11408 
11409   // Should be enough for uint128 (39 decimal digits)
11410   SmallString<64> PrettySourceValue;
11411   llvm::raw_svector_ostream OS(PrettySourceValue);
11412   if (ED) {
11413     OS << '\'' << *ED << "' (" << Value << ")";
11414   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11415                Constant->IgnoreParenImpCasts())) {
11416     OS << (BL->getValue() ? "YES" : "NO");
11417   } else {
11418     OS << Value;
11419   }
11420 
11421   if (!TautologicalTypeCompare) {
11422     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11423         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11424         << E->getOpcodeStr() << OS.str() << *Result
11425         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11426     return true;
11427   }
11428 
11429   if (IsObjCSignedCharBool) {
11430     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11431                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11432                               << OS.str() << *Result);
11433     return true;
11434   }
11435 
11436   // FIXME: We use a somewhat different formatting for the in-range cases and
11437   // cases involving boolean values for historical reasons. We should pick a
11438   // consistent way of presenting these diagnostics.
11439   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11440 
11441     S.DiagRuntimeBehavior(
11442         E->getOperatorLoc(), E,
11443         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11444                          : diag::warn_tautological_bool_compare)
11445             << OS.str() << classifyConstantValue(Constant) << OtherT
11446             << OtherIsBooleanDespiteType << *Result
11447             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11448   } else {
11449     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11450     unsigned Diag =
11451         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11452             ? (HasEnumType(OriginalOther)
11453                    ? diag::warn_unsigned_enum_always_true_comparison
11454                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11455                               : diag::warn_unsigned_always_true_comparison)
11456             : diag::warn_tautological_constant_compare;
11457 
11458     S.Diag(E->getOperatorLoc(), Diag)
11459         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11460         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11461   }
11462 
11463   return true;
11464 }
11465 
11466 /// Analyze the operands of the given comparison.  Implements the
11467 /// fallback case from AnalyzeComparison.
11468 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11469   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11470   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11471 }
11472 
11473 /// Implements -Wsign-compare.
11474 ///
11475 /// \param E the binary operator to check for warnings
11476 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11477   // The type the comparison is being performed in.
11478   QualType T = E->getLHS()->getType();
11479 
11480   // Only analyze comparison operators where both sides have been converted to
11481   // the same type.
11482   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11483     return AnalyzeImpConvsInComparison(S, E);
11484 
11485   // Don't analyze value-dependent comparisons directly.
11486   if (E->isValueDependent())
11487     return AnalyzeImpConvsInComparison(S, E);
11488 
11489   Expr *LHS = E->getLHS();
11490   Expr *RHS = E->getRHS();
11491 
11492   if (T->isIntegralType(S.Context)) {
11493     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11494     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11495 
11496     // We don't care about expressions whose result is a constant.
11497     if (RHSValue && LHSValue)
11498       return AnalyzeImpConvsInComparison(S, E);
11499 
11500     // We only care about expressions where just one side is literal
11501     if ((bool)RHSValue ^ (bool)LHSValue) {
11502       // Is the constant on the RHS or LHS?
11503       const bool RhsConstant = (bool)RHSValue;
11504       Expr *Const = RhsConstant ? RHS : LHS;
11505       Expr *Other = RhsConstant ? LHS : RHS;
11506       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11507 
11508       // Check whether an integer constant comparison results in a value
11509       // of 'true' or 'false'.
11510       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11511         return AnalyzeImpConvsInComparison(S, E);
11512     }
11513   }
11514 
11515   if (!T->hasUnsignedIntegerRepresentation()) {
11516     // We don't do anything special if this isn't an unsigned integral
11517     // comparison:  we're only interested in integral comparisons, and
11518     // signed comparisons only happen in cases we don't care to warn about.
11519     return AnalyzeImpConvsInComparison(S, E);
11520   }
11521 
11522   LHS = LHS->IgnoreParenImpCasts();
11523   RHS = RHS->IgnoreParenImpCasts();
11524 
11525   if (!S.getLangOpts().CPlusPlus) {
11526     // Avoid warning about comparison of integers with different signs when
11527     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11528     // the type of `E`.
11529     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11530       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11531     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11532       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11533   }
11534 
11535   // Check to see if one of the (unmodified) operands is of different
11536   // signedness.
11537   Expr *signedOperand, *unsignedOperand;
11538   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11539     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11540            "unsigned comparison between two signed integer expressions?");
11541     signedOperand = LHS;
11542     unsignedOperand = RHS;
11543   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11544     signedOperand = RHS;
11545     unsignedOperand = LHS;
11546   } else {
11547     return AnalyzeImpConvsInComparison(S, E);
11548   }
11549 
11550   // Otherwise, calculate the effective range of the signed operand.
11551   IntRange signedRange = GetExprRange(
11552       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11553 
11554   // Go ahead and analyze implicit conversions in the operands.  Note
11555   // that we skip the implicit conversions on both sides.
11556   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11557   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11558 
11559   // If the signed range is non-negative, -Wsign-compare won't fire.
11560   if (signedRange.NonNegative)
11561     return;
11562 
11563   // For (in)equality comparisons, if the unsigned operand is a
11564   // constant which cannot collide with a overflowed signed operand,
11565   // then reinterpreting the signed operand as unsigned will not
11566   // change the result of the comparison.
11567   if (E->isEqualityOp()) {
11568     unsigned comparisonWidth = S.Context.getIntWidth(T);
11569     IntRange unsignedRange =
11570         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11571                      /*Approximate*/ true);
11572 
11573     // We should never be unable to prove that the unsigned operand is
11574     // non-negative.
11575     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11576 
11577     if (unsignedRange.Width < comparisonWidth)
11578       return;
11579   }
11580 
11581   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11582                         S.PDiag(diag::warn_mixed_sign_comparison)
11583                             << LHS->getType() << RHS->getType()
11584                             << LHS->getSourceRange() << RHS->getSourceRange());
11585 }
11586 
11587 /// Analyzes an attempt to assign the given value to a bitfield.
11588 ///
11589 /// Returns true if there was something fishy about the attempt.
11590 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11591                                       SourceLocation InitLoc) {
11592   assert(Bitfield->isBitField());
11593   if (Bitfield->isInvalidDecl())
11594     return false;
11595 
11596   // White-list bool bitfields.
11597   QualType BitfieldType = Bitfield->getType();
11598   if (BitfieldType->isBooleanType())
11599      return false;
11600 
11601   if (BitfieldType->isEnumeralType()) {
11602     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11603     // If the underlying enum type was not explicitly specified as an unsigned
11604     // type and the enum contain only positive values, MSVC++ will cause an
11605     // inconsistency by storing this as a signed type.
11606     if (S.getLangOpts().CPlusPlus11 &&
11607         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11608         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11609         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11610       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11611           << BitfieldEnumDecl;
11612     }
11613   }
11614 
11615   if (Bitfield->getType()->isBooleanType())
11616     return false;
11617 
11618   // Ignore value- or type-dependent expressions.
11619   if (Bitfield->getBitWidth()->isValueDependent() ||
11620       Bitfield->getBitWidth()->isTypeDependent() ||
11621       Init->isValueDependent() ||
11622       Init->isTypeDependent())
11623     return false;
11624 
11625   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11626   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11627 
11628   Expr::EvalResult Result;
11629   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11630                                    Expr::SE_AllowSideEffects)) {
11631     // The RHS is not constant.  If the RHS has an enum type, make sure the
11632     // bitfield is wide enough to hold all the values of the enum without
11633     // truncation.
11634     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11635       EnumDecl *ED = EnumTy->getDecl();
11636       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11637 
11638       // Enum types are implicitly signed on Windows, so check if there are any
11639       // negative enumerators to see if the enum was intended to be signed or
11640       // not.
11641       bool SignedEnum = ED->getNumNegativeBits() > 0;
11642 
11643       // Check for surprising sign changes when assigning enum values to a
11644       // bitfield of different signedness.  If the bitfield is signed and we
11645       // have exactly the right number of bits to store this unsigned enum,
11646       // suggest changing the enum to an unsigned type. This typically happens
11647       // on Windows where unfixed enums always use an underlying type of 'int'.
11648       unsigned DiagID = 0;
11649       if (SignedEnum && !SignedBitfield) {
11650         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11651       } else if (SignedBitfield && !SignedEnum &&
11652                  ED->getNumPositiveBits() == FieldWidth) {
11653         DiagID = diag::warn_signed_bitfield_enum_conversion;
11654       }
11655 
11656       if (DiagID) {
11657         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11658         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11659         SourceRange TypeRange =
11660             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11661         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11662             << SignedEnum << TypeRange;
11663       }
11664 
11665       // Compute the required bitwidth. If the enum has negative values, we need
11666       // one more bit than the normal number of positive bits to represent the
11667       // sign bit.
11668       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11669                                                   ED->getNumNegativeBits())
11670                                        : ED->getNumPositiveBits();
11671 
11672       // Check the bitwidth.
11673       if (BitsNeeded > FieldWidth) {
11674         Expr *WidthExpr = Bitfield->getBitWidth();
11675         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11676             << Bitfield << ED;
11677         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11678             << BitsNeeded << ED << WidthExpr->getSourceRange();
11679       }
11680     }
11681 
11682     return false;
11683   }
11684 
11685   llvm::APSInt Value = Result.Val.getInt();
11686 
11687   unsigned OriginalWidth = Value.getBitWidth();
11688 
11689   if (!Value.isSigned() || Value.isNegative())
11690     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11691       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11692         OriginalWidth = Value.getMinSignedBits();
11693 
11694   if (OriginalWidth <= FieldWidth)
11695     return false;
11696 
11697   // Compute the value which the bitfield will contain.
11698   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11699   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11700 
11701   // Check whether the stored value is equal to the original value.
11702   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11703   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11704     return false;
11705 
11706   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11707   // therefore don't strictly fit into a signed bitfield of width 1.
11708   if (FieldWidth == 1 && Value == 1)
11709     return false;
11710 
11711   std::string PrettyValue = Value.toString(10);
11712   std::string PrettyTrunc = TruncatedValue.toString(10);
11713 
11714   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11715     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11716     << Init->getSourceRange();
11717 
11718   return true;
11719 }
11720 
11721 /// Analyze the given simple or compound assignment for warning-worthy
11722 /// operations.
11723 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11724   // Just recurse on the LHS.
11725   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11726 
11727   // We want to recurse on the RHS as normal unless we're assigning to
11728   // a bitfield.
11729   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11730     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11731                                   E->getOperatorLoc())) {
11732       // Recurse, ignoring any implicit conversions on the RHS.
11733       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11734                                         E->getOperatorLoc());
11735     }
11736   }
11737 
11738   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11739 
11740   // Diagnose implicitly sequentially-consistent atomic assignment.
11741   if (E->getLHS()->getType()->isAtomicType())
11742     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11743 }
11744 
11745 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11746 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11747                             SourceLocation CContext, unsigned diag,
11748                             bool pruneControlFlow = false) {
11749   if (pruneControlFlow) {
11750     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11751                           S.PDiag(diag)
11752                               << SourceType << T << E->getSourceRange()
11753                               << SourceRange(CContext));
11754     return;
11755   }
11756   S.Diag(E->getExprLoc(), diag)
11757     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11758 }
11759 
11760 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11761 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11762                             SourceLocation CContext,
11763                             unsigned diag, bool pruneControlFlow = false) {
11764   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11765 }
11766 
11767 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11768   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11769       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11770 }
11771 
11772 static void adornObjCBoolConversionDiagWithTernaryFixit(
11773     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11774   Expr *Ignored = SourceExpr->IgnoreImplicit();
11775   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11776     Ignored = OVE->getSourceExpr();
11777   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11778                      isa<BinaryOperator>(Ignored) ||
11779                      isa<CXXOperatorCallExpr>(Ignored);
11780   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11781   if (NeedsParens)
11782     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11783             << FixItHint::CreateInsertion(EndLoc, ")");
11784   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11785 }
11786 
11787 /// Diagnose an implicit cast from a floating point value to an integer value.
11788 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11789                                     SourceLocation CContext) {
11790   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11791   const bool PruneWarnings = S.inTemplateInstantiation();
11792 
11793   Expr *InnerE = E->IgnoreParenImpCasts();
11794   // We also want to warn on, e.g., "int i = -1.234"
11795   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11796     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11797       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11798 
11799   const bool IsLiteral =
11800       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11801 
11802   llvm::APFloat Value(0.0);
11803   bool IsConstant =
11804     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11805   if (!IsConstant) {
11806     if (isObjCSignedCharBool(S, T)) {
11807       return adornObjCBoolConversionDiagWithTernaryFixit(
11808           S, E,
11809           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11810               << E->getType());
11811     }
11812 
11813     return DiagnoseImpCast(S, E, T, CContext,
11814                            diag::warn_impcast_float_integer, PruneWarnings);
11815   }
11816 
11817   bool isExact = false;
11818 
11819   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11820                             T->hasUnsignedIntegerRepresentation());
11821   llvm::APFloat::opStatus Result = Value.convertToInteger(
11822       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11823 
11824   // FIXME: Force the precision of the source value down so we don't print
11825   // digits which are usually useless (we don't really care here if we
11826   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11827   // would automatically print the shortest representation, but it's a bit
11828   // tricky to implement.
11829   SmallString<16> PrettySourceValue;
11830   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11831   precision = (precision * 59 + 195) / 196;
11832   Value.toString(PrettySourceValue, precision);
11833 
11834   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11835     return adornObjCBoolConversionDiagWithTernaryFixit(
11836         S, E,
11837         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11838             << PrettySourceValue);
11839   }
11840 
11841   if (Result == llvm::APFloat::opOK && isExact) {
11842     if (IsLiteral) return;
11843     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11844                            PruneWarnings);
11845   }
11846 
11847   // Conversion of a floating-point value to a non-bool integer where the
11848   // integral part cannot be represented by the integer type is undefined.
11849   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11850     return DiagnoseImpCast(
11851         S, E, T, CContext,
11852         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11853                   : diag::warn_impcast_float_to_integer_out_of_range,
11854         PruneWarnings);
11855 
11856   unsigned DiagID = 0;
11857   if (IsLiteral) {
11858     // Warn on floating point literal to integer.
11859     DiagID = diag::warn_impcast_literal_float_to_integer;
11860   } else if (IntegerValue == 0) {
11861     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11862       return DiagnoseImpCast(S, E, T, CContext,
11863                              diag::warn_impcast_float_integer, PruneWarnings);
11864     }
11865     // Warn on non-zero to zero conversion.
11866     DiagID = diag::warn_impcast_float_to_integer_zero;
11867   } else {
11868     if (IntegerValue.isUnsigned()) {
11869       if (!IntegerValue.isMaxValue()) {
11870         return DiagnoseImpCast(S, E, T, CContext,
11871                                diag::warn_impcast_float_integer, PruneWarnings);
11872       }
11873     } else {  // IntegerValue.isSigned()
11874       if (!IntegerValue.isMaxSignedValue() &&
11875           !IntegerValue.isMinSignedValue()) {
11876         return DiagnoseImpCast(S, E, T, CContext,
11877                                diag::warn_impcast_float_integer, PruneWarnings);
11878       }
11879     }
11880     // Warn on evaluatable floating point expression to integer conversion.
11881     DiagID = diag::warn_impcast_float_to_integer;
11882   }
11883 
11884   SmallString<16> PrettyTargetValue;
11885   if (IsBool)
11886     PrettyTargetValue = Value.isZero() ? "false" : "true";
11887   else
11888     IntegerValue.toString(PrettyTargetValue);
11889 
11890   if (PruneWarnings) {
11891     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11892                           S.PDiag(DiagID)
11893                               << E->getType() << T.getUnqualifiedType()
11894                               << PrettySourceValue << PrettyTargetValue
11895                               << E->getSourceRange() << SourceRange(CContext));
11896   } else {
11897     S.Diag(E->getExprLoc(), DiagID)
11898         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11899         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11900   }
11901 }
11902 
11903 /// Analyze the given compound assignment for the possible losing of
11904 /// floating-point precision.
11905 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11906   assert(isa<CompoundAssignOperator>(E) &&
11907          "Must be compound assignment operation");
11908   // Recurse on the LHS and RHS in here
11909   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11910   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11911 
11912   if (E->getLHS()->getType()->isAtomicType())
11913     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11914 
11915   // Now check the outermost expression
11916   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11917   const auto *RBT = cast<CompoundAssignOperator>(E)
11918                         ->getComputationResultType()
11919                         ->getAs<BuiltinType>();
11920 
11921   // The below checks assume source is floating point.
11922   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11923 
11924   // If source is floating point but target is an integer.
11925   if (ResultBT->isInteger())
11926     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11927                            E->getExprLoc(), diag::warn_impcast_float_integer);
11928 
11929   if (!ResultBT->isFloatingPoint())
11930     return;
11931 
11932   // If both source and target are floating points, warn about losing precision.
11933   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11934       QualType(ResultBT, 0), QualType(RBT, 0));
11935   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11936     // warn about dropping FP rank.
11937     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11938                     diag::warn_impcast_float_result_precision);
11939 }
11940 
11941 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11942                                       IntRange Range) {
11943   if (!Range.Width) return "0";
11944 
11945   llvm::APSInt ValueInRange = Value;
11946   ValueInRange.setIsSigned(!Range.NonNegative);
11947   ValueInRange = ValueInRange.trunc(Range.Width);
11948   return ValueInRange.toString(10);
11949 }
11950 
11951 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11952   if (!isa<ImplicitCastExpr>(Ex))
11953     return false;
11954 
11955   Expr *InnerE = Ex->IgnoreParenImpCasts();
11956   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11957   const Type *Source =
11958     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11959   if (Target->isDependentType())
11960     return false;
11961 
11962   const BuiltinType *FloatCandidateBT =
11963     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11964   const Type *BoolCandidateType = ToBool ? Target : Source;
11965 
11966   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11967           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11968 }
11969 
11970 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11971                                              SourceLocation CC) {
11972   unsigned NumArgs = TheCall->getNumArgs();
11973   for (unsigned i = 0; i < NumArgs; ++i) {
11974     Expr *CurrA = TheCall->getArg(i);
11975     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11976       continue;
11977 
11978     bool IsSwapped = ((i > 0) &&
11979         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11980     IsSwapped |= ((i < (NumArgs - 1)) &&
11981         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11982     if (IsSwapped) {
11983       // Warn on this floating-point to bool conversion.
11984       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11985                       CurrA->getType(), CC,
11986                       diag::warn_impcast_floating_point_to_bool);
11987     }
11988   }
11989 }
11990 
11991 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11992                                    SourceLocation CC) {
11993   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11994                         E->getExprLoc()))
11995     return;
11996 
11997   // Don't warn on functions which have return type nullptr_t.
11998   if (isa<CallExpr>(E))
11999     return;
12000 
12001   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12002   const Expr::NullPointerConstantKind NullKind =
12003       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12004   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12005     return;
12006 
12007   // Return if target type is a safe conversion.
12008   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12009       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12010     return;
12011 
12012   SourceLocation Loc = E->getSourceRange().getBegin();
12013 
12014   // Venture through the macro stacks to get to the source of macro arguments.
12015   // The new location is a better location than the complete location that was
12016   // passed in.
12017   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12018   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12019 
12020   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12021   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12022     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12023         Loc, S.SourceMgr, S.getLangOpts());
12024     if (MacroName == "NULL")
12025       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12026   }
12027 
12028   // Only warn if the null and context location are in the same macro expansion.
12029   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12030     return;
12031 
12032   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12033       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12034       << FixItHint::CreateReplacement(Loc,
12035                                       S.getFixItZeroLiteralForType(T, Loc));
12036 }
12037 
12038 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12039                                   ObjCArrayLiteral *ArrayLiteral);
12040 
12041 static void
12042 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12043                            ObjCDictionaryLiteral *DictionaryLiteral);
12044 
12045 /// Check a single element within a collection literal against the
12046 /// target element type.
12047 static void checkObjCCollectionLiteralElement(Sema &S,
12048                                               QualType TargetElementType,
12049                                               Expr *Element,
12050                                               unsigned ElementKind) {
12051   // Skip a bitcast to 'id' or qualified 'id'.
12052   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12053     if (ICE->getCastKind() == CK_BitCast &&
12054         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12055       Element = ICE->getSubExpr();
12056   }
12057 
12058   QualType ElementType = Element->getType();
12059   ExprResult ElementResult(Element);
12060   if (ElementType->getAs<ObjCObjectPointerType>() &&
12061       S.CheckSingleAssignmentConstraints(TargetElementType,
12062                                          ElementResult,
12063                                          false, false)
12064         != Sema::Compatible) {
12065     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12066         << ElementType << ElementKind << TargetElementType
12067         << Element->getSourceRange();
12068   }
12069 
12070   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12071     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12072   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12073     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12074 }
12075 
12076 /// Check an Objective-C array literal being converted to the given
12077 /// target type.
12078 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12079                                   ObjCArrayLiteral *ArrayLiteral) {
12080   if (!S.NSArrayDecl)
12081     return;
12082 
12083   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12084   if (!TargetObjCPtr)
12085     return;
12086 
12087   if (TargetObjCPtr->isUnspecialized() ||
12088       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12089         != S.NSArrayDecl->getCanonicalDecl())
12090     return;
12091 
12092   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12093   if (TypeArgs.size() != 1)
12094     return;
12095 
12096   QualType TargetElementType = TypeArgs[0];
12097   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12098     checkObjCCollectionLiteralElement(S, TargetElementType,
12099                                       ArrayLiteral->getElement(I),
12100                                       0);
12101   }
12102 }
12103 
12104 /// Check an Objective-C dictionary literal being converted to the given
12105 /// target type.
12106 static void
12107 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12108                            ObjCDictionaryLiteral *DictionaryLiteral) {
12109   if (!S.NSDictionaryDecl)
12110     return;
12111 
12112   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12113   if (!TargetObjCPtr)
12114     return;
12115 
12116   if (TargetObjCPtr->isUnspecialized() ||
12117       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12118         != S.NSDictionaryDecl->getCanonicalDecl())
12119     return;
12120 
12121   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12122   if (TypeArgs.size() != 2)
12123     return;
12124 
12125   QualType TargetKeyType = TypeArgs[0];
12126   QualType TargetObjectType = TypeArgs[1];
12127   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12128     auto Element = DictionaryLiteral->getKeyValueElement(I);
12129     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12130     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12131   }
12132 }
12133 
12134 // Helper function to filter out cases for constant width constant conversion.
12135 // Don't warn on char array initialization or for non-decimal values.
12136 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12137                                           SourceLocation CC) {
12138   // If initializing from a constant, and the constant starts with '0',
12139   // then it is a binary, octal, or hexadecimal.  Allow these constants
12140   // to fill all the bits, even if there is a sign change.
12141   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12142     const char FirstLiteralCharacter =
12143         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12144     if (FirstLiteralCharacter == '0')
12145       return false;
12146   }
12147 
12148   // If the CC location points to a '{', and the type is char, then assume
12149   // assume it is an array initialization.
12150   if (CC.isValid() && T->isCharType()) {
12151     const char FirstContextCharacter =
12152         S.getSourceManager().getCharacterData(CC)[0];
12153     if (FirstContextCharacter == '{')
12154       return false;
12155   }
12156 
12157   return true;
12158 }
12159 
12160 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12161   const auto *IL = dyn_cast<IntegerLiteral>(E);
12162   if (!IL) {
12163     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12164       if (UO->getOpcode() == UO_Minus)
12165         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12166     }
12167   }
12168 
12169   return IL;
12170 }
12171 
12172 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12173   E = E->IgnoreParenImpCasts();
12174   SourceLocation ExprLoc = E->getExprLoc();
12175 
12176   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12177     BinaryOperator::Opcode Opc = BO->getOpcode();
12178     Expr::EvalResult Result;
12179     // Do not diagnose unsigned shifts.
12180     if (Opc == BO_Shl) {
12181       const auto *LHS = getIntegerLiteral(BO->getLHS());
12182       const auto *RHS = getIntegerLiteral(BO->getRHS());
12183       if (LHS && LHS->getValue() == 0)
12184         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12185       else if (!E->isValueDependent() && LHS && RHS &&
12186                RHS->getValue().isNonNegative() &&
12187                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12188         S.Diag(ExprLoc, diag::warn_left_shift_always)
12189             << (Result.Val.getInt() != 0);
12190       else if (E->getType()->isSignedIntegerType())
12191         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12192     }
12193   }
12194 
12195   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12196     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12197     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12198     if (!LHS || !RHS)
12199       return;
12200     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12201         (RHS->getValue() == 0 || RHS->getValue() == 1))
12202       // Do not diagnose common idioms.
12203       return;
12204     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12205       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12206   }
12207 }
12208 
12209 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12210                                     SourceLocation CC,
12211                                     bool *ICContext = nullptr,
12212                                     bool IsListInit = false) {
12213   if (E->isTypeDependent() || E->isValueDependent()) return;
12214 
12215   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12216   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12217   if (Source == Target) return;
12218   if (Target->isDependentType()) return;
12219 
12220   // If the conversion context location is invalid don't complain. We also
12221   // don't want to emit a warning if the issue occurs from the expansion of
12222   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12223   // delay this check as long as possible. Once we detect we are in that
12224   // scenario, we just return.
12225   if (CC.isInvalid())
12226     return;
12227 
12228   if (Source->isAtomicType())
12229     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12230 
12231   // Diagnose implicit casts to bool.
12232   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12233     if (isa<StringLiteral>(E))
12234       // Warn on string literal to bool.  Checks for string literals in logical
12235       // and expressions, for instance, assert(0 && "error here"), are
12236       // prevented by a check in AnalyzeImplicitConversions().
12237       return DiagnoseImpCast(S, E, T, CC,
12238                              diag::warn_impcast_string_literal_to_bool);
12239     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12240         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12241       // This covers the literal expressions that evaluate to Objective-C
12242       // objects.
12243       return DiagnoseImpCast(S, E, T, CC,
12244                              diag::warn_impcast_objective_c_literal_to_bool);
12245     }
12246     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12247       // Warn on pointer to bool conversion that is always true.
12248       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12249                                      SourceRange(CC));
12250     }
12251   }
12252 
12253   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12254   // is a typedef for signed char (macOS), then that constant value has to be 1
12255   // or 0.
12256   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12257     Expr::EvalResult Result;
12258     if (E->EvaluateAsInt(Result, S.getASTContext(),
12259                          Expr::SE_AllowSideEffects)) {
12260       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12261         adornObjCBoolConversionDiagWithTernaryFixit(
12262             S, E,
12263             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12264                 << Result.Val.getInt().toString(10));
12265       }
12266       return;
12267     }
12268   }
12269 
12270   // Check implicit casts from Objective-C collection literals to specialized
12271   // collection types, e.g., NSArray<NSString *> *.
12272   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12273     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12274   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12275     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12276 
12277   // Strip vector types.
12278   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12279     if (Target->isVLSTBuiltinType()) {
12280       auto SourceVectorKind = SourceVT->getVectorKind();
12281       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12282           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12283           (SourceVectorKind == VectorType::GenericVector &&
12284            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12285         return;
12286     }
12287 
12288     if (!isa<VectorType>(Target)) {
12289       if (S.SourceMgr.isInSystemMacro(CC))
12290         return;
12291       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12292     }
12293 
12294     // If the vector cast is cast between two vectors of the same size, it is
12295     // a bitcast, not a conversion.
12296     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12297       return;
12298 
12299     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12300     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12301   }
12302   if (auto VecTy = dyn_cast<VectorType>(Target))
12303     Target = VecTy->getElementType().getTypePtr();
12304 
12305   // Strip complex types.
12306   if (isa<ComplexType>(Source)) {
12307     if (!isa<ComplexType>(Target)) {
12308       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12309         return;
12310 
12311       return DiagnoseImpCast(S, E, T, CC,
12312                              S.getLangOpts().CPlusPlus
12313                                  ? diag::err_impcast_complex_scalar
12314                                  : diag::warn_impcast_complex_scalar);
12315     }
12316 
12317     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12318     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12319   }
12320 
12321   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12322   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12323 
12324   // If the source is floating point...
12325   if (SourceBT && SourceBT->isFloatingPoint()) {
12326     // ...and the target is floating point...
12327     if (TargetBT && TargetBT->isFloatingPoint()) {
12328       // ...then warn if we're dropping FP rank.
12329 
12330       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12331           QualType(SourceBT, 0), QualType(TargetBT, 0));
12332       if (Order > 0) {
12333         // Don't warn about float constants that are precisely
12334         // representable in the target type.
12335         Expr::EvalResult result;
12336         if (E->EvaluateAsRValue(result, S.Context)) {
12337           // Value might be a float, a float vector, or a float complex.
12338           if (IsSameFloatAfterCast(result.Val,
12339                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12340                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12341             return;
12342         }
12343 
12344         if (S.SourceMgr.isInSystemMacro(CC))
12345           return;
12346 
12347         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12348       }
12349       // ... or possibly if we're increasing rank, too
12350       else if (Order < 0) {
12351         if (S.SourceMgr.isInSystemMacro(CC))
12352           return;
12353 
12354         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12355       }
12356       return;
12357     }
12358 
12359     // If the target is integral, always warn.
12360     if (TargetBT && TargetBT->isInteger()) {
12361       if (S.SourceMgr.isInSystemMacro(CC))
12362         return;
12363 
12364       DiagnoseFloatingImpCast(S, E, T, CC);
12365     }
12366 
12367     // Detect the case where a call result is converted from floating-point to
12368     // to bool, and the final argument to the call is converted from bool, to
12369     // discover this typo:
12370     //
12371     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12372     //
12373     // FIXME: This is an incredibly special case; is there some more general
12374     // way to detect this class of misplaced-parentheses bug?
12375     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12376       // Check last argument of function call to see if it is an
12377       // implicit cast from a type matching the type the result
12378       // is being cast to.
12379       CallExpr *CEx = cast<CallExpr>(E);
12380       if (unsigned NumArgs = CEx->getNumArgs()) {
12381         Expr *LastA = CEx->getArg(NumArgs - 1);
12382         Expr *InnerE = LastA->IgnoreParenImpCasts();
12383         if (isa<ImplicitCastExpr>(LastA) &&
12384             InnerE->getType()->isBooleanType()) {
12385           // Warn on this floating-point to bool conversion
12386           DiagnoseImpCast(S, E, T, CC,
12387                           diag::warn_impcast_floating_point_to_bool);
12388         }
12389       }
12390     }
12391     return;
12392   }
12393 
12394   // Valid casts involving fixed point types should be accounted for here.
12395   if (Source->isFixedPointType()) {
12396     if (Target->isUnsaturatedFixedPointType()) {
12397       Expr::EvalResult Result;
12398       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12399                                   S.isConstantEvaluated())) {
12400         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12401         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12402         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12403         if (Value > MaxVal || Value < MinVal) {
12404           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12405                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12406                                     << Value.toString() << T
12407                                     << E->getSourceRange()
12408                                     << clang::SourceRange(CC));
12409           return;
12410         }
12411       }
12412     } else if (Target->isIntegerType()) {
12413       Expr::EvalResult Result;
12414       if (!S.isConstantEvaluated() &&
12415           E->EvaluateAsFixedPoint(Result, S.Context,
12416                                   Expr::SE_AllowSideEffects)) {
12417         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12418 
12419         bool Overflowed;
12420         llvm::APSInt IntResult = FXResult.convertToInt(
12421             S.Context.getIntWidth(T),
12422             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12423 
12424         if (Overflowed) {
12425           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12426                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12427                                     << FXResult.toString() << T
12428                                     << E->getSourceRange()
12429                                     << clang::SourceRange(CC));
12430           return;
12431         }
12432       }
12433     }
12434   } else if (Target->isUnsaturatedFixedPointType()) {
12435     if (Source->isIntegerType()) {
12436       Expr::EvalResult Result;
12437       if (!S.isConstantEvaluated() &&
12438           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12439         llvm::APSInt Value = Result.Val.getInt();
12440 
12441         bool Overflowed;
12442         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12443             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12444 
12445         if (Overflowed) {
12446           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12447                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12448                                     << Value.toString(/*Radix=*/10) << T
12449                                     << E->getSourceRange()
12450                                     << clang::SourceRange(CC));
12451           return;
12452         }
12453       }
12454     }
12455   }
12456 
12457   // If we are casting an integer type to a floating point type without
12458   // initialization-list syntax, we might lose accuracy if the floating
12459   // point type has a narrower significand than the integer type.
12460   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12461       TargetBT->isFloatingType() && !IsListInit) {
12462     // Determine the number of precision bits in the source integer type.
12463     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12464                                         /*Approximate*/ true);
12465     unsigned int SourcePrecision = SourceRange.Width;
12466 
12467     // Determine the number of precision bits in the
12468     // target floating point type.
12469     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12470         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12471 
12472     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12473         SourcePrecision > TargetPrecision) {
12474 
12475       if (Optional<llvm::APSInt> SourceInt =
12476               E->getIntegerConstantExpr(S.Context)) {
12477         // If the source integer is a constant, convert it to the target
12478         // floating point type. Issue a warning if the value changes
12479         // during the whole conversion.
12480         llvm::APFloat TargetFloatValue(
12481             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12482         llvm::APFloat::opStatus ConversionStatus =
12483             TargetFloatValue.convertFromAPInt(
12484                 *SourceInt, SourceBT->isSignedInteger(),
12485                 llvm::APFloat::rmNearestTiesToEven);
12486 
12487         if (ConversionStatus != llvm::APFloat::opOK) {
12488           std::string PrettySourceValue = SourceInt->toString(10);
12489           SmallString<32> PrettyTargetValue;
12490           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12491 
12492           S.DiagRuntimeBehavior(
12493               E->getExprLoc(), E,
12494               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12495                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12496                   << E->getSourceRange() << clang::SourceRange(CC));
12497         }
12498       } else {
12499         // Otherwise, the implicit conversion may lose precision.
12500         DiagnoseImpCast(S, E, T, CC,
12501                         diag::warn_impcast_integer_float_precision);
12502       }
12503     }
12504   }
12505 
12506   DiagnoseNullConversion(S, E, T, CC);
12507 
12508   S.DiscardMisalignedMemberAddress(Target, E);
12509 
12510   if (Target->isBooleanType())
12511     DiagnoseIntInBoolContext(S, E);
12512 
12513   if (!Source->isIntegerType() || !Target->isIntegerType())
12514     return;
12515 
12516   // TODO: remove this early return once the false positives for constant->bool
12517   // in templates, macros, etc, are reduced or removed.
12518   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12519     return;
12520 
12521   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12522       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12523     return adornObjCBoolConversionDiagWithTernaryFixit(
12524         S, E,
12525         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12526             << E->getType());
12527   }
12528 
12529   IntRange SourceTypeRange =
12530       IntRange::forTargetOfCanonicalType(S.Context, Source);
12531   IntRange LikelySourceRange =
12532       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12533   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12534 
12535   if (LikelySourceRange.Width > TargetRange.Width) {
12536     // If the source is a constant, use a default-on diagnostic.
12537     // TODO: this should happen for bitfield stores, too.
12538     Expr::EvalResult Result;
12539     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12540                          S.isConstantEvaluated())) {
12541       llvm::APSInt Value(32);
12542       Value = Result.Val.getInt();
12543 
12544       if (S.SourceMgr.isInSystemMacro(CC))
12545         return;
12546 
12547       std::string PrettySourceValue = Value.toString(10);
12548       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12549 
12550       S.DiagRuntimeBehavior(
12551           E->getExprLoc(), E,
12552           S.PDiag(diag::warn_impcast_integer_precision_constant)
12553               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12554               << E->getSourceRange() << SourceRange(CC));
12555       return;
12556     }
12557 
12558     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12559     if (S.SourceMgr.isInSystemMacro(CC))
12560       return;
12561 
12562     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12563       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12564                              /* pruneControlFlow */ true);
12565     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12566   }
12567 
12568   if (TargetRange.Width > SourceTypeRange.Width) {
12569     if (auto *UO = dyn_cast<UnaryOperator>(E))
12570       if (UO->getOpcode() == UO_Minus)
12571         if (Source->isUnsignedIntegerType()) {
12572           if (Target->isUnsignedIntegerType())
12573             return DiagnoseImpCast(S, E, T, CC,
12574                                    diag::warn_impcast_high_order_zero_bits);
12575           if (Target->isSignedIntegerType())
12576             return DiagnoseImpCast(S, E, T, CC,
12577                                    diag::warn_impcast_nonnegative_result);
12578         }
12579   }
12580 
12581   if (TargetRange.Width == LikelySourceRange.Width &&
12582       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12583       Source->isSignedIntegerType()) {
12584     // Warn when doing a signed to signed conversion, warn if the positive
12585     // source value is exactly the width of the target type, which will
12586     // cause a negative value to be stored.
12587 
12588     Expr::EvalResult Result;
12589     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12590         !S.SourceMgr.isInSystemMacro(CC)) {
12591       llvm::APSInt Value = Result.Val.getInt();
12592       if (isSameWidthConstantConversion(S, E, T, CC)) {
12593         std::string PrettySourceValue = Value.toString(10);
12594         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12595 
12596         S.DiagRuntimeBehavior(
12597             E->getExprLoc(), E,
12598             S.PDiag(diag::warn_impcast_integer_precision_constant)
12599                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12600                 << E->getSourceRange() << SourceRange(CC));
12601         return;
12602       }
12603     }
12604 
12605     // Fall through for non-constants to give a sign conversion warning.
12606   }
12607 
12608   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12609       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12610        LikelySourceRange.Width == TargetRange.Width)) {
12611     if (S.SourceMgr.isInSystemMacro(CC))
12612       return;
12613 
12614     unsigned DiagID = diag::warn_impcast_integer_sign;
12615 
12616     // Traditionally, gcc has warned about this under -Wsign-compare.
12617     // We also want to warn about it in -Wconversion.
12618     // So if -Wconversion is off, use a completely identical diagnostic
12619     // in the sign-compare group.
12620     // The conditional-checking code will
12621     if (ICContext) {
12622       DiagID = diag::warn_impcast_integer_sign_conditional;
12623       *ICContext = true;
12624     }
12625 
12626     return DiagnoseImpCast(S, E, T, CC, DiagID);
12627   }
12628 
12629   // Diagnose conversions between different enumeration types.
12630   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12631   // type, to give us better diagnostics.
12632   QualType SourceType = E->getType();
12633   if (!S.getLangOpts().CPlusPlus) {
12634     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12635       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12636         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12637         SourceType = S.Context.getTypeDeclType(Enum);
12638         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12639       }
12640   }
12641 
12642   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12643     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12644       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12645           TargetEnum->getDecl()->hasNameForLinkage() &&
12646           SourceEnum != TargetEnum) {
12647         if (S.SourceMgr.isInSystemMacro(CC))
12648           return;
12649 
12650         return DiagnoseImpCast(S, E, SourceType, T, CC,
12651                                diag::warn_impcast_different_enum_types);
12652       }
12653 }
12654 
12655 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12656                                      SourceLocation CC, QualType T);
12657 
12658 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12659                                     SourceLocation CC, bool &ICContext) {
12660   E = E->IgnoreParenImpCasts();
12661 
12662   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12663     return CheckConditionalOperator(S, CO, CC, T);
12664 
12665   AnalyzeImplicitConversions(S, E, CC);
12666   if (E->getType() != T)
12667     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12668 }
12669 
12670 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12671                                      SourceLocation CC, QualType T) {
12672   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12673 
12674   Expr *TrueExpr = E->getTrueExpr();
12675   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12676     TrueExpr = BCO->getCommon();
12677 
12678   bool Suspicious = false;
12679   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12680   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12681 
12682   if (T->isBooleanType())
12683     DiagnoseIntInBoolContext(S, E);
12684 
12685   // If -Wconversion would have warned about either of the candidates
12686   // for a signedness conversion to the context type...
12687   if (!Suspicious) return;
12688 
12689   // ...but it's currently ignored...
12690   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12691     return;
12692 
12693   // ...then check whether it would have warned about either of the
12694   // candidates for a signedness conversion to the condition type.
12695   if (E->getType() == T) return;
12696 
12697   Suspicious = false;
12698   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12699                           E->getType(), CC, &Suspicious);
12700   if (!Suspicious)
12701     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12702                             E->getType(), CC, &Suspicious);
12703 }
12704 
12705 /// Check conversion of given expression to boolean.
12706 /// Input argument E is a logical expression.
12707 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12708   if (S.getLangOpts().Bool)
12709     return;
12710   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12711     return;
12712   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12713 }
12714 
12715 namespace {
12716 struct AnalyzeImplicitConversionsWorkItem {
12717   Expr *E;
12718   SourceLocation CC;
12719   bool IsListInit;
12720 };
12721 }
12722 
12723 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12724 /// that should be visited are added to WorkList.
12725 static void AnalyzeImplicitConversions(
12726     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12727     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12728   Expr *OrigE = Item.E;
12729   SourceLocation CC = Item.CC;
12730 
12731   QualType T = OrigE->getType();
12732   Expr *E = OrigE->IgnoreParenImpCasts();
12733 
12734   // Propagate whether we are in a C++ list initialization expression.
12735   // If so, we do not issue warnings for implicit int-float conversion
12736   // precision loss, because C++11 narrowing already handles it.
12737   bool IsListInit = Item.IsListInit ||
12738                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12739 
12740   if (E->isTypeDependent() || E->isValueDependent())
12741     return;
12742 
12743   Expr *SourceExpr = E;
12744   // Examine, but don't traverse into the source expression of an
12745   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12746   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12747   // evaluate it in the context of checking the specific conversion to T though.
12748   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12749     if (auto *Src = OVE->getSourceExpr())
12750       SourceExpr = Src;
12751 
12752   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12753     if (UO->getOpcode() == UO_Not &&
12754         UO->getSubExpr()->isKnownToHaveBooleanValue())
12755       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12756           << OrigE->getSourceRange() << T->isBooleanType()
12757           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12758 
12759   // For conditional operators, we analyze the arguments as if they
12760   // were being fed directly into the output.
12761   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12762     CheckConditionalOperator(S, CO, CC, T);
12763     return;
12764   }
12765 
12766   // Check implicit argument conversions for function calls.
12767   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12768     CheckImplicitArgumentConversions(S, Call, CC);
12769 
12770   // Go ahead and check any implicit conversions we might have skipped.
12771   // The non-canonical typecheck is just an optimization;
12772   // CheckImplicitConversion will filter out dead implicit conversions.
12773   if (SourceExpr->getType() != T)
12774     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12775 
12776   // Now continue drilling into this expression.
12777 
12778   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12779     // The bound subexpressions in a PseudoObjectExpr are not reachable
12780     // as transitive children.
12781     // FIXME: Use a more uniform representation for this.
12782     for (auto *SE : POE->semantics())
12783       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12784         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12785   }
12786 
12787   // Skip past explicit casts.
12788   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12789     E = CE->getSubExpr()->IgnoreParenImpCasts();
12790     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12791       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12792     WorkList.push_back({E, CC, IsListInit});
12793     return;
12794   }
12795 
12796   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12797     // Do a somewhat different check with comparison operators.
12798     if (BO->isComparisonOp())
12799       return AnalyzeComparison(S, BO);
12800 
12801     // And with simple assignments.
12802     if (BO->getOpcode() == BO_Assign)
12803       return AnalyzeAssignment(S, BO);
12804     // And with compound assignments.
12805     if (BO->isAssignmentOp())
12806       return AnalyzeCompoundAssignment(S, BO);
12807   }
12808 
12809   // These break the otherwise-useful invariant below.  Fortunately,
12810   // we don't really need to recurse into them, because any internal
12811   // expressions should have been analyzed already when they were
12812   // built into statements.
12813   if (isa<StmtExpr>(E)) return;
12814 
12815   // Don't descend into unevaluated contexts.
12816   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12817 
12818   // Now just recurse over the expression's children.
12819   CC = E->getExprLoc();
12820   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12821   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12822   for (Stmt *SubStmt : E->children()) {
12823     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12824     if (!ChildExpr)
12825       continue;
12826 
12827     if (IsLogicalAndOperator &&
12828         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12829       // Ignore checking string literals that are in logical and operators.
12830       // This is a common pattern for asserts.
12831       continue;
12832     WorkList.push_back({ChildExpr, CC, IsListInit});
12833   }
12834 
12835   if (BO && BO->isLogicalOp()) {
12836     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12837     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12838       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12839 
12840     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12841     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12842       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12843   }
12844 
12845   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12846     if (U->getOpcode() == UO_LNot) {
12847       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12848     } else if (U->getOpcode() != UO_AddrOf) {
12849       if (U->getSubExpr()->getType()->isAtomicType())
12850         S.Diag(U->getSubExpr()->getBeginLoc(),
12851                diag::warn_atomic_implicit_seq_cst);
12852     }
12853   }
12854 }
12855 
12856 /// AnalyzeImplicitConversions - Find and report any interesting
12857 /// implicit conversions in the given expression.  There are a couple
12858 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12859 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12860                                        bool IsListInit/*= false*/) {
12861   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12862   WorkList.push_back({OrigE, CC, IsListInit});
12863   while (!WorkList.empty())
12864     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12865 }
12866 
12867 /// Diagnose integer type and any valid implicit conversion to it.
12868 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12869   // Taking into account implicit conversions,
12870   // allow any integer.
12871   if (!E->getType()->isIntegerType()) {
12872     S.Diag(E->getBeginLoc(),
12873            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12874     return true;
12875   }
12876   // Potentially emit standard warnings for implicit conversions if enabled
12877   // using -Wconversion.
12878   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12879   return false;
12880 }
12881 
12882 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12883 // Returns true when emitting a warning about taking the address of a reference.
12884 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12885                               const PartialDiagnostic &PD) {
12886   E = E->IgnoreParenImpCasts();
12887 
12888   const FunctionDecl *FD = nullptr;
12889 
12890   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12891     if (!DRE->getDecl()->getType()->isReferenceType())
12892       return false;
12893   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12894     if (!M->getMemberDecl()->getType()->isReferenceType())
12895       return false;
12896   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12897     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12898       return false;
12899     FD = Call->getDirectCallee();
12900   } else {
12901     return false;
12902   }
12903 
12904   SemaRef.Diag(E->getExprLoc(), PD);
12905 
12906   // If possible, point to location of function.
12907   if (FD) {
12908     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12909   }
12910 
12911   return true;
12912 }
12913 
12914 // Returns true if the SourceLocation is expanded from any macro body.
12915 // Returns false if the SourceLocation is invalid, is from not in a macro
12916 // expansion, or is from expanded from a top-level macro argument.
12917 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12918   if (Loc.isInvalid())
12919     return false;
12920 
12921   while (Loc.isMacroID()) {
12922     if (SM.isMacroBodyExpansion(Loc))
12923       return true;
12924     Loc = SM.getImmediateMacroCallerLoc(Loc);
12925   }
12926 
12927   return false;
12928 }
12929 
12930 /// Diagnose pointers that are always non-null.
12931 /// \param E the expression containing the pointer
12932 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12933 /// compared to a null pointer
12934 /// \param IsEqual True when the comparison is equal to a null pointer
12935 /// \param Range Extra SourceRange to highlight in the diagnostic
12936 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12937                                         Expr::NullPointerConstantKind NullKind,
12938                                         bool IsEqual, SourceRange Range) {
12939   if (!E)
12940     return;
12941 
12942   // Don't warn inside macros.
12943   if (E->getExprLoc().isMacroID()) {
12944     const SourceManager &SM = getSourceManager();
12945     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12946         IsInAnyMacroBody(SM, Range.getBegin()))
12947       return;
12948   }
12949   E = E->IgnoreImpCasts();
12950 
12951   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12952 
12953   if (isa<CXXThisExpr>(E)) {
12954     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12955                                 : diag::warn_this_bool_conversion;
12956     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12957     return;
12958   }
12959 
12960   bool IsAddressOf = false;
12961 
12962   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12963     if (UO->getOpcode() != UO_AddrOf)
12964       return;
12965     IsAddressOf = true;
12966     E = UO->getSubExpr();
12967   }
12968 
12969   if (IsAddressOf) {
12970     unsigned DiagID = IsCompare
12971                           ? diag::warn_address_of_reference_null_compare
12972                           : diag::warn_address_of_reference_bool_conversion;
12973     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12974                                          << IsEqual;
12975     if (CheckForReference(*this, E, PD)) {
12976       return;
12977     }
12978   }
12979 
12980   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12981     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12982     std::string Str;
12983     llvm::raw_string_ostream S(Str);
12984     E->printPretty(S, nullptr, getPrintingPolicy());
12985     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12986                                 : diag::warn_cast_nonnull_to_bool;
12987     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12988       << E->getSourceRange() << Range << IsEqual;
12989     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12990   };
12991 
12992   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12993   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12994     if (auto *Callee = Call->getDirectCallee()) {
12995       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12996         ComplainAboutNonnullParamOrCall(A);
12997         return;
12998       }
12999     }
13000   }
13001 
13002   // Expect to find a single Decl.  Skip anything more complicated.
13003   ValueDecl *D = nullptr;
13004   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13005     D = R->getDecl();
13006   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13007     D = M->getMemberDecl();
13008   }
13009 
13010   // Weak Decls can be null.
13011   if (!D || D->isWeak())
13012     return;
13013 
13014   // Check for parameter decl with nonnull attribute
13015   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13016     if (getCurFunction() &&
13017         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13018       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13019         ComplainAboutNonnullParamOrCall(A);
13020         return;
13021       }
13022 
13023       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13024         // Skip function template not specialized yet.
13025         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13026           return;
13027         auto ParamIter = llvm::find(FD->parameters(), PV);
13028         assert(ParamIter != FD->param_end());
13029         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13030 
13031         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13032           if (!NonNull->args_size()) {
13033               ComplainAboutNonnullParamOrCall(NonNull);
13034               return;
13035           }
13036 
13037           for (const ParamIdx &ArgNo : NonNull->args()) {
13038             if (ArgNo.getASTIndex() == ParamNo) {
13039               ComplainAboutNonnullParamOrCall(NonNull);
13040               return;
13041             }
13042           }
13043         }
13044       }
13045     }
13046   }
13047 
13048   QualType T = D->getType();
13049   const bool IsArray = T->isArrayType();
13050   const bool IsFunction = T->isFunctionType();
13051 
13052   // Address of function is used to silence the function warning.
13053   if (IsAddressOf && IsFunction) {
13054     return;
13055   }
13056 
13057   // Found nothing.
13058   if (!IsAddressOf && !IsFunction && !IsArray)
13059     return;
13060 
13061   // Pretty print the expression for the diagnostic.
13062   std::string Str;
13063   llvm::raw_string_ostream S(Str);
13064   E->printPretty(S, nullptr, getPrintingPolicy());
13065 
13066   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13067                               : diag::warn_impcast_pointer_to_bool;
13068   enum {
13069     AddressOf,
13070     FunctionPointer,
13071     ArrayPointer
13072   } DiagType;
13073   if (IsAddressOf)
13074     DiagType = AddressOf;
13075   else if (IsFunction)
13076     DiagType = FunctionPointer;
13077   else if (IsArray)
13078     DiagType = ArrayPointer;
13079   else
13080     llvm_unreachable("Could not determine diagnostic.");
13081   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13082                                 << Range << IsEqual;
13083 
13084   if (!IsFunction)
13085     return;
13086 
13087   // Suggest '&' to silence the function warning.
13088   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13089       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13090 
13091   // Check to see if '()' fixit should be emitted.
13092   QualType ReturnType;
13093   UnresolvedSet<4> NonTemplateOverloads;
13094   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13095   if (ReturnType.isNull())
13096     return;
13097 
13098   if (IsCompare) {
13099     // There are two cases here.  If there is null constant, the only suggest
13100     // for a pointer return type.  If the null is 0, then suggest if the return
13101     // type is a pointer or an integer type.
13102     if (!ReturnType->isPointerType()) {
13103       if (NullKind == Expr::NPCK_ZeroExpression ||
13104           NullKind == Expr::NPCK_ZeroLiteral) {
13105         if (!ReturnType->isIntegerType())
13106           return;
13107       } else {
13108         return;
13109       }
13110     }
13111   } else { // !IsCompare
13112     // For function to bool, only suggest if the function pointer has bool
13113     // return type.
13114     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13115       return;
13116   }
13117   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13118       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13119 }
13120 
13121 /// Diagnoses "dangerous" implicit conversions within the given
13122 /// expression (which is a full expression).  Implements -Wconversion
13123 /// and -Wsign-compare.
13124 ///
13125 /// \param CC the "context" location of the implicit conversion, i.e.
13126 ///   the most location of the syntactic entity requiring the implicit
13127 ///   conversion
13128 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13129   // Don't diagnose in unevaluated contexts.
13130   if (isUnevaluatedContext())
13131     return;
13132 
13133   // Don't diagnose for value- or type-dependent expressions.
13134   if (E->isTypeDependent() || E->isValueDependent())
13135     return;
13136 
13137   // Check for array bounds violations in cases where the check isn't triggered
13138   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13139   // ArraySubscriptExpr is on the RHS of a variable initialization.
13140   CheckArrayAccess(E);
13141 
13142   // This is not the right CC for (e.g.) a variable initialization.
13143   AnalyzeImplicitConversions(*this, E, CC);
13144 }
13145 
13146 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13147 /// Input argument E is a logical expression.
13148 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13149   ::CheckBoolLikeConversion(*this, E, CC);
13150 }
13151 
13152 /// Diagnose when expression is an integer constant expression and its evaluation
13153 /// results in integer overflow
13154 void Sema::CheckForIntOverflow (Expr *E) {
13155   // Use a work list to deal with nested struct initializers.
13156   SmallVector<Expr *, 2> Exprs(1, E);
13157 
13158   do {
13159     Expr *OriginalE = Exprs.pop_back_val();
13160     Expr *E = OriginalE->IgnoreParenCasts();
13161 
13162     if (isa<BinaryOperator>(E)) {
13163       E->EvaluateForOverflow(Context);
13164       continue;
13165     }
13166 
13167     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13168       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13169     else if (isa<ObjCBoxedExpr>(OriginalE))
13170       E->EvaluateForOverflow(Context);
13171     else if (auto Call = dyn_cast<CallExpr>(E))
13172       Exprs.append(Call->arg_begin(), Call->arg_end());
13173     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13174       Exprs.append(Message->arg_begin(), Message->arg_end());
13175   } while (!Exprs.empty());
13176 }
13177 
13178 namespace {
13179 
13180 /// Visitor for expressions which looks for unsequenced operations on the
13181 /// same object.
13182 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13183   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13184 
13185   /// A tree of sequenced regions within an expression. Two regions are
13186   /// unsequenced if one is an ancestor or a descendent of the other. When we
13187   /// finish processing an expression with sequencing, such as a comma
13188   /// expression, we fold its tree nodes into its parent, since they are
13189   /// unsequenced with respect to nodes we will visit later.
13190   class SequenceTree {
13191     struct Value {
13192       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13193       unsigned Parent : 31;
13194       unsigned Merged : 1;
13195     };
13196     SmallVector<Value, 8> Values;
13197 
13198   public:
13199     /// A region within an expression which may be sequenced with respect
13200     /// to some other region.
13201     class Seq {
13202       friend class SequenceTree;
13203 
13204       unsigned Index;
13205 
13206       explicit Seq(unsigned N) : Index(N) {}
13207 
13208     public:
13209       Seq() : Index(0) {}
13210     };
13211 
13212     SequenceTree() { Values.push_back(Value(0)); }
13213     Seq root() const { return Seq(0); }
13214 
13215     /// Create a new sequence of operations, which is an unsequenced
13216     /// subset of \p Parent. This sequence of operations is sequenced with
13217     /// respect to other children of \p Parent.
13218     Seq allocate(Seq Parent) {
13219       Values.push_back(Value(Parent.Index));
13220       return Seq(Values.size() - 1);
13221     }
13222 
13223     /// Merge a sequence of operations into its parent.
13224     void merge(Seq S) {
13225       Values[S.Index].Merged = true;
13226     }
13227 
13228     /// Determine whether two operations are unsequenced. This operation
13229     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13230     /// should have been merged into its parent as appropriate.
13231     bool isUnsequenced(Seq Cur, Seq Old) {
13232       unsigned C = representative(Cur.Index);
13233       unsigned Target = representative(Old.Index);
13234       while (C >= Target) {
13235         if (C == Target)
13236           return true;
13237         C = Values[C].Parent;
13238       }
13239       return false;
13240     }
13241 
13242   private:
13243     /// Pick a representative for a sequence.
13244     unsigned representative(unsigned K) {
13245       if (Values[K].Merged)
13246         // Perform path compression as we go.
13247         return Values[K].Parent = representative(Values[K].Parent);
13248       return K;
13249     }
13250   };
13251 
13252   /// An object for which we can track unsequenced uses.
13253   using Object = const NamedDecl *;
13254 
13255   /// Different flavors of object usage which we track. We only track the
13256   /// least-sequenced usage of each kind.
13257   enum UsageKind {
13258     /// A read of an object. Multiple unsequenced reads are OK.
13259     UK_Use,
13260 
13261     /// A modification of an object which is sequenced before the value
13262     /// computation of the expression, such as ++n in C++.
13263     UK_ModAsValue,
13264 
13265     /// A modification of an object which is not sequenced before the value
13266     /// computation of the expression, such as n++.
13267     UK_ModAsSideEffect,
13268 
13269     UK_Count = UK_ModAsSideEffect + 1
13270   };
13271 
13272   /// Bundle together a sequencing region and the expression corresponding
13273   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13274   struct Usage {
13275     const Expr *UsageExpr;
13276     SequenceTree::Seq Seq;
13277 
13278     Usage() : UsageExpr(nullptr), Seq() {}
13279   };
13280 
13281   struct UsageInfo {
13282     Usage Uses[UK_Count];
13283 
13284     /// Have we issued a diagnostic for this object already?
13285     bool Diagnosed;
13286 
13287     UsageInfo() : Uses(), Diagnosed(false) {}
13288   };
13289   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13290 
13291   Sema &SemaRef;
13292 
13293   /// Sequenced regions within the expression.
13294   SequenceTree Tree;
13295 
13296   /// Declaration modifications and references which we have seen.
13297   UsageInfoMap UsageMap;
13298 
13299   /// The region we are currently within.
13300   SequenceTree::Seq Region;
13301 
13302   /// Filled in with declarations which were modified as a side-effect
13303   /// (that is, post-increment operations).
13304   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13305 
13306   /// Expressions to check later. We defer checking these to reduce
13307   /// stack usage.
13308   SmallVectorImpl<const Expr *> &WorkList;
13309 
13310   /// RAII object wrapping the visitation of a sequenced subexpression of an
13311   /// expression. At the end of this process, the side-effects of the evaluation
13312   /// become sequenced with respect to the value computation of the result, so
13313   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13314   /// UK_ModAsValue.
13315   struct SequencedSubexpression {
13316     SequencedSubexpression(SequenceChecker &Self)
13317       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13318       Self.ModAsSideEffect = &ModAsSideEffect;
13319     }
13320 
13321     ~SequencedSubexpression() {
13322       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13323         // Add a new usage with usage kind UK_ModAsValue, and then restore
13324         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13325         // the previous one was empty).
13326         UsageInfo &UI = Self.UsageMap[M.first];
13327         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13328         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13329         SideEffectUsage = M.second;
13330       }
13331       Self.ModAsSideEffect = OldModAsSideEffect;
13332     }
13333 
13334     SequenceChecker &Self;
13335     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13336     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13337   };
13338 
13339   /// RAII object wrapping the visitation of a subexpression which we might
13340   /// choose to evaluate as a constant. If any subexpression is evaluated and
13341   /// found to be non-constant, this allows us to suppress the evaluation of
13342   /// the outer expression.
13343   class EvaluationTracker {
13344   public:
13345     EvaluationTracker(SequenceChecker &Self)
13346         : Self(Self), Prev(Self.EvalTracker) {
13347       Self.EvalTracker = this;
13348     }
13349 
13350     ~EvaluationTracker() {
13351       Self.EvalTracker = Prev;
13352       if (Prev)
13353         Prev->EvalOK &= EvalOK;
13354     }
13355 
13356     bool evaluate(const Expr *E, bool &Result) {
13357       if (!EvalOK || E->isValueDependent())
13358         return false;
13359       EvalOK = E->EvaluateAsBooleanCondition(
13360           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13361       return EvalOK;
13362     }
13363 
13364   private:
13365     SequenceChecker &Self;
13366     EvaluationTracker *Prev;
13367     bool EvalOK = true;
13368   } *EvalTracker = nullptr;
13369 
13370   /// Find the object which is produced by the specified expression,
13371   /// if any.
13372   Object getObject(const Expr *E, bool Mod) const {
13373     E = E->IgnoreParenCasts();
13374     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13375       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13376         return getObject(UO->getSubExpr(), Mod);
13377     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13378       if (BO->getOpcode() == BO_Comma)
13379         return getObject(BO->getRHS(), Mod);
13380       if (Mod && BO->isAssignmentOp())
13381         return getObject(BO->getLHS(), Mod);
13382     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13383       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13384       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13385         return ME->getMemberDecl();
13386     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13387       // FIXME: If this is a reference, map through to its value.
13388       return DRE->getDecl();
13389     return nullptr;
13390   }
13391 
13392   /// Note that an object \p O was modified or used by an expression
13393   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13394   /// the object \p O as obtained via the \p UsageMap.
13395   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13396     // Get the old usage for the given object and usage kind.
13397     Usage &U = UI.Uses[UK];
13398     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13399       // If we have a modification as side effect and are in a sequenced
13400       // subexpression, save the old Usage so that we can restore it later
13401       // in SequencedSubexpression::~SequencedSubexpression.
13402       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13403         ModAsSideEffect->push_back(std::make_pair(O, U));
13404       // Then record the new usage with the current sequencing region.
13405       U.UsageExpr = UsageExpr;
13406       U.Seq = Region;
13407     }
13408   }
13409 
13410   /// Check whether a modification or use of an object \p O in an expression
13411   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13412   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13413   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13414   /// usage and false we are checking for a mod-use unsequenced usage.
13415   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13416                   UsageKind OtherKind, bool IsModMod) {
13417     if (UI.Diagnosed)
13418       return;
13419 
13420     const Usage &U = UI.Uses[OtherKind];
13421     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13422       return;
13423 
13424     const Expr *Mod = U.UsageExpr;
13425     const Expr *ModOrUse = UsageExpr;
13426     if (OtherKind == UK_Use)
13427       std::swap(Mod, ModOrUse);
13428 
13429     SemaRef.DiagRuntimeBehavior(
13430         Mod->getExprLoc(), {Mod, ModOrUse},
13431         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13432                                : diag::warn_unsequenced_mod_use)
13433             << O << SourceRange(ModOrUse->getExprLoc()));
13434     UI.Diagnosed = true;
13435   }
13436 
13437   // A note on note{Pre, Post}{Use, Mod}:
13438   //
13439   // (It helps to follow the algorithm with an expression such as
13440   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13441   //  operations before C++17 and both are well-defined in C++17).
13442   //
13443   // When visiting a node which uses/modify an object we first call notePreUse
13444   // or notePreMod before visiting its sub-expression(s). At this point the
13445   // children of the current node have not yet been visited and so the eventual
13446   // uses/modifications resulting from the children of the current node have not
13447   // been recorded yet.
13448   //
13449   // We then visit the children of the current node. After that notePostUse or
13450   // notePostMod is called. These will 1) detect an unsequenced modification
13451   // as side effect (as in "k++ + k") and 2) add a new usage with the
13452   // appropriate usage kind.
13453   //
13454   // We also have to be careful that some operation sequences modification as
13455   // side effect as well (for example: || or ,). To account for this we wrap
13456   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13457   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13458   // which record usages which are modifications as side effect, and then
13459   // downgrade them (or more accurately restore the previous usage which was a
13460   // modification as side effect) when exiting the scope of the sequenced
13461   // subexpression.
13462 
13463   void notePreUse(Object O, const Expr *UseExpr) {
13464     UsageInfo &UI = UsageMap[O];
13465     // Uses conflict with other modifications.
13466     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13467   }
13468 
13469   void notePostUse(Object O, const Expr *UseExpr) {
13470     UsageInfo &UI = UsageMap[O];
13471     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13472                /*IsModMod=*/false);
13473     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13474   }
13475 
13476   void notePreMod(Object O, const Expr *ModExpr) {
13477     UsageInfo &UI = UsageMap[O];
13478     // Modifications conflict with other modifications and with uses.
13479     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13480     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13481   }
13482 
13483   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13484     UsageInfo &UI = UsageMap[O];
13485     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13486                /*IsModMod=*/true);
13487     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13488   }
13489 
13490 public:
13491   SequenceChecker(Sema &S, const Expr *E,
13492                   SmallVectorImpl<const Expr *> &WorkList)
13493       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13494     Visit(E);
13495     // Silence a -Wunused-private-field since WorkList is now unused.
13496     // TODO: Evaluate if it can be used, and if not remove it.
13497     (void)this->WorkList;
13498   }
13499 
13500   void VisitStmt(const Stmt *S) {
13501     // Skip all statements which aren't expressions for now.
13502   }
13503 
13504   void VisitExpr(const Expr *E) {
13505     // By default, just recurse to evaluated subexpressions.
13506     Base::VisitStmt(E);
13507   }
13508 
13509   void VisitCastExpr(const CastExpr *E) {
13510     Object O = Object();
13511     if (E->getCastKind() == CK_LValueToRValue)
13512       O = getObject(E->getSubExpr(), false);
13513 
13514     if (O)
13515       notePreUse(O, E);
13516     VisitExpr(E);
13517     if (O)
13518       notePostUse(O, E);
13519   }
13520 
13521   void VisitSequencedExpressions(const Expr *SequencedBefore,
13522                                  const Expr *SequencedAfter) {
13523     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13524     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13525     SequenceTree::Seq OldRegion = Region;
13526 
13527     {
13528       SequencedSubexpression SeqBefore(*this);
13529       Region = BeforeRegion;
13530       Visit(SequencedBefore);
13531     }
13532 
13533     Region = AfterRegion;
13534     Visit(SequencedAfter);
13535 
13536     Region = OldRegion;
13537 
13538     Tree.merge(BeforeRegion);
13539     Tree.merge(AfterRegion);
13540   }
13541 
13542   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13543     // C++17 [expr.sub]p1:
13544     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13545     //   expression E1 is sequenced before the expression E2.
13546     if (SemaRef.getLangOpts().CPlusPlus17)
13547       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13548     else {
13549       Visit(ASE->getLHS());
13550       Visit(ASE->getRHS());
13551     }
13552   }
13553 
13554   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13555   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13556   void VisitBinPtrMem(const BinaryOperator *BO) {
13557     // C++17 [expr.mptr.oper]p4:
13558     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13559     //  the expression E1 is sequenced before the expression E2.
13560     if (SemaRef.getLangOpts().CPlusPlus17)
13561       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13562     else {
13563       Visit(BO->getLHS());
13564       Visit(BO->getRHS());
13565     }
13566   }
13567 
13568   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13569   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13570   void VisitBinShlShr(const BinaryOperator *BO) {
13571     // C++17 [expr.shift]p4:
13572     //  The expression E1 is sequenced before the expression E2.
13573     if (SemaRef.getLangOpts().CPlusPlus17)
13574       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13575     else {
13576       Visit(BO->getLHS());
13577       Visit(BO->getRHS());
13578     }
13579   }
13580 
13581   void VisitBinComma(const BinaryOperator *BO) {
13582     // C++11 [expr.comma]p1:
13583     //   Every value computation and side effect associated with the left
13584     //   expression is sequenced before every value computation and side
13585     //   effect associated with the right expression.
13586     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13587   }
13588 
13589   void VisitBinAssign(const BinaryOperator *BO) {
13590     SequenceTree::Seq RHSRegion;
13591     SequenceTree::Seq LHSRegion;
13592     if (SemaRef.getLangOpts().CPlusPlus17) {
13593       RHSRegion = Tree.allocate(Region);
13594       LHSRegion = Tree.allocate(Region);
13595     } else {
13596       RHSRegion = Region;
13597       LHSRegion = Region;
13598     }
13599     SequenceTree::Seq OldRegion = Region;
13600 
13601     // C++11 [expr.ass]p1:
13602     //  [...] the assignment is sequenced after the value computation
13603     //  of the right and left operands, [...]
13604     //
13605     // so check it before inspecting the operands and update the
13606     // map afterwards.
13607     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13608     if (O)
13609       notePreMod(O, BO);
13610 
13611     if (SemaRef.getLangOpts().CPlusPlus17) {
13612       // C++17 [expr.ass]p1:
13613       //  [...] The right operand is sequenced before the left operand. [...]
13614       {
13615         SequencedSubexpression SeqBefore(*this);
13616         Region = RHSRegion;
13617         Visit(BO->getRHS());
13618       }
13619 
13620       Region = LHSRegion;
13621       Visit(BO->getLHS());
13622 
13623       if (O && isa<CompoundAssignOperator>(BO))
13624         notePostUse(O, BO);
13625 
13626     } else {
13627       // C++11 does not specify any sequencing between the LHS and RHS.
13628       Region = LHSRegion;
13629       Visit(BO->getLHS());
13630 
13631       if (O && isa<CompoundAssignOperator>(BO))
13632         notePostUse(O, BO);
13633 
13634       Region = RHSRegion;
13635       Visit(BO->getRHS());
13636     }
13637 
13638     // C++11 [expr.ass]p1:
13639     //  the assignment is sequenced [...] before the value computation of the
13640     //  assignment expression.
13641     // C11 6.5.16/3 has no such rule.
13642     Region = OldRegion;
13643     if (O)
13644       notePostMod(O, BO,
13645                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13646                                                   : UK_ModAsSideEffect);
13647     if (SemaRef.getLangOpts().CPlusPlus17) {
13648       Tree.merge(RHSRegion);
13649       Tree.merge(LHSRegion);
13650     }
13651   }
13652 
13653   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13654     VisitBinAssign(CAO);
13655   }
13656 
13657   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13658   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13659   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13660     Object O = getObject(UO->getSubExpr(), true);
13661     if (!O)
13662       return VisitExpr(UO);
13663 
13664     notePreMod(O, UO);
13665     Visit(UO->getSubExpr());
13666     // C++11 [expr.pre.incr]p1:
13667     //   the expression ++x is equivalent to x+=1
13668     notePostMod(O, UO,
13669                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13670                                                 : UK_ModAsSideEffect);
13671   }
13672 
13673   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13674   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13675   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13676     Object O = getObject(UO->getSubExpr(), true);
13677     if (!O)
13678       return VisitExpr(UO);
13679 
13680     notePreMod(O, UO);
13681     Visit(UO->getSubExpr());
13682     notePostMod(O, UO, UK_ModAsSideEffect);
13683   }
13684 
13685   void VisitBinLOr(const BinaryOperator *BO) {
13686     // C++11 [expr.log.or]p2:
13687     //  If the second expression is evaluated, every value computation and
13688     //  side effect associated with the first expression is sequenced before
13689     //  every value computation and side effect associated with the
13690     //  second expression.
13691     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13692     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13693     SequenceTree::Seq OldRegion = Region;
13694 
13695     EvaluationTracker Eval(*this);
13696     {
13697       SequencedSubexpression Sequenced(*this);
13698       Region = LHSRegion;
13699       Visit(BO->getLHS());
13700     }
13701 
13702     // C++11 [expr.log.or]p1:
13703     //  [...] the second operand is not evaluated if the first operand
13704     //  evaluates to true.
13705     bool EvalResult = false;
13706     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13707     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13708     if (ShouldVisitRHS) {
13709       Region = RHSRegion;
13710       Visit(BO->getRHS());
13711     }
13712 
13713     Region = OldRegion;
13714     Tree.merge(LHSRegion);
13715     Tree.merge(RHSRegion);
13716   }
13717 
13718   void VisitBinLAnd(const BinaryOperator *BO) {
13719     // C++11 [expr.log.and]p2:
13720     //  If the second expression is evaluated, every value computation and
13721     //  side effect associated with the first expression is sequenced before
13722     //  every value computation and side effect associated with the
13723     //  second expression.
13724     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13725     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13726     SequenceTree::Seq OldRegion = Region;
13727 
13728     EvaluationTracker Eval(*this);
13729     {
13730       SequencedSubexpression Sequenced(*this);
13731       Region = LHSRegion;
13732       Visit(BO->getLHS());
13733     }
13734 
13735     // C++11 [expr.log.and]p1:
13736     //  [...] the second operand is not evaluated if the first operand is false.
13737     bool EvalResult = false;
13738     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13739     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13740     if (ShouldVisitRHS) {
13741       Region = RHSRegion;
13742       Visit(BO->getRHS());
13743     }
13744 
13745     Region = OldRegion;
13746     Tree.merge(LHSRegion);
13747     Tree.merge(RHSRegion);
13748   }
13749 
13750   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13751     // C++11 [expr.cond]p1:
13752     //  [...] Every value computation and side effect associated with the first
13753     //  expression is sequenced before every value computation and side effect
13754     //  associated with the second or third expression.
13755     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13756 
13757     // No sequencing is specified between the true and false expression.
13758     // However since exactly one of both is going to be evaluated we can
13759     // consider them to be sequenced. This is needed to avoid warning on
13760     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13761     // both the true and false expressions because we can't evaluate x.
13762     // This will still allow us to detect an expression like (pre C++17)
13763     // "(x ? y += 1 : y += 2) = y".
13764     //
13765     // We don't wrap the visitation of the true and false expression with
13766     // SequencedSubexpression because we don't want to downgrade modifications
13767     // as side effect in the true and false expressions after the visition
13768     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13769     // not warn between the two "y++", but we should warn between the "y++"
13770     // and the "y".
13771     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13772     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13773     SequenceTree::Seq OldRegion = Region;
13774 
13775     EvaluationTracker Eval(*this);
13776     {
13777       SequencedSubexpression Sequenced(*this);
13778       Region = ConditionRegion;
13779       Visit(CO->getCond());
13780     }
13781 
13782     // C++11 [expr.cond]p1:
13783     // [...] The first expression is contextually converted to bool (Clause 4).
13784     // It is evaluated and if it is true, the result of the conditional
13785     // expression is the value of the second expression, otherwise that of the
13786     // third expression. Only one of the second and third expressions is
13787     // evaluated. [...]
13788     bool EvalResult = false;
13789     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13790     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13791     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13792     if (ShouldVisitTrueExpr) {
13793       Region = TrueRegion;
13794       Visit(CO->getTrueExpr());
13795     }
13796     if (ShouldVisitFalseExpr) {
13797       Region = FalseRegion;
13798       Visit(CO->getFalseExpr());
13799     }
13800 
13801     Region = OldRegion;
13802     Tree.merge(ConditionRegion);
13803     Tree.merge(TrueRegion);
13804     Tree.merge(FalseRegion);
13805   }
13806 
13807   void VisitCallExpr(const CallExpr *CE) {
13808     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13809 
13810     if (CE->isUnevaluatedBuiltinCall(Context))
13811       return;
13812 
13813     // C++11 [intro.execution]p15:
13814     //   When calling a function [...], every value computation and side effect
13815     //   associated with any argument expression, or with the postfix expression
13816     //   designating the called function, is sequenced before execution of every
13817     //   expression or statement in the body of the function [and thus before
13818     //   the value computation of its result].
13819     SequencedSubexpression Sequenced(*this);
13820     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13821       // C++17 [expr.call]p5
13822       //   The postfix-expression is sequenced before each expression in the
13823       //   expression-list and any default argument. [...]
13824       SequenceTree::Seq CalleeRegion;
13825       SequenceTree::Seq OtherRegion;
13826       if (SemaRef.getLangOpts().CPlusPlus17) {
13827         CalleeRegion = Tree.allocate(Region);
13828         OtherRegion = Tree.allocate(Region);
13829       } else {
13830         CalleeRegion = Region;
13831         OtherRegion = Region;
13832       }
13833       SequenceTree::Seq OldRegion = Region;
13834 
13835       // Visit the callee expression first.
13836       Region = CalleeRegion;
13837       if (SemaRef.getLangOpts().CPlusPlus17) {
13838         SequencedSubexpression Sequenced(*this);
13839         Visit(CE->getCallee());
13840       } else {
13841         Visit(CE->getCallee());
13842       }
13843 
13844       // Then visit the argument expressions.
13845       Region = OtherRegion;
13846       for (const Expr *Argument : CE->arguments())
13847         Visit(Argument);
13848 
13849       Region = OldRegion;
13850       if (SemaRef.getLangOpts().CPlusPlus17) {
13851         Tree.merge(CalleeRegion);
13852         Tree.merge(OtherRegion);
13853       }
13854     });
13855   }
13856 
13857   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13858     // C++17 [over.match.oper]p2:
13859     //   [...] the operator notation is first transformed to the equivalent
13860     //   function-call notation as summarized in Table 12 (where @ denotes one
13861     //   of the operators covered in the specified subclause). However, the
13862     //   operands are sequenced in the order prescribed for the built-in
13863     //   operator (Clause 8).
13864     //
13865     // From the above only overloaded binary operators and overloaded call
13866     // operators have sequencing rules in C++17 that we need to handle
13867     // separately.
13868     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13869         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13870       return VisitCallExpr(CXXOCE);
13871 
13872     enum {
13873       NoSequencing,
13874       LHSBeforeRHS,
13875       RHSBeforeLHS,
13876       LHSBeforeRest
13877     } SequencingKind;
13878     switch (CXXOCE->getOperator()) {
13879     case OO_Equal:
13880     case OO_PlusEqual:
13881     case OO_MinusEqual:
13882     case OO_StarEqual:
13883     case OO_SlashEqual:
13884     case OO_PercentEqual:
13885     case OO_CaretEqual:
13886     case OO_AmpEqual:
13887     case OO_PipeEqual:
13888     case OO_LessLessEqual:
13889     case OO_GreaterGreaterEqual:
13890       SequencingKind = RHSBeforeLHS;
13891       break;
13892 
13893     case OO_LessLess:
13894     case OO_GreaterGreater:
13895     case OO_AmpAmp:
13896     case OO_PipePipe:
13897     case OO_Comma:
13898     case OO_ArrowStar:
13899     case OO_Subscript:
13900       SequencingKind = LHSBeforeRHS;
13901       break;
13902 
13903     case OO_Call:
13904       SequencingKind = LHSBeforeRest;
13905       break;
13906 
13907     default:
13908       SequencingKind = NoSequencing;
13909       break;
13910     }
13911 
13912     if (SequencingKind == NoSequencing)
13913       return VisitCallExpr(CXXOCE);
13914 
13915     // This is a call, so all subexpressions are sequenced before the result.
13916     SequencedSubexpression Sequenced(*this);
13917 
13918     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13919       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13920              "Should only get there with C++17 and above!");
13921       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13922              "Should only get there with an overloaded binary operator"
13923              " or an overloaded call operator!");
13924 
13925       if (SequencingKind == LHSBeforeRest) {
13926         assert(CXXOCE->getOperator() == OO_Call &&
13927                "We should only have an overloaded call operator here!");
13928 
13929         // This is very similar to VisitCallExpr, except that we only have the
13930         // C++17 case. The postfix-expression is the first argument of the
13931         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13932         // are in the following arguments.
13933         //
13934         // Note that we intentionally do not visit the callee expression since
13935         // it is just a decayed reference to a function.
13936         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13937         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13938         SequenceTree::Seq OldRegion = Region;
13939 
13940         assert(CXXOCE->getNumArgs() >= 1 &&
13941                "An overloaded call operator must have at least one argument"
13942                " for the postfix-expression!");
13943         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13944         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13945                                           CXXOCE->getNumArgs() - 1);
13946 
13947         // Visit the postfix-expression first.
13948         {
13949           Region = PostfixExprRegion;
13950           SequencedSubexpression Sequenced(*this);
13951           Visit(PostfixExpr);
13952         }
13953 
13954         // Then visit the argument expressions.
13955         Region = ArgsRegion;
13956         for (const Expr *Arg : Args)
13957           Visit(Arg);
13958 
13959         Region = OldRegion;
13960         Tree.merge(PostfixExprRegion);
13961         Tree.merge(ArgsRegion);
13962       } else {
13963         assert(CXXOCE->getNumArgs() == 2 &&
13964                "Should only have two arguments here!");
13965         assert((SequencingKind == LHSBeforeRHS ||
13966                 SequencingKind == RHSBeforeLHS) &&
13967                "Unexpected sequencing kind!");
13968 
13969         // We do not visit the callee expression since it is just a decayed
13970         // reference to a function.
13971         const Expr *E1 = CXXOCE->getArg(0);
13972         const Expr *E2 = CXXOCE->getArg(1);
13973         if (SequencingKind == RHSBeforeLHS)
13974           std::swap(E1, E2);
13975 
13976         return VisitSequencedExpressions(E1, E2);
13977       }
13978     });
13979   }
13980 
13981   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13982     // This is a call, so all subexpressions are sequenced before the result.
13983     SequencedSubexpression Sequenced(*this);
13984 
13985     if (!CCE->isListInitialization())
13986       return VisitExpr(CCE);
13987 
13988     // In C++11, list initializations are sequenced.
13989     SmallVector<SequenceTree::Seq, 32> Elts;
13990     SequenceTree::Seq Parent = Region;
13991     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13992                                               E = CCE->arg_end();
13993          I != E; ++I) {
13994       Region = Tree.allocate(Parent);
13995       Elts.push_back(Region);
13996       Visit(*I);
13997     }
13998 
13999     // Forget that the initializers are sequenced.
14000     Region = Parent;
14001     for (unsigned I = 0; I < Elts.size(); ++I)
14002       Tree.merge(Elts[I]);
14003   }
14004 
14005   void VisitInitListExpr(const InitListExpr *ILE) {
14006     if (!SemaRef.getLangOpts().CPlusPlus11)
14007       return VisitExpr(ILE);
14008 
14009     // In C++11, list initializations are sequenced.
14010     SmallVector<SequenceTree::Seq, 32> Elts;
14011     SequenceTree::Seq Parent = Region;
14012     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14013       const Expr *E = ILE->getInit(I);
14014       if (!E)
14015         continue;
14016       Region = Tree.allocate(Parent);
14017       Elts.push_back(Region);
14018       Visit(E);
14019     }
14020 
14021     // Forget that the initializers are sequenced.
14022     Region = Parent;
14023     for (unsigned I = 0; I < Elts.size(); ++I)
14024       Tree.merge(Elts[I]);
14025   }
14026 };
14027 
14028 } // namespace
14029 
14030 void Sema::CheckUnsequencedOperations(const Expr *E) {
14031   SmallVector<const Expr *, 8> WorkList;
14032   WorkList.push_back(E);
14033   while (!WorkList.empty()) {
14034     const Expr *Item = WorkList.pop_back_val();
14035     SequenceChecker(*this, Item, WorkList);
14036   }
14037 }
14038 
14039 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14040                               bool IsConstexpr) {
14041   llvm::SaveAndRestore<bool> ConstantContext(
14042       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14043   CheckImplicitConversions(E, CheckLoc);
14044   if (!E->isInstantiationDependent())
14045     CheckUnsequencedOperations(E);
14046   if (!IsConstexpr && !E->isValueDependent())
14047     CheckForIntOverflow(E);
14048   DiagnoseMisalignedMembers();
14049 }
14050 
14051 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14052                                        FieldDecl *BitField,
14053                                        Expr *Init) {
14054   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14055 }
14056 
14057 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14058                                          SourceLocation Loc) {
14059   if (!PType->isVariablyModifiedType())
14060     return;
14061   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14062     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14063     return;
14064   }
14065   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14066     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14067     return;
14068   }
14069   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14070     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14071     return;
14072   }
14073 
14074   const ArrayType *AT = S.Context.getAsArrayType(PType);
14075   if (!AT)
14076     return;
14077 
14078   if (AT->getSizeModifier() != ArrayType::Star) {
14079     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14080     return;
14081   }
14082 
14083   S.Diag(Loc, diag::err_array_star_in_function_definition);
14084 }
14085 
14086 /// CheckParmsForFunctionDef - Check that the parameters of the given
14087 /// function are appropriate for the definition of a function. This
14088 /// takes care of any checks that cannot be performed on the
14089 /// declaration itself, e.g., that the types of each of the function
14090 /// parameters are complete.
14091 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14092                                     bool CheckParameterNames) {
14093   bool HasInvalidParm = false;
14094   for (ParmVarDecl *Param : Parameters) {
14095     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14096     // function declarator that is part of a function definition of
14097     // that function shall not have incomplete type.
14098     //
14099     // This is also C++ [dcl.fct]p6.
14100     if (!Param->isInvalidDecl() &&
14101         RequireCompleteType(Param->getLocation(), Param->getType(),
14102                             diag::err_typecheck_decl_incomplete_type)) {
14103       Param->setInvalidDecl();
14104       HasInvalidParm = true;
14105     }
14106 
14107     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14108     // declaration of each parameter shall include an identifier.
14109     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14110         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14111       // Diagnose this as an extension in C17 and earlier.
14112       if (!getLangOpts().C2x)
14113         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14114     }
14115 
14116     // C99 6.7.5.3p12:
14117     //   If the function declarator is not part of a definition of that
14118     //   function, parameters may have incomplete type and may use the [*]
14119     //   notation in their sequences of declarator specifiers to specify
14120     //   variable length array types.
14121     QualType PType = Param->getOriginalType();
14122     // FIXME: This diagnostic should point the '[*]' if source-location
14123     // information is added for it.
14124     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14125 
14126     // If the parameter is a c++ class type and it has to be destructed in the
14127     // callee function, declare the destructor so that it can be called by the
14128     // callee function. Do not perform any direct access check on the dtor here.
14129     if (!Param->isInvalidDecl()) {
14130       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14131         if (!ClassDecl->isInvalidDecl() &&
14132             !ClassDecl->hasIrrelevantDestructor() &&
14133             !ClassDecl->isDependentContext() &&
14134             ClassDecl->isParamDestroyedInCallee()) {
14135           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14136           MarkFunctionReferenced(Param->getLocation(), Destructor);
14137           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14138         }
14139       }
14140     }
14141 
14142     // Parameters with the pass_object_size attribute only need to be marked
14143     // constant at function definitions. Because we lack information about
14144     // whether we're on a declaration or definition when we're instantiating the
14145     // attribute, we need to check for constness here.
14146     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14147       if (!Param->getType().isConstQualified())
14148         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14149             << Attr->getSpelling() << 1;
14150 
14151     // Check for parameter names shadowing fields from the class.
14152     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14153       // The owning context for the parameter should be the function, but we
14154       // want to see if this function's declaration context is a record.
14155       DeclContext *DC = Param->getDeclContext();
14156       if (DC && DC->isFunctionOrMethod()) {
14157         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14158           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14159                                      RD, /*DeclIsField*/ false);
14160       }
14161     }
14162   }
14163 
14164   return HasInvalidParm;
14165 }
14166 
14167 Optional<std::pair<CharUnits, CharUnits>>
14168 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14169 
14170 /// Compute the alignment and offset of the base class object given the
14171 /// derived-to-base cast expression and the alignment and offset of the derived
14172 /// class object.
14173 static std::pair<CharUnits, CharUnits>
14174 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14175                                    CharUnits BaseAlignment, CharUnits Offset,
14176                                    ASTContext &Ctx) {
14177   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14178        ++PathI) {
14179     const CXXBaseSpecifier *Base = *PathI;
14180     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14181     if (Base->isVirtual()) {
14182       // The complete object may have a lower alignment than the non-virtual
14183       // alignment of the base, in which case the base may be misaligned. Choose
14184       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14185       // conservative lower bound of the complete object alignment.
14186       CharUnits NonVirtualAlignment =
14187           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14188       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14189       Offset = CharUnits::Zero();
14190     } else {
14191       const ASTRecordLayout &RL =
14192           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14193       Offset += RL.getBaseClassOffset(BaseDecl);
14194     }
14195     DerivedType = Base->getType();
14196   }
14197 
14198   return std::make_pair(BaseAlignment, Offset);
14199 }
14200 
14201 /// Compute the alignment and offset of a binary additive operator.
14202 static Optional<std::pair<CharUnits, CharUnits>>
14203 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14204                                      bool IsSub, ASTContext &Ctx) {
14205   QualType PointeeType = PtrE->getType()->getPointeeType();
14206 
14207   if (!PointeeType->isConstantSizeType())
14208     return llvm::None;
14209 
14210   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14211 
14212   if (!P)
14213     return llvm::None;
14214 
14215   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14216   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14217     CharUnits Offset = EltSize * IdxRes->getExtValue();
14218     if (IsSub)
14219       Offset = -Offset;
14220     return std::make_pair(P->first, P->second + Offset);
14221   }
14222 
14223   // If the integer expression isn't a constant expression, compute the lower
14224   // bound of the alignment using the alignment and offset of the pointer
14225   // expression and the element size.
14226   return std::make_pair(
14227       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14228       CharUnits::Zero());
14229 }
14230 
14231 /// This helper function takes an lvalue expression and returns the alignment of
14232 /// a VarDecl and a constant offset from the VarDecl.
14233 Optional<std::pair<CharUnits, CharUnits>>
14234 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14235   E = E->IgnoreParens();
14236   switch (E->getStmtClass()) {
14237   default:
14238     break;
14239   case Stmt::CStyleCastExprClass:
14240   case Stmt::CXXStaticCastExprClass:
14241   case Stmt::ImplicitCastExprClass: {
14242     auto *CE = cast<CastExpr>(E);
14243     const Expr *From = CE->getSubExpr();
14244     switch (CE->getCastKind()) {
14245     default:
14246       break;
14247     case CK_NoOp:
14248       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14249     case CK_UncheckedDerivedToBase:
14250     case CK_DerivedToBase: {
14251       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14252       if (!P)
14253         break;
14254       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14255                                                 P->second, Ctx);
14256     }
14257     }
14258     break;
14259   }
14260   case Stmt::ArraySubscriptExprClass: {
14261     auto *ASE = cast<ArraySubscriptExpr>(E);
14262     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14263                                                 false, Ctx);
14264   }
14265   case Stmt::DeclRefExprClass: {
14266     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14267       // FIXME: If VD is captured by copy or is an escaping __block variable,
14268       // use the alignment of VD's type.
14269       if (!VD->getType()->isReferenceType())
14270         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14271       if (VD->hasInit())
14272         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14273     }
14274     break;
14275   }
14276   case Stmt::MemberExprClass: {
14277     auto *ME = cast<MemberExpr>(E);
14278     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14279     if (!FD || FD->getType()->isReferenceType())
14280       break;
14281     Optional<std::pair<CharUnits, CharUnits>> P;
14282     if (ME->isArrow())
14283       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14284     else
14285       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14286     if (!P)
14287       break;
14288     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14289     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14290     return std::make_pair(P->first,
14291                           P->second + CharUnits::fromQuantity(Offset));
14292   }
14293   case Stmt::UnaryOperatorClass: {
14294     auto *UO = cast<UnaryOperator>(E);
14295     switch (UO->getOpcode()) {
14296     default:
14297       break;
14298     case UO_Deref:
14299       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14300     }
14301     break;
14302   }
14303   case Stmt::BinaryOperatorClass: {
14304     auto *BO = cast<BinaryOperator>(E);
14305     auto Opcode = BO->getOpcode();
14306     switch (Opcode) {
14307     default:
14308       break;
14309     case BO_Comma:
14310       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14311     }
14312     break;
14313   }
14314   }
14315   return llvm::None;
14316 }
14317 
14318 /// This helper function takes a pointer expression and returns the alignment of
14319 /// a VarDecl and a constant offset from the VarDecl.
14320 Optional<std::pair<CharUnits, CharUnits>>
14321 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14322   E = E->IgnoreParens();
14323   switch (E->getStmtClass()) {
14324   default:
14325     break;
14326   case Stmt::CStyleCastExprClass:
14327   case Stmt::CXXStaticCastExprClass:
14328   case Stmt::ImplicitCastExprClass: {
14329     auto *CE = cast<CastExpr>(E);
14330     const Expr *From = CE->getSubExpr();
14331     switch (CE->getCastKind()) {
14332     default:
14333       break;
14334     case CK_NoOp:
14335       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14336     case CK_ArrayToPointerDecay:
14337       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14338     case CK_UncheckedDerivedToBase:
14339     case CK_DerivedToBase: {
14340       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14341       if (!P)
14342         break;
14343       return getDerivedToBaseAlignmentAndOffset(
14344           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14345     }
14346     }
14347     break;
14348   }
14349   case Stmt::CXXThisExprClass: {
14350     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14351     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14352     return std::make_pair(Alignment, CharUnits::Zero());
14353   }
14354   case Stmt::UnaryOperatorClass: {
14355     auto *UO = cast<UnaryOperator>(E);
14356     if (UO->getOpcode() == UO_AddrOf)
14357       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14358     break;
14359   }
14360   case Stmt::BinaryOperatorClass: {
14361     auto *BO = cast<BinaryOperator>(E);
14362     auto Opcode = BO->getOpcode();
14363     switch (Opcode) {
14364     default:
14365       break;
14366     case BO_Add:
14367     case BO_Sub: {
14368       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14369       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14370         std::swap(LHS, RHS);
14371       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14372                                                   Ctx);
14373     }
14374     case BO_Comma:
14375       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14376     }
14377     break;
14378   }
14379   }
14380   return llvm::None;
14381 }
14382 
14383 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14384   // See if we can compute the alignment of a VarDecl and an offset from it.
14385   Optional<std::pair<CharUnits, CharUnits>> P =
14386       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14387 
14388   if (P)
14389     return P->first.alignmentAtOffset(P->second);
14390 
14391   // If that failed, return the type's alignment.
14392   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14393 }
14394 
14395 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14396 /// pointer cast increases the alignment requirements.
14397 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14398   // This is actually a lot of work to potentially be doing on every
14399   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14400   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14401     return;
14402 
14403   // Ignore dependent types.
14404   if (T->isDependentType() || Op->getType()->isDependentType())
14405     return;
14406 
14407   // Require that the destination be a pointer type.
14408   const PointerType *DestPtr = T->getAs<PointerType>();
14409   if (!DestPtr) return;
14410 
14411   // If the destination has alignment 1, we're done.
14412   QualType DestPointee = DestPtr->getPointeeType();
14413   if (DestPointee->isIncompleteType()) return;
14414   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14415   if (DestAlign.isOne()) return;
14416 
14417   // Require that the source be a pointer type.
14418   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14419   if (!SrcPtr) return;
14420   QualType SrcPointee = SrcPtr->getPointeeType();
14421 
14422   // Explicitly allow casts from cv void*.  We already implicitly
14423   // allowed casts to cv void*, since they have alignment 1.
14424   // Also allow casts involving incomplete types, which implicitly
14425   // includes 'void'.
14426   if (SrcPointee->isIncompleteType()) return;
14427 
14428   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14429 
14430   if (SrcAlign >= DestAlign) return;
14431 
14432   Diag(TRange.getBegin(), diag::warn_cast_align)
14433     << Op->getType() << T
14434     << static_cast<unsigned>(SrcAlign.getQuantity())
14435     << static_cast<unsigned>(DestAlign.getQuantity())
14436     << TRange << Op->getSourceRange();
14437 }
14438 
14439 /// Check whether this array fits the idiom of a size-one tail padded
14440 /// array member of a struct.
14441 ///
14442 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14443 /// commonly used to emulate flexible arrays in C89 code.
14444 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14445                                     const NamedDecl *ND) {
14446   if (Size != 1 || !ND) return false;
14447 
14448   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14449   if (!FD) return false;
14450 
14451   // Don't consider sizes resulting from macro expansions or template argument
14452   // substitution to form C89 tail-padded arrays.
14453 
14454   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14455   while (TInfo) {
14456     TypeLoc TL = TInfo->getTypeLoc();
14457     // Look through typedefs.
14458     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14459       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14460       TInfo = TDL->getTypeSourceInfo();
14461       continue;
14462     }
14463     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14464       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14465       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14466         return false;
14467     }
14468     break;
14469   }
14470 
14471   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14472   if (!RD) return false;
14473   if (RD->isUnion()) return false;
14474   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14475     if (!CRD->isStandardLayout()) return false;
14476   }
14477 
14478   // See if this is the last field decl in the record.
14479   const Decl *D = FD;
14480   while ((D = D->getNextDeclInContext()))
14481     if (isa<FieldDecl>(D))
14482       return false;
14483   return true;
14484 }
14485 
14486 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14487                             const ArraySubscriptExpr *ASE,
14488                             bool AllowOnePastEnd, bool IndexNegated) {
14489   // Already diagnosed by the constant evaluator.
14490   if (isConstantEvaluated())
14491     return;
14492 
14493   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14494   if (IndexExpr->isValueDependent())
14495     return;
14496 
14497   const Type *EffectiveType =
14498       BaseExpr->getType()->getPointeeOrArrayElementType();
14499   BaseExpr = BaseExpr->IgnoreParenCasts();
14500   const ConstantArrayType *ArrayTy =
14501       Context.getAsConstantArrayType(BaseExpr->getType());
14502 
14503   if (!ArrayTy)
14504     return;
14505 
14506   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14507   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14508     return;
14509 
14510   Expr::EvalResult Result;
14511   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14512     return;
14513 
14514   llvm::APSInt index = Result.Val.getInt();
14515   if (IndexNegated)
14516     index = -index;
14517 
14518   const NamedDecl *ND = nullptr;
14519   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14520     ND = DRE->getDecl();
14521   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14522     ND = ME->getMemberDecl();
14523 
14524   if (index.isUnsigned() || !index.isNegative()) {
14525     // It is possible that the type of the base expression after
14526     // IgnoreParenCasts is incomplete, even though the type of the base
14527     // expression before IgnoreParenCasts is complete (see PR39746 for an
14528     // example). In this case we have no information about whether the array
14529     // access exceeds the array bounds. However we can still diagnose an array
14530     // access which precedes the array bounds.
14531     if (BaseType->isIncompleteType())
14532       return;
14533 
14534     llvm::APInt size = ArrayTy->getSize();
14535     if (!size.isStrictlyPositive())
14536       return;
14537 
14538     if (BaseType != EffectiveType) {
14539       // Make sure we're comparing apples to apples when comparing index to size
14540       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14541       uint64_t array_typesize = Context.getTypeSize(BaseType);
14542       // Handle ptrarith_typesize being zero, such as when casting to void*
14543       if (!ptrarith_typesize) ptrarith_typesize = 1;
14544       if (ptrarith_typesize != array_typesize) {
14545         // There's a cast to a different size type involved
14546         uint64_t ratio = array_typesize / ptrarith_typesize;
14547         // TODO: Be smarter about handling cases where array_typesize is not a
14548         // multiple of ptrarith_typesize
14549         if (ptrarith_typesize * ratio == array_typesize)
14550           size *= llvm::APInt(size.getBitWidth(), ratio);
14551       }
14552     }
14553 
14554     if (size.getBitWidth() > index.getBitWidth())
14555       index = index.zext(size.getBitWidth());
14556     else if (size.getBitWidth() < index.getBitWidth())
14557       size = size.zext(index.getBitWidth());
14558 
14559     // For array subscripting the index must be less than size, but for pointer
14560     // arithmetic also allow the index (offset) to be equal to size since
14561     // computing the next address after the end of the array is legal and
14562     // commonly done e.g. in C++ iterators and range-based for loops.
14563     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14564       return;
14565 
14566     // Also don't warn for arrays of size 1 which are members of some
14567     // structure. These are often used to approximate flexible arrays in C89
14568     // code.
14569     if (IsTailPaddedMemberArray(*this, size, ND))
14570       return;
14571 
14572     // Suppress the warning if the subscript expression (as identified by the
14573     // ']' location) and the index expression are both from macro expansions
14574     // within a system header.
14575     if (ASE) {
14576       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14577           ASE->getRBracketLoc());
14578       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14579         SourceLocation IndexLoc =
14580             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14581         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14582           return;
14583       }
14584     }
14585 
14586     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14587     if (ASE)
14588       DiagID = diag::warn_array_index_exceeds_bounds;
14589 
14590     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14591                         PDiag(DiagID) << index.toString(10, true)
14592                                       << size.toString(10, true)
14593                                       << (unsigned)size.getLimitedValue(~0U)
14594                                       << IndexExpr->getSourceRange());
14595   } else {
14596     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14597     if (!ASE) {
14598       DiagID = diag::warn_ptr_arith_precedes_bounds;
14599       if (index.isNegative()) index = -index;
14600     }
14601 
14602     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14603                         PDiag(DiagID) << index.toString(10, true)
14604                                       << IndexExpr->getSourceRange());
14605   }
14606 
14607   if (!ND) {
14608     // Try harder to find a NamedDecl to point at in the note.
14609     while (const ArraySubscriptExpr *ASE =
14610            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14611       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14612     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14613       ND = DRE->getDecl();
14614     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14615       ND = ME->getMemberDecl();
14616   }
14617 
14618   if (ND)
14619     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14620                         PDiag(diag::note_array_declared_here) << ND);
14621 }
14622 
14623 void Sema::CheckArrayAccess(const Expr *expr) {
14624   int AllowOnePastEnd = 0;
14625   while (expr) {
14626     expr = expr->IgnoreParenImpCasts();
14627     switch (expr->getStmtClass()) {
14628       case Stmt::ArraySubscriptExprClass: {
14629         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14630         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14631                          AllowOnePastEnd > 0);
14632         expr = ASE->getBase();
14633         break;
14634       }
14635       case Stmt::MemberExprClass: {
14636         expr = cast<MemberExpr>(expr)->getBase();
14637         break;
14638       }
14639       case Stmt::OMPArraySectionExprClass: {
14640         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14641         if (ASE->getLowerBound())
14642           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14643                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14644         return;
14645       }
14646       case Stmt::UnaryOperatorClass: {
14647         // Only unwrap the * and & unary operators
14648         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14649         expr = UO->getSubExpr();
14650         switch (UO->getOpcode()) {
14651           case UO_AddrOf:
14652             AllowOnePastEnd++;
14653             break;
14654           case UO_Deref:
14655             AllowOnePastEnd--;
14656             break;
14657           default:
14658             return;
14659         }
14660         break;
14661       }
14662       case Stmt::ConditionalOperatorClass: {
14663         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14664         if (const Expr *lhs = cond->getLHS())
14665           CheckArrayAccess(lhs);
14666         if (const Expr *rhs = cond->getRHS())
14667           CheckArrayAccess(rhs);
14668         return;
14669       }
14670       case Stmt::CXXOperatorCallExprClass: {
14671         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14672         for (const auto *Arg : OCE->arguments())
14673           CheckArrayAccess(Arg);
14674         return;
14675       }
14676       default:
14677         return;
14678     }
14679   }
14680 }
14681 
14682 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14683 
14684 namespace {
14685 
14686 struct RetainCycleOwner {
14687   VarDecl *Variable = nullptr;
14688   SourceRange Range;
14689   SourceLocation Loc;
14690   bool Indirect = false;
14691 
14692   RetainCycleOwner() = default;
14693 
14694   void setLocsFrom(Expr *e) {
14695     Loc = e->getExprLoc();
14696     Range = e->getSourceRange();
14697   }
14698 };
14699 
14700 } // namespace
14701 
14702 /// Consider whether capturing the given variable can possibly lead to
14703 /// a retain cycle.
14704 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14705   // In ARC, it's captured strongly iff the variable has __strong
14706   // lifetime.  In MRR, it's captured strongly if the variable is
14707   // __block and has an appropriate type.
14708   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14709     return false;
14710 
14711   owner.Variable = var;
14712   if (ref)
14713     owner.setLocsFrom(ref);
14714   return true;
14715 }
14716 
14717 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14718   while (true) {
14719     e = e->IgnoreParens();
14720     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14721       switch (cast->getCastKind()) {
14722       case CK_BitCast:
14723       case CK_LValueBitCast:
14724       case CK_LValueToRValue:
14725       case CK_ARCReclaimReturnedObject:
14726         e = cast->getSubExpr();
14727         continue;
14728 
14729       default:
14730         return false;
14731       }
14732     }
14733 
14734     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14735       ObjCIvarDecl *ivar = ref->getDecl();
14736       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14737         return false;
14738 
14739       // Try to find a retain cycle in the base.
14740       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14741         return false;
14742 
14743       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14744       owner.Indirect = true;
14745       return true;
14746     }
14747 
14748     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14749       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14750       if (!var) return false;
14751       return considerVariable(var, ref, owner);
14752     }
14753 
14754     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14755       if (member->isArrow()) return false;
14756 
14757       // Don't count this as an indirect ownership.
14758       e = member->getBase();
14759       continue;
14760     }
14761 
14762     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14763       // Only pay attention to pseudo-objects on property references.
14764       ObjCPropertyRefExpr *pre
14765         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14766                                               ->IgnoreParens());
14767       if (!pre) return false;
14768       if (pre->isImplicitProperty()) return false;
14769       ObjCPropertyDecl *property = pre->getExplicitProperty();
14770       if (!property->isRetaining() &&
14771           !(property->getPropertyIvarDecl() &&
14772             property->getPropertyIvarDecl()->getType()
14773               .getObjCLifetime() == Qualifiers::OCL_Strong))
14774           return false;
14775 
14776       owner.Indirect = true;
14777       if (pre->isSuperReceiver()) {
14778         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14779         if (!owner.Variable)
14780           return false;
14781         owner.Loc = pre->getLocation();
14782         owner.Range = pre->getSourceRange();
14783         return true;
14784       }
14785       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14786                               ->getSourceExpr());
14787       continue;
14788     }
14789 
14790     // Array ivars?
14791 
14792     return false;
14793   }
14794 }
14795 
14796 namespace {
14797 
14798   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14799     ASTContext &Context;
14800     VarDecl *Variable;
14801     Expr *Capturer = nullptr;
14802     bool VarWillBeReased = false;
14803 
14804     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14805         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14806           Context(Context), Variable(variable) {}
14807 
14808     void VisitDeclRefExpr(DeclRefExpr *ref) {
14809       if (ref->getDecl() == Variable && !Capturer)
14810         Capturer = ref;
14811     }
14812 
14813     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14814       if (Capturer) return;
14815       Visit(ref->getBase());
14816       if (Capturer && ref->isFreeIvar())
14817         Capturer = ref;
14818     }
14819 
14820     void VisitBlockExpr(BlockExpr *block) {
14821       // Look inside nested blocks
14822       if (block->getBlockDecl()->capturesVariable(Variable))
14823         Visit(block->getBlockDecl()->getBody());
14824     }
14825 
14826     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14827       if (Capturer) return;
14828       if (OVE->getSourceExpr())
14829         Visit(OVE->getSourceExpr());
14830     }
14831 
14832     void VisitBinaryOperator(BinaryOperator *BinOp) {
14833       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14834         return;
14835       Expr *LHS = BinOp->getLHS();
14836       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14837         if (DRE->getDecl() != Variable)
14838           return;
14839         if (Expr *RHS = BinOp->getRHS()) {
14840           RHS = RHS->IgnoreParenCasts();
14841           Optional<llvm::APSInt> Value;
14842           VarWillBeReased =
14843               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14844                *Value == 0);
14845         }
14846       }
14847     }
14848   };
14849 
14850 } // namespace
14851 
14852 /// Check whether the given argument is a block which captures a
14853 /// variable.
14854 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14855   assert(owner.Variable && owner.Loc.isValid());
14856 
14857   e = e->IgnoreParenCasts();
14858 
14859   // Look through [^{...} copy] and Block_copy(^{...}).
14860   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14861     Selector Cmd = ME->getSelector();
14862     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14863       e = ME->getInstanceReceiver();
14864       if (!e)
14865         return nullptr;
14866       e = e->IgnoreParenCasts();
14867     }
14868   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14869     if (CE->getNumArgs() == 1) {
14870       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14871       if (Fn) {
14872         const IdentifierInfo *FnI = Fn->getIdentifier();
14873         if (FnI && FnI->isStr("_Block_copy")) {
14874           e = CE->getArg(0)->IgnoreParenCasts();
14875         }
14876       }
14877     }
14878   }
14879 
14880   BlockExpr *block = dyn_cast<BlockExpr>(e);
14881   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14882     return nullptr;
14883 
14884   FindCaptureVisitor visitor(S.Context, owner.Variable);
14885   visitor.Visit(block->getBlockDecl()->getBody());
14886   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14887 }
14888 
14889 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14890                                 RetainCycleOwner &owner) {
14891   assert(capturer);
14892   assert(owner.Variable && owner.Loc.isValid());
14893 
14894   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14895     << owner.Variable << capturer->getSourceRange();
14896   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14897     << owner.Indirect << owner.Range;
14898 }
14899 
14900 /// Check for a keyword selector that starts with the word 'add' or
14901 /// 'set'.
14902 static bool isSetterLikeSelector(Selector sel) {
14903   if (sel.isUnarySelector()) return false;
14904 
14905   StringRef str = sel.getNameForSlot(0);
14906   while (!str.empty() && str.front() == '_') str = str.substr(1);
14907   if (str.startswith("set"))
14908     str = str.substr(3);
14909   else if (str.startswith("add")) {
14910     // Specially allow 'addOperationWithBlock:'.
14911     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14912       return false;
14913     str = str.substr(3);
14914   }
14915   else
14916     return false;
14917 
14918   if (str.empty()) return true;
14919   return !isLowercase(str.front());
14920 }
14921 
14922 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14923                                                     ObjCMessageExpr *Message) {
14924   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14925                                                 Message->getReceiverInterface(),
14926                                                 NSAPI::ClassId_NSMutableArray);
14927   if (!IsMutableArray) {
14928     return None;
14929   }
14930 
14931   Selector Sel = Message->getSelector();
14932 
14933   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14934     S.NSAPIObj->getNSArrayMethodKind(Sel);
14935   if (!MKOpt) {
14936     return None;
14937   }
14938 
14939   NSAPI::NSArrayMethodKind MK = *MKOpt;
14940 
14941   switch (MK) {
14942     case NSAPI::NSMutableArr_addObject:
14943     case NSAPI::NSMutableArr_insertObjectAtIndex:
14944     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14945       return 0;
14946     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14947       return 1;
14948 
14949     default:
14950       return None;
14951   }
14952 
14953   return None;
14954 }
14955 
14956 static
14957 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14958                                                   ObjCMessageExpr *Message) {
14959   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14960                                             Message->getReceiverInterface(),
14961                                             NSAPI::ClassId_NSMutableDictionary);
14962   if (!IsMutableDictionary) {
14963     return None;
14964   }
14965 
14966   Selector Sel = Message->getSelector();
14967 
14968   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14969     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14970   if (!MKOpt) {
14971     return None;
14972   }
14973 
14974   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14975 
14976   switch (MK) {
14977     case NSAPI::NSMutableDict_setObjectForKey:
14978     case NSAPI::NSMutableDict_setValueForKey:
14979     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14980       return 0;
14981 
14982     default:
14983       return None;
14984   }
14985 
14986   return None;
14987 }
14988 
14989 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14990   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14991                                                 Message->getReceiverInterface(),
14992                                                 NSAPI::ClassId_NSMutableSet);
14993 
14994   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14995                                             Message->getReceiverInterface(),
14996                                             NSAPI::ClassId_NSMutableOrderedSet);
14997   if (!IsMutableSet && !IsMutableOrderedSet) {
14998     return None;
14999   }
15000 
15001   Selector Sel = Message->getSelector();
15002 
15003   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15004   if (!MKOpt) {
15005     return None;
15006   }
15007 
15008   NSAPI::NSSetMethodKind MK = *MKOpt;
15009 
15010   switch (MK) {
15011     case NSAPI::NSMutableSet_addObject:
15012     case NSAPI::NSOrderedSet_setObjectAtIndex:
15013     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15014     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15015       return 0;
15016     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15017       return 1;
15018   }
15019 
15020   return None;
15021 }
15022 
15023 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15024   if (!Message->isInstanceMessage()) {
15025     return;
15026   }
15027 
15028   Optional<int> ArgOpt;
15029 
15030   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15031       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15032       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15033     return;
15034   }
15035 
15036   int ArgIndex = *ArgOpt;
15037 
15038   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15039   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15040     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15041   }
15042 
15043   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15044     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15045       if (ArgRE->isObjCSelfExpr()) {
15046         Diag(Message->getSourceRange().getBegin(),
15047              diag::warn_objc_circular_container)
15048           << ArgRE->getDecl() << StringRef("'super'");
15049       }
15050     }
15051   } else {
15052     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15053 
15054     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15055       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15056     }
15057 
15058     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15059       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15060         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15061           ValueDecl *Decl = ReceiverRE->getDecl();
15062           Diag(Message->getSourceRange().getBegin(),
15063                diag::warn_objc_circular_container)
15064             << Decl << Decl;
15065           if (!ArgRE->isObjCSelfExpr()) {
15066             Diag(Decl->getLocation(),
15067                  diag::note_objc_circular_container_declared_here)
15068               << Decl;
15069           }
15070         }
15071       }
15072     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15073       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15074         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15075           ObjCIvarDecl *Decl = IvarRE->getDecl();
15076           Diag(Message->getSourceRange().getBegin(),
15077                diag::warn_objc_circular_container)
15078             << Decl << Decl;
15079           Diag(Decl->getLocation(),
15080                diag::note_objc_circular_container_declared_here)
15081             << Decl;
15082         }
15083       }
15084     }
15085   }
15086 }
15087 
15088 /// Check a message send to see if it's likely to cause a retain cycle.
15089 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15090   // Only check instance methods whose selector looks like a setter.
15091   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15092     return;
15093 
15094   // Try to find a variable that the receiver is strongly owned by.
15095   RetainCycleOwner owner;
15096   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15097     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15098       return;
15099   } else {
15100     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15101     owner.Variable = getCurMethodDecl()->getSelfDecl();
15102     owner.Loc = msg->getSuperLoc();
15103     owner.Range = msg->getSuperLoc();
15104   }
15105 
15106   // Check whether the receiver is captured by any of the arguments.
15107   const ObjCMethodDecl *MD = msg->getMethodDecl();
15108   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15109     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15110       // noescape blocks should not be retained by the method.
15111       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15112         continue;
15113       return diagnoseRetainCycle(*this, capturer, owner);
15114     }
15115   }
15116 }
15117 
15118 /// Check a property assign to see if it's likely to cause a retain cycle.
15119 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15120   RetainCycleOwner owner;
15121   if (!findRetainCycleOwner(*this, receiver, owner))
15122     return;
15123 
15124   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15125     diagnoseRetainCycle(*this, capturer, owner);
15126 }
15127 
15128 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15129   RetainCycleOwner Owner;
15130   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15131     return;
15132 
15133   // Because we don't have an expression for the variable, we have to set the
15134   // location explicitly here.
15135   Owner.Loc = Var->getLocation();
15136   Owner.Range = Var->getSourceRange();
15137 
15138   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15139     diagnoseRetainCycle(*this, Capturer, Owner);
15140 }
15141 
15142 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15143                                      Expr *RHS, bool isProperty) {
15144   // Check if RHS is an Objective-C object literal, which also can get
15145   // immediately zapped in a weak reference.  Note that we explicitly
15146   // allow ObjCStringLiterals, since those are designed to never really die.
15147   RHS = RHS->IgnoreParenImpCasts();
15148 
15149   // This enum needs to match with the 'select' in
15150   // warn_objc_arc_literal_assign (off-by-1).
15151   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15152   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15153     return false;
15154 
15155   S.Diag(Loc, diag::warn_arc_literal_assign)
15156     << (unsigned) Kind
15157     << (isProperty ? 0 : 1)
15158     << RHS->getSourceRange();
15159 
15160   return true;
15161 }
15162 
15163 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15164                                     Qualifiers::ObjCLifetime LT,
15165                                     Expr *RHS, bool isProperty) {
15166   // Strip off any implicit cast added to get to the one ARC-specific.
15167   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15168     if (cast->getCastKind() == CK_ARCConsumeObject) {
15169       S.Diag(Loc, diag::warn_arc_retained_assign)
15170         << (LT == Qualifiers::OCL_ExplicitNone)
15171         << (isProperty ? 0 : 1)
15172         << RHS->getSourceRange();
15173       return true;
15174     }
15175     RHS = cast->getSubExpr();
15176   }
15177 
15178   if (LT == Qualifiers::OCL_Weak &&
15179       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15180     return true;
15181 
15182   return false;
15183 }
15184 
15185 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15186                               QualType LHS, Expr *RHS) {
15187   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15188 
15189   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15190     return false;
15191 
15192   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15193     return true;
15194 
15195   return false;
15196 }
15197 
15198 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15199                               Expr *LHS, Expr *RHS) {
15200   QualType LHSType;
15201   // PropertyRef on LHS type need be directly obtained from
15202   // its declaration as it has a PseudoType.
15203   ObjCPropertyRefExpr *PRE
15204     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15205   if (PRE && !PRE->isImplicitProperty()) {
15206     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15207     if (PD)
15208       LHSType = PD->getType();
15209   }
15210 
15211   if (LHSType.isNull())
15212     LHSType = LHS->getType();
15213 
15214   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15215 
15216   if (LT == Qualifiers::OCL_Weak) {
15217     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15218       getCurFunction()->markSafeWeakUse(LHS);
15219   }
15220 
15221   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15222     return;
15223 
15224   // FIXME. Check for other life times.
15225   if (LT != Qualifiers::OCL_None)
15226     return;
15227 
15228   if (PRE) {
15229     if (PRE->isImplicitProperty())
15230       return;
15231     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15232     if (!PD)
15233       return;
15234 
15235     unsigned Attributes = PD->getPropertyAttributes();
15236     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15237       // when 'assign' attribute was not explicitly specified
15238       // by user, ignore it and rely on property type itself
15239       // for lifetime info.
15240       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15241       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15242           LHSType->isObjCRetainableType())
15243         return;
15244 
15245       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15246         if (cast->getCastKind() == CK_ARCConsumeObject) {
15247           Diag(Loc, diag::warn_arc_retained_property_assign)
15248           << RHS->getSourceRange();
15249           return;
15250         }
15251         RHS = cast->getSubExpr();
15252       }
15253     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15254       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15255         return;
15256     }
15257   }
15258 }
15259 
15260 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15261 
15262 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15263                                         SourceLocation StmtLoc,
15264                                         const NullStmt *Body) {
15265   // Do not warn if the body is a macro that expands to nothing, e.g:
15266   //
15267   // #define CALL(x)
15268   // if (condition)
15269   //   CALL(0);
15270   if (Body->hasLeadingEmptyMacro())
15271     return false;
15272 
15273   // Get line numbers of statement and body.
15274   bool StmtLineInvalid;
15275   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15276                                                       &StmtLineInvalid);
15277   if (StmtLineInvalid)
15278     return false;
15279 
15280   bool BodyLineInvalid;
15281   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15282                                                       &BodyLineInvalid);
15283   if (BodyLineInvalid)
15284     return false;
15285 
15286   // Warn if null statement and body are on the same line.
15287   if (StmtLine != BodyLine)
15288     return false;
15289 
15290   return true;
15291 }
15292 
15293 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15294                                  const Stmt *Body,
15295                                  unsigned DiagID) {
15296   // Since this is a syntactic check, don't emit diagnostic for template
15297   // instantiations, this just adds noise.
15298   if (CurrentInstantiationScope)
15299     return;
15300 
15301   // The body should be a null statement.
15302   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15303   if (!NBody)
15304     return;
15305 
15306   // Do the usual checks.
15307   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15308     return;
15309 
15310   Diag(NBody->getSemiLoc(), DiagID);
15311   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15312 }
15313 
15314 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15315                                  const Stmt *PossibleBody) {
15316   assert(!CurrentInstantiationScope); // Ensured by caller
15317 
15318   SourceLocation StmtLoc;
15319   const Stmt *Body;
15320   unsigned DiagID;
15321   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15322     StmtLoc = FS->getRParenLoc();
15323     Body = FS->getBody();
15324     DiagID = diag::warn_empty_for_body;
15325   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15326     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15327     Body = WS->getBody();
15328     DiagID = diag::warn_empty_while_body;
15329   } else
15330     return; // Neither `for' nor `while'.
15331 
15332   // The body should be a null statement.
15333   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15334   if (!NBody)
15335     return;
15336 
15337   // Skip expensive checks if diagnostic is disabled.
15338   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15339     return;
15340 
15341   // Do the usual checks.
15342   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15343     return;
15344 
15345   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15346   // noise level low, emit diagnostics only if for/while is followed by a
15347   // CompoundStmt, e.g.:
15348   //    for (int i = 0; i < n; i++);
15349   //    {
15350   //      a(i);
15351   //    }
15352   // or if for/while is followed by a statement with more indentation
15353   // than for/while itself:
15354   //    for (int i = 0; i < n; i++);
15355   //      a(i);
15356   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15357   if (!ProbableTypo) {
15358     bool BodyColInvalid;
15359     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15360         PossibleBody->getBeginLoc(), &BodyColInvalid);
15361     if (BodyColInvalid)
15362       return;
15363 
15364     bool StmtColInvalid;
15365     unsigned StmtCol =
15366         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15367     if (StmtColInvalid)
15368       return;
15369 
15370     if (BodyCol > StmtCol)
15371       ProbableTypo = true;
15372   }
15373 
15374   if (ProbableTypo) {
15375     Diag(NBody->getSemiLoc(), DiagID);
15376     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15377   }
15378 }
15379 
15380 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15381 
15382 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15383 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15384                              SourceLocation OpLoc) {
15385   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15386     return;
15387 
15388   if (inTemplateInstantiation())
15389     return;
15390 
15391   // Strip parens and casts away.
15392   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15393   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15394 
15395   // Check for a call expression
15396   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15397   if (!CE || CE->getNumArgs() != 1)
15398     return;
15399 
15400   // Check for a call to std::move
15401   if (!CE->isCallToStdMove())
15402     return;
15403 
15404   // Get argument from std::move
15405   RHSExpr = CE->getArg(0);
15406 
15407   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15408   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15409 
15410   // Two DeclRefExpr's, check that the decls are the same.
15411   if (LHSDeclRef && RHSDeclRef) {
15412     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15413       return;
15414     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15415         RHSDeclRef->getDecl()->getCanonicalDecl())
15416       return;
15417 
15418     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15419                                         << LHSExpr->getSourceRange()
15420                                         << RHSExpr->getSourceRange();
15421     return;
15422   }
15423 
15424   // Member variables require a different approach to check for self moves.
15425   // MemberExpr's are the same if every nested MemberExpr refers to the same
15426   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15427   // the base Expr's are CXXThisExpr's.
15428   const Expr *LHSBase = LHSExpr;
15429   const Expr *RHSBase = RHSExpr;
15430   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15431   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15432   if (!LHSME || !RHSME)
15433     return;
15434 
15435   while (LHSME && RHSME) {
15436     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15437         RHSME->getMemberDecl()->getCanonicalDecl())
15438       return;
15439 
15440     LHSBase = LHSME->getBase();
15441     RHSBase = RHSME->getBase();
15442     LHSME = dyn_cast<MemberExpr>(LHSBase);
15443     RHSME = dyn_cast<MemberExpr>(RHSBase);
15444   }
15445 
15446   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15447   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15448   if (LHSDeclRef && RHSDeclRef) {
15449     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15450       return;
15451     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15452         RHSDeclRef->getDecl()->getCanonicalDecl())
15453       return;
15454 
15455     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15456                                         << LHSExpr->getSourceRange()
15457                                         << RHSExpr->getSourceRange();
15458     return;
15459   }
15460 
15461   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15462     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15463                                         << LHSExpr->getSourceRange()
15464                                         << RHSExpr->getSourceRange();
15465 }
15466 
15467 //===--- Layout compatibility ----------------------------------------------//
15468 
15469 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15470 
15471 /// Check if two enumeration types are layout-compatible.
15472 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15473   // C++11 [dcl.enum] p8:
15474   // Two enumeration types are layout-compatible if they have the same
15475   // underlying type.
15476   return ED1->isComplete() && ED2->isComplete() &&
15477          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15478 }
15479 
15480 /// Check if two fields are layout-compatible.
15481 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15482                                FieldDecl *Field2) {
15483   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15484     return false;
15485 
15486   if (Field1->isBitField() != Field2->isBitField())
15487     return false;
15488 
15489   if (Field1->isBitField()) {
15490     // Make sure that the bit-fields are the same length.
15491     unsigned Bits1 = Field1->getBitWidthValue(C);
15492     unsigned Bits2 = Field2->getBitWidthValue(C);
15493 
15494     if (Bits1 != Bits2)
15495       return false;
15496   }
15497 
15498   return true;
15499 }
15500 
15501 /// Check if two standard-layout structs are layout-compatible.
15502 /// (C++11 [class.mem] p17)
15503 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15504                                      RecordDecl *RD2) {
15505   // If both records are C++ classes, check that base classes match.
15506   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15507     // If one of records is a CXXRecordDecl we are in C++ mode,
15508     // thus the other one is a CXXRecordDecl, too.
15509     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15510     // Check number of base classes.
15511     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15512       return false;
15513 
15514     // Check the base classes.
15515     for (CXXRecordDecl::base_class_const_iterator
15516                Base1 = D1CXX->bases_begin(),
15517            BaseEnd1 = D1CXX->bases_end(),
15518               Base2 = D2CXX->bases_begin();
15519          Base1 != BaseEnd1;
15520          ++Base1, ++Base2) {
15521       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15522         return false;
15523     }
15524   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15525     // If only RD2 is a C++ class, it should have zero base classes.
15526     if (D2CXX->getNumBases() > 0)
15527       return false;
15528   }
15529 
15530   // Check the fields.
15531   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15532                              Field2End = RD2->field_end(),
15533                              Field1 = RD1->field_begin(),
15534                              Field1End = RD1->field_end();
15535   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15536     if (!isLayoutCompatible(C, *Field1, *Field2))
15537       return false;
15538   }
15539   if (Field1 != Field1End || Field2 != Field2End)
15540     return false;
15541 
15542   return true;
15543 }
15544 
15545 /// Check if two standard-layout unions are layout-compatible.
15546 /// (C++11 [class.mem] p18)
15547 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15548                                     RecordDecl *RD2) {
15549   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15550   for (auto *Field2 : RD2->fields())
15551     UnmatchedFields.insert(Field2);
15552 
15553   for (auto *Field1 : RD1->fields()) {
15554     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15555         I = UnmatchedFields.begin(),
15556         E = UnmatchedFields.end();
15557 
15558     for ( ; I != E; ++I) {
15559       if (isLayoutCompatible(C, Field1, *I)) {
15560         bool Result = UnmatchedFields.erase(*I);
15561         (void) Result;
15562         assert(Result);
15563         break;
15564       }
15565     }
15566     if (I == E)
15567       return false;
15568   }
15569 
15570   return UnmatchedFields.empty();
15571 }
15572 
15573 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15574                                RecordDecl *RD2) {
15575   if (RD1->isUnion() != RD2->isUnion())
15576     return false;
15577 
15578   if (RD1->isUnion())
15579     return isLayoutCompatibleUnion(C, RD1, RD2);
15580   else
15581     return isLayoutCompatibleStruct(C, RD1, RD2);
15582 }
15583 
15584 /// Check if two types are layout-compatible in C++11 sense.
15585 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15586   if (T1.isNull() || T2.isNull())
15587     return false;
15588 
15589   // C++11 [basic.types] p11:
15590   // If two types T1 and T2 are the same type, then T1 and T2 are
15591   // layout-compatible types.
15592   if (C.hasSameType(T1, T2))
15593     return true;
15594 
15595   T1 = T1.getCanonicalType().getUnqualifiedType();
15596   T2 = T2.getCanonicalType().getUnqualifiedType();
15597 
15598   const Type::TypeClass TC1 = T1->getTypeClass();
15599   const Type::TypeClass TC2 = T2->getTypeClass();
15600 
15601   if (TC1 != TC2)
15602     return false;
15603 
15604   if (TC1 == Type::Enum) {
15605     return isLayoutCompatible(C,
15606                               cast<EnumType>(T1)->getDecl(),
15607                               cast<EnumType>(T2)->getDecl());
15608   } else if (TC1 == Type::Record) {
15609     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15610       return false;
15611 
15612     return isLayoutCompatible(C,
15613                               cast<RecordType>(T1)->getDecl(),
15614                               cast<RecordType>(T2)->getDecl());
15615   }
15616 
15617   return false;
15618 }
15619 
15620 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15621 
15622 /// Given a type tag expression find the type tag itself.
15623 ///
15624 /// \param TypeExpr Type tag expression, as it appears in user's code.
15625 ///
15626 /// \param VD Declaration of an identifier that appears in a type tag.
15627 ///
15628 /// \param MagicValue Type tag magic value.
15629 ///
15630 /// \param isConstantEvaluated wether the evalaution should be performed in
15631 
15632 /// constant context.
15633 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15634                             const ValueDecl **VD, uint64_t *MagicValue,
15635                             bool isConstantEvaluated) {
15636   while(true) {
15637     if (!TypeExpr)
15638       return false;
15639 
15640     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15641 
15642     switch (TypeExpr->getStmtClass()) {
15643     case Stmt::UnaryOperatorClass: {
15644       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15645       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15646         TypeExpr = UO->getSubExpr();
15647         continue;
15648       }
15649       return false;
15650     }
15651 
15652     case Stmt::DeclRefExprClass: {
15653       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15654       *VD = DRE->getDecl();
15655       return true;
15656     }
15657 
15658     case Stmt::IntegerLiteralClass: {
15659       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15660       llvm::APInt MagicValueAPInt = IL->getValue();
15661       if (MagicValueAPInt.getActiveBits() <= 64) {
15662         *MagicValue = MagicValueAPInt.getZExtValue();
15663         return true;
15664       } else
15665         return false;
15666     }
15667 
15668     case Stmt::BinaryConditionalOperatorClass:
15669     case Stmt::ConditionalOperatorClass: {
15670       const AbstractConditionalOperator *ACO =
15671           cast<AbstractConditionalOperator>(TypeExpr);
15672       bool Result;
15673       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15674                                                      isConstantEvaluated)) {
15675         if (Result)
15676           TypeExpr = ACO->getTrueExpr();
15677         else
15678           TypeExpr = ACO->getFalseExpr();
15679         continue;
15680       }
15681       return false;
15682     }
15683 
15684     case Stmt::BinaryOperatorClass: {
15685       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15686       if (BO->getOpcode() == BO_Comma) {
15687         TypeExpr = BO->getRHS();
15688         continue;
15689       }
15690       return false;
15691     }
15692 
15693     default:
15694       return false;
15695     }
15696   }
15697 }
15698 
15699 /// Retrieve the C type corresponding to type tag TypeExpr.
15700 ///
15701 /// \param TypeExpr Expression that specifies a type tag.
15702 ///
15703 /// \param MagicValues Registered magic values.
15704 ///
15705 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15706 ///        kind.
15707 ///
15708 /// \param TypeInfo Information about the corresponding C type.
15709 ///
15710 /// \param isConstantEvaluated wether the evalaution should be performed in
15711 /// constant context.
15712 ///
15713 /// \returns true if the corresponding C type was found.
15714 static bool GetMatchingCType(
15715     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15716     const ASTContext &Ctx,
15717     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15718         *MagicValues,
15719     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15720     bool isConstantEvaluated) {
15721   FoundWrongKind = false;
15722 
15723   // Variable declaration that has type_tag_for_datatype attribute.
15724   const ValueDecl *VD = nullptr;
15725 
15726   uint64_t MagicValue;
15727 
15728   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15729     return false;
15730 
15731   if (VD) {
15732     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15733       if (I->getArgumentKind() != ArgumentKind) {
15734         FoundWrongKind = true;
15735         return false;
15736       }
15737       TypeInfo.Type = I->getMatchingCType();
15738       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15739       TypeInfo.MustBeNull = I->getMustBeNull();
15740       return true;
15741     }
15742     return false;
15743   }
15744 
15745   if (!MagicValues)
15746     return false;
15747 
15748   llvm::DenseMap<Sema::TypeTagMagicValue,
15749                  Sema::TypeTagData>::const_iterator I =
15750       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15751   if (I == MagicValues->end())
15752     return false;
15753 
15754   TypeInfo = I->second;
15755   return true;
15756 }
15757 
15758 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15759                                       uint64_t MagicValue, QualType Type,
15760                                       bool LayoutCompatible,
15761                                       bool MustBeNull) {
15762   if (!TypeTagForDatatypeMagicValues)
15763     TypeTagForDatatypeMagicValues.reset(
15764         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15765 
15766   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15767   (*TypeTagForDatatypeMagicValues)[Magic] =
15768       TypeTagData(Type, LayoutCompatible, MustBeNull);
15769 }
15770 
15771 static bool IsSameCharType(QualType T1, QualType T2) {
15772   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15773   if (!BT1)
15774     return false;
15775 
15776   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15777   if (!BT2)
15778     return false;
15779 
15780   BuiltinType::Kind T1Kind = BT1->getKind();
15781   BuiltinType::Kind T2Kind = BT2->getKind();
15782 
15783   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15784          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15785          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15786          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15787 }
15788 
15789 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15790                                     const ArrayRef<const Expr *> ExprArgs,
15791                                     SourceLocation CallSiteLoc) {
15792   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15793   bool IsPointerAttr = Attr->getIsPointer();
15794 
15795   // Retrieve the argument representing the 'type_tag'.
15796   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15797   if (TypeTagIdxAST >= ExprArgs.size()) {
15798     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15799         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15800     return;
15801   }
15802   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15803   bool FoundWrongKind;
15804   TypeTagData TypeInfo;
15805   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15806                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15807                         TypeInfo, isConstantEvaluated())) {
15808     if (FoundWrongKind)
15809       Diag(TypeTagExpr->getExprLoc(),
15810            diag::warn_type_tag_for_datatype_wrong_kind)
15811         << TypeTagExpr->getSourceRange();
15812     return;
15813   }
15814 
15815   // Retrieve the argument representing the 'arg_idx'.
15816   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15817   if (ArgumentIdxAST >= ExprArgs.size()) {
15818     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15819         << 1 << Attr->getArgumentIdx().getSourceIndex();
15820     return;
15821   }
15822   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15823   if (IsPointerAttr) {
15824     // Skip implicit cast of pointer to `void *' (as a function argument).
15825     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15826       if (ICE->getType()->isVoidPointerType() &&
15827           ICE->getCastKind() == CK_BitCast)
15828         ArgumentExpr = ICE->getSubExpr();
15829   }
15830   QualType ArgumentType = ArgumentExpr->getType();
15831 
15832   // Passing a `void*' pointer shouldn't trigger a warning.
15833   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15834     return;
15835 
15836   if (TypeInfo.MustBeNull) {
15837     // Type tag with matching void type requires a null pointer.
15838     if (!ArgumentExpr->isNullPointerConstant(Context,
15839                                              Expr::NPC_ValueDependentIsNotNull)) {
15840       Diag(ArgumentExpr->getExprLoc(),
15841            diag::warn_type_safety_null_pointer_required)
15842           << ArgumentKind->getName()
15843           << ArgumentExpr->getSourceRange()
15844           << TypeTagExpr->getSourceRange();
15845     }
15846     return;
15847   }
15848 
15849   QualType RequiredType = TypeInfo.Type;
15850   if (IsPointerAttr)
15851     RequiredType = Context.getPointerType(RequiredType);
15852 
15853   bool mismatch = false;
15854   if (!TypeInfo.LayoutCompatible) {
15855     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15856 
15857     // C++11 [basic.fundamental] p1:
15858     // Plain char, signed char, and unsigned char are three distinct types.
15859     //
15860     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15861     // char' depending on the current char signedness mode.
15862     if (mismatch)
15863       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15864                                            RequiredType->getPointeeType())) ||
15865           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15866         mismatch = false;
15867   } else
15868     if (IsPointerAttr)
15869       mismatch = !isLayoutCompatible(Context,
15870                                      ArgumentType->getPointeeType(),
15871                                      RequiredType->getPointeeType());
15872     else
15873       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15874 
15875   if (mismatch)
15876     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15877         << ArgumentType << ArgumentKind
15878         << TypeInfo.LayoutCompatible << RequiredType
15879         << ArgumentExpr->getSourceRange()
15880         << TypeTagExpr->getSourceRange();
15881 }
15882 
15883 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15884                                          CharUnits Alignment) {
15885   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15886 }
15887 
15888 void Sema::DiagnoseMisalignedMembers() {
15889   for (MisalignedMember &m : MisalignedMembers) {
15890     const NamedDecl *ND = m.RD;
15891     if (ND->getName().empty()) {
15892       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15893         ND = TD;
15894     }
15895     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15896         << m.MD << ND << m.E->getSourceRange();
15897   }
15898   MisalignedMembers.clear();
15899 }
15900 
15901 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15902   E = E->IgnoreParens();
15903   if (!T->isPointerType() && !T->isIntegerType())
15904     return;
15905   if (isa<UnaryOperator>(E) &&
15906       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15907     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15908     if (isa<MemberExpr>(Op)) {
15909       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15910       if (MA != MisalignedMembers.end() &&
15911           (T->isIntegerType() ||
15912            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15913                                    Context.getTypeAlignInChars(
15914                                        T->getPointeeType()) <= MA->Alignment))))
15915         MisalignedMembers.erase(MA);
15916     }
15917   }
15918 }
15919 
15920 void Sema::RefersToMemberWithReducedAlignment(
15921     Expr *E,
15922     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15923         Action) {
15924   const auto *ME = dyn_cast<MemberExpr>(E);
15925   if (!ME)
15926     return;
15927 
15928   // No need to check expressions with an __unaligned-qualified type.
15929   if (E->getType().getQualifiers().hasUnaligned())
15930     return;
15931 
15932   // For a chain of MemberExpr like "a.b.c.d" this list
15933   // will keep FieldDecl's like [d, c, b].
15934   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15935   const MemberExpr *TopME = nullptr;
15936   bool AnyIsPacked = false;
15937   do {
15938     QualType BaseType = ME->getBase()->getType();
15939     if (BaseType->isDependentType())
15940       return;
15941     if (ME->isArrow())
15942       BaseType = BaseType->getPointeeType();
15943     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15944     if (RD->isInvalidDecl())
15945       return;
15946 
15947     ValueDecl *MD = ME->getMemberDecl();
15948     auto *FD = dyn_cast<FieldDecl>(MD);
15949     // We do not care about non-data members.
15950     if (!FD || FD->isInvalidDecl())
15951       return;
15952 
15953     AnyIsPacked =
15954         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15955     ReverseMemberChain.push_back(FD);
15956 
15957     TopME = ME;
15958     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15959   } while (ME);
15960   assert(TopME && "We did not compute a topmost MemberExpr!");
15961 
15962   // Not the scope of this diagnostic.
15963   if (!AnyIsPacked)
15964     return;
15965 
15966   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15967   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15968   // TODO: The innermost base of the member expression may be too complicated.
15969   // For now, just disregard these cases. This is left for future
15970   // improvement.
15971   if (!DRE && !isa<CXXThisExpr>(TopBase))
15972       return;
15973 
15974   // Alignment expected by the whole expression.
15975   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15976 
15977   // No need to do anything else with this case.
15978   if (ExpectedAlignment.isOne())
15979     return;
15980 
15981   // Synthesize offset of the whole access.
15982   CharUnits Offset;
15983   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15984        I++) {
15985     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15986   }
15987 
15988   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15989   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15990       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15991 
15992   // The base expression of the innermost MemberExpr may give
15993   // stronger guarantees than the class containing the member.
15994   if (DRE && !TopME->isArrow()) {
15995     const ValueDecl *VD = DRE->getDecl();
15996     if (!VD->getType()->isReferenceType())
15997       CompleteObjectAlignment =
15998           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15999   }
16000 
16001   // Check if the synthesized offset fulfills the alignment.
16002   if (Offset % ExpectedAlignment != 0 ||
16003       // It may fulfill the offset it but the effective alignment may still be
16004       // lower than the expected expression alignment.
16005       CompleteObjectAlignment < ExpectedAlignment) {
16006     // If this happens, we want to determine a sensible culprit of this.
16007     // Intuitively, watching the chain of member expressions from right to
16008     // left, we start with the required alignment (as required by the field
16009     // type) but some packed attribute in that chain has reduced the alignment.
16010     // It may happen that another packed structure increases it again. But if
16011     // we are here such increase has not been enough. So pointing the first
16012     // FieldDecl that either is packed or else its RecordDecl is,
16013     // seems reasonable.
16014     FieldDecl *FD = nullptr;
16015     CharUnits Alignment;
16016     for (FieldDecl *FDI : ReverseMemberChain) {
16017       if (FDI->hasAttr<PackedAttr>() ||
16018           FDI->getParent()->hasAttr<PackedAttr>()) {
16019         FD = FDI;
16020         Alignment = std::min(
16021             Context.getTypeAlignInChars(FD->getType()),
16022             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16023         break;
16024       }
16025     }
16026     assert(FD && "We did not find a packed FieldDecl!");
16027     Action(E, FD->getParent(), FD, Alignment);
16028   }
16029 }
16030 
16031 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16032   using namespace std::placeholders;
16033 
16034   RefersToMemberWithReducedAlignment(
16035       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16036                      _2, _3, _4));
16037 }
16038 
16039 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16040                                             ExprResult CallResult) {
16041   if (checkArgCount(*this, TheCall, 1))
16042     return ExprError();
16043 
16044   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16045   if (MatrixArg.isInvalid())
16046     return MatrixArg;
16047   Expr *Matrix = MatrixArg.get();
16048 
16049   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16050   if (!MType) {
16051     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16052     return ExprError();
16053   }
16054 
16055   // Create returned matrix type by swapping rows and columns of the argument
16056   // matrix type.
16057   QualType ResultType = Context.getConstantMatrixType(
16058       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16059 
16060   // Change the return type to the type of the returned matrix.
16061   TheCall->setType(ResultType);
16062 
16063   // Update call argument to use the possibly converted matrix argument.
16064   TheCall->setArg(0, Matrix);
16065   return CallResult;
16066 }
16067 
16068 // Get and verify the matrix dimensions.
16069 static llvm::Optional<unsigned>
16070 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16071   SourceLocation ErrorPos;
16072   Optional<llvm::APSInt> Value =
16073       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16074   if (!Value) {
16075     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16076         << Name;
16077     return {};
16078   }
16079   uint64_t Dim = Value->getZExtValue();
16080   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16081     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16082         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16083     return {};
16084   }
16085   return Dim;
16086 }
16087 
16088 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16089                                                   ExprResult CallResult) {
16090   if (!getLangOpts().MatrixTypes) {
16091     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16092     return ExprError();
16093   }
16094 
16095   if (checkArgCount(*this, TheCall, 4))
16096     return ExprError();
16097 
16098   unsigned PtrArgIdx = 0;
16099   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16100   Expr *RowsExpr = TheCall->getArg(1);
16101   Expr *ColumnsExpr = TheCall->getArg(2);
16102   Expr *StrideExpr = TheCall->getArg(3);
16103 
16104   bool ArgError = false;
16105 
16106   // Check pointer argument.
16107   {
16108     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16109     if (PtrConv.isInvalid())
16110       return PtrConv;
16111     PtrExpr = PtrConv.get();
16112     TheCall->setArg(0, PtrExpr);
16113     if (PtrExpr->isTypeDependent()) {
16114       TheCall->setType(Context.DependentTy);
16115       return TheCall;
16116     }
16117   }
16118 
16119   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16120   QualType ElementTy;
16121   if (!PtrTy) {
16122     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16123         << PtrArgIdx + 1;
16124     ArgError = true;
16125   } else {
16126     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16127 
16128     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16129       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16130           << PtrArgIdx + 1;
16131       ArgError = true;
16132     }
16133   }
16134 
16135   // Apply default Lvalue conversions and convert the expression to size_t.
16136   auto ApplyArgumentConversions = [this](Expr *E) {
16137     ExprResult Conv = DefaultLvalueConversion(E);
16138     if (Conv.isInvalid())
16139       return Conv;
16140 
16141     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16142   };
16143 
16144   // Apply conversion to row and column expressions.
16145   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16146   if (!RowsConv.isInvalid()) {
16147     RowsExpr = RowsConv.get();
16148     TheCall->setArg(1, RowsExpr);
16149   } else
16150     RowsExpr = nullptr;
16151 
16152   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16153   if (!ColumnsConv.isInvalid()) {
16154     ColumnsExpr = ColumnsConv.get();
16155     TheCall->setArg(2, ColumnsExpr);
16156   } else
16157     ColumnsExpr = nullptr;
16158 
16159   // If any any part of the result matrix type is still pending, just use
16160   // Context.DependentTy, until all parts are resolved.
16161   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16162       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16163     TheCall->setType(Context.DependentTy);
16164     return CallResult;
16165   }
16166 
16167   // Check row and column dimenions.
16168   llvm::Optional<unsigned> MaybeRows;
16169   if (RowsExpr)
16170     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16171 
16172   llvm::Optional<unsigned> MaybeColumns;
16173   if (ColumnsExpr)
16174     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16175 
16176   // Check stride argument.
16177   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16178   if (StrideConv.isInvalid())
16179     return ExprError();
16180   StrideExpr = StrideConv.get();
16181   TheCall->setArg(3, StrideExpr);
16182 
16183   if (MaybeRows) {
16184     if (Optional<llvm::APSInt> Value =
16185             StrideExpr->getIntegerConstantExpr(Context)) {
16186       uint64_t Stride = Value->getZExtValue();
16187       if (Stride < *MaybeRows) {
16188         Diag(StrideExpr->getBeginLoc(),
16189              diag::err_builtin_matrix_stride_too_small);
16190         ArgError = true;
16191       }
16192     }
16193   }
16194 
16195   if (ArgError || !MaybeRows || !MaybeColumns)
16196     return ExprError();
16197 
16198   TheCall->setType(
16199       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16200   return CallResult;
16201 }
16202 
16203 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16204                                                    ExprResult CallResult) {
16205   if (checkArgCount(*this, TheCall, 3))
16206     return ExprError();
16207 
16208   unsigned PtrArgIdx = 1;
16209   Expr *MatrixExpr = TheCall->getArg(0);
16210   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16211   Expr *StrideExpr = TheCall->getArg(2);
16212 
16213   bool ArgError = false;
16214 
16215   {
16216     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16217     if (MatrixConv.isInvalid())
16218       return MatrixConv;
16219     MatrixExpr = MatrixConv.get();
16220     TheCall->setArg(0, MatrixExpr);
16221   }
16222   if (MatrixExpr->isTypeDependent()) {
16223     TheCall->setType(Context.DependentTy);
16224     return TheCall;
16225   }
16226 
16227   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16228   if (!MatrixTy) {
16229     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16230     ArgError = true;
16231   }
16232 
16233   {
16234     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16235     if (PtrConv.isInvalid())
16236       return PtrConv;
16237     PtrExpr = PtrConv.get();
16238     TheCall->setArg(1, PtrExpr);
16239     if (PtrExpr->isTypeDependent()) {
16240       TheCall->setType(Context.DependentTy);
16241       return TheCall;
16242     }
16243   }
16244 
16245   // Check pointer argument.
16246   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16247   if (!PtrTy) {
16248     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16249         << PtrArgIdx + 1;
16250     ArgError = true;
16251   } else {
16252     QualType ElementTy = PtrTy->getPointeeType();
16253     if (ElementTy.isConstQualified()) {
16254       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16255       ArgError = true;
16256     }
16257     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16258     if (MatrixTy &&
16259         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16260       Diag(PtrExpr->getBeginLoc(),
16261            diag::err_builtin_matrix_pointer_arg_mismatch)
16262           << ElementTy << MatrixTy->getElementType();
16263       ArgError = true;
16264     }
16265   }
16266 
16267   // Apply default Lvalue conversions and convert the stride expression to
16268   // size_t.
16269   {
16270     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16271     if (StrideConv.isInvalid())
16272       return StrideConv;
16273 
16274     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16275     if (StrideConv.isInvalid())
16276       return StrideConv;
16277     StrideExpr = StrideConv.get();
16278     TheCall->setArg(2, StrideExpr);
16279   }
16280 
16281   // Check stride argument.
16282   if (MatrixTy) {
16283     if (Optional<llvm::APSInt> Value =
16284             StrideExpr->getIntegerConstantExpr(Context)) {
16285       uint64_t Stride = Value->getZExtValue();
16286       if (Stride < MatrixTy->getNumRows()) {
16287         Diag(StrideExpr->getBeginLoc(),
16288              diag::err_builtin_matrix_stride_too_small);
16289         ArgError = true;
16290       }
16291     }
16292   }
16293 
16294   if (ArgError)
16295     return ExprError();
16296 
16297   return CallResult;
16298 }
16299 
16300 /// \brief Enforce the bounds of a TCB
16301 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16302 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16303 /// and enforce_tcb_leaf attributes.
16304 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16305                                const FunctionDecl *Callee) {
16306   const FunctionDecl *Caller = getCurFunctionDecl();
16307 
16308   // Calls to builtins are not enforced.
16309   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16310       Callee->getBuiltinID() != 0)
16311     return;
16312 
16313   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16314   // all TCBs the callee is a part of.
16315   llvm::StringSet<> CalleeTCBs;
16316   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16317            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16318   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16319            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16320 
16321   // Go through the TCBs the caller is a part of and emit warnings if Caller
16322   // is in a TCB that the Callee is not.
16323   for_each(
16324       Caller->specific_attrs<EnforceTCBAttr>(),
16325       [&](const auto *A) {
16326         StringRef CallerTCB = A->getTCBName();
16327         if (CalleeTCBs.count(CallerTCB) == 0) {
16328           this->Diag(TheCall->getExprLoc(),
16329                      diag::warn_tcb_enforcement_violation) << Callee
16330                                                            << CallerTCB;
16331         }
16332       });
16333 }
16334