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           << toString(MaxValue, 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 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
592                                                CallExpr *TheCall) {
593   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
594       isConstantEvaluated())
595     return;
596 
597   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
598   if (!BuiltinID)
599     return;
600 
601   const TargetInfo &TI = getASTContext().getTargetInfo();
602   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
603 
604   auto ComputeExplicitObjectSizeArgument =
605       [&](unsigned Index) -> Optional<llvm::APSInt> {
606     Expr::EvalResult Result;
607     Expr *SizeArg = TheCall->getArg(Index);
608     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
609       return llvm::None;
610     return Result.Val.getInt();
611   };
612 
613   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
614     // If the parameter has a pass_object_size attribute, then we should use its
615     // (potentially) more strict checking mode. Otherwise, conservatively assume
616     // type 0.
617     int BOSType = 0;
618     if (const auto *POS =
619             FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
620       BOSType = POS->getType();
621 
622     const Expr *ObjArg = TheCall->getArg(Index);
623     uint64_t Result;
624     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
625       return llvm::None;
626 
627     // Get the object size in the target's size_t width.
628     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
629   };
630 
631   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
632     Expr *ObjArg = TheCall->getArg(Index);
633     uint64_t Result;
634     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
635       return llvm::None;
636     // Add 1 for null byte.
637     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
638   };
639 
640   Optional<llvm::APSInt> SourceSize;
641   Optional<llvm::APSInt> DestinationSize;
642   unsigned DiagID = 0;
643   bool IsChkVariant = false;
644 
645   switch (BuiltinID) {
646   default:
647     return;
648   case Builtin::BI__builtin_strcpy:
649   case Builtin::BIstrcpy: {
650     DiagID = diag::warn_fortify_strlen_overflow;
651     SourceSize = ComputeStrLenArgument(1);
652     DestinationSize = ComputeSizeArgument(0);
653     break;
654   }
655 
656   case Builtin::BI__builtin___strcpy_chk: {
657     DiagID = diag::warn_fortify_strlen_overflow;
658     SourceSize = ComputeStrLenArgument(1);
659     DestinationSize = ComputeExplicitObjectSizeArgument(2);
660     IsChkVariant = true;
661     break;
662   }
663 
664   case Builtin::BIsprintf:
665   case Builtin::BI__builtin___sprintf_chk: {
666     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
667     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
668 
669     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
670 
671       if (!Format->isAscii() && !Format->isUTF8())
672         return;
673 
674       StringRef FormatStrRef = Format->getString();
675       EstimateSizeFormatHandler H(FormatStrRef);
676       const char *FormatBytes = FormatStrRef.data();
677       const ConstantArrayType *T =
678           Context.getAsConstantArrayType(Format->getType());
679       assert(T && "String literal not of constant array type!");
680       size_t TypeSize = T->getSize().getZExtValue();
681 
682       // In case there's a null byte somewhere.
683       size_t StrLen =
684           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
685       if (!analyze_format_string::ParsePrintfString(
686               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
687               Context.getTargetInfo(), false)) {
688         DiagID = diag::warn_fortify_source_format_overflow;
689         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
690                          .extOrTrunc(SizeTypeWidth);
691         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
692           DestinationSize = ComputeExplicitObjectSizeArgument(2);
693           IsChkVariant = true;
694         } else {
695           DestinationSize = ComputeSizeArgument(0);
696         }
697         break;
698       }
699     }
700     return;
701   }
702   case Builtin::BI__builtin___memcpy_chk:
703   case Builtin::BI__builtin___memmove_chk:
704   case Builtin::BI__builtin___memset_chk:
705   case Builtin::BI__builtin___strlcat_chk:
706   case Builtin::BI__builtin___strlcpy_chk:
707   case Builtin::BI__builtin___strncat_chk:
708   case Builtin::BI__builtin___strncpy_chk:
709   case Builtin::BI__builtin___stpncpy_chk:
710   case Builtin::BI__builtin___memccpy_chk:
711   case Builtin::BI__builtin___mempcpy_chk: {
712     DiagID = diag::warn_builtin_chk_overflow;
713     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
714     DestinationSize =
715         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
716     IsChkVariant = true;
717     break;
718   }
719 
720   case Builtin::BI__builtin___snprintf_chk:
721   case Builtin::BI__builtin___vsnprintf_chk: {
722     DiagID = diag::warn_builtin_chk_overflow;
723     SourceSize = ComputeExplicitObjectSizeArgument(1);
724     DestinationSize = ComputeExplicitObjectSizeArgument(3);
725     IsChkVariant = true;
726     break;
727   }
728 
729   case Builtin::BIstrncat:
730   case Builtin::BI__builtin_strncat:
731   case Builtin::BIstrncpy:
732   case Builtin::BI__builtin_strncpy:
733   case Builtin::BIstpncpy:
734   case Builtin::BI__builtin_stpncpy: {
735     // Whether these functions overflow depends on the runtime strlen of the
736     // string, not just the buffer size, so emitting the "always overflow"
737     // diagnostic isn't quite right. We should still diagnose passing a buffer
738     // size larger than the destination buffer though; this is a runtime abort
739     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
740     DiagID = diag::warn_fortify_source_size_mismatch;
741     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
742     DestinationSize = ComputeSizeArgument(0);
743     break;
744   }
745 
746   case Builtin::BImemcpy:
747   case Builtin::BI__builtin_memcpy:
748   case Builtin::BImemmove:
749   case Builtin::BI__builtin_memmove:
750   case Builtin::BImemset:
751   case Builtin::BI__builtin_memset:
752   case Builtin::BImempcpy:
753   case Builtin::BI__builtin_mempcpy: {
754     DiagID = diag::warn_fortify_source_overflow;
755     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
756     DestinationSize = ComputeSizeArgument(0);
757     break;
758   }
759   case Builtin::BIsnprintf:
760   case Builtin::BI__builtin_snprintf:
761   case Builtin::BIvsnprintf:
762   case Builtin::BI__builtin_vsnprintf: {
763     DiagID = diag::warn_fortify_source_size_mismatch;
764     SourceSize = ComputeExplicitObjectSizeArgument(1);
765     DestinationSize = ComputeSizeArgument(0);
766     break;
767   }
768   }
769 
770   if (!SourceSize || !DestinationSize ||
771       SourceSize.getValue().ule(DestinationSize.getValue()))
772     return;
773 
774   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
775   // Skim off the details of whichever builtin was called to produce a better
776   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
777   if (IsChkVariant) {
778     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
779     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
780   } else if (FunctionName.startswith("__builtin_")) {
781     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
782   }
783 
784   SmallString<16> DestinationStr;
785   SmallString<16> SourceStr;
786   DestinationSize->toString(DestinationStr, /*Radix=*/10);
787   SourceSize->toString(SourceStr, /*Radix=*/10);
788   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
789                       PDiag(DiagID)
790                           << FunctionName << DestinationStr << SourceStr);
791 }
792 
793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
794                                      Scope::ScopeFlags NeededScopeFlags,
795                                      unsigned DiagID) {
796   // Scopes aren't available during instantiation. Fortunately, builtin
797   // functions cannot be template args so they cannot be formed through template
798   // instantiation. Therefore checking once during the parse is sufficient.
799   if (SemaRef.inTemplateInstantiation())
800     return false;
801 
802   Scope *S = SemaRef.getCurScope();
803   while (S && !S->isSEHExceptScope())
804     S = S->getParent();
805   if (!S || !(S->getFlags() & NeededScopeFlags)) {
806     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
807     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
808         << DRE->getDecl()->getIdentifier();
809     return true;
810   }
811 
812   return false;
813 }
814 
815 static inline bool isBlockPointer(Expr *Arg) {
816   return Arg->getType()->isBlockPointerType();
817 }
818 
819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
820 /// void*, which is a requirement of device side enqueue.
821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
822   const BlockPointerType *BPT =
823       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
824   ArrayRef<QualType> Params =
825       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
826   unsigned ArgCounter = 0;
827   bool IllegalParams = false;
828   // Iterate through the block parameters until either one is found that is not
829   // a local void*, or the block is valid.
830   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
831        I != E; ++I, ++ArgCounter) {
832     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
833         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
834             LangAS::opencl_local) {
835       // Get the location of the error. If a block literal has been passed
836       // (BlockExpr) then we can point straight to the offending argument,
837       // else we just point to the variable reference.
838       SourceLocation ErrorLoc;
839       if (isa<BlockExpr>(BlockArg)) {
840         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
841         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
842       } else if (isa<DeclRefExpr>(BlockArg)) {
843         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
844       }
845       S.Diag(ErrorLoc,
846              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
847       IllegalParams = true;
848     }
849   }
850 
851   return IllegalParams;
852 }
853 
854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
855   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
856     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
857         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
858     return true;
859   }
860   return false;
861 }
862 
863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
864   if (checkArgCount(S, TheCall, 2))
865     return true;
866 
867   if (checkOpenCLSubgroupExt(S, TheCall))
868     return true;
869 
870   // First argument is an ndrange_t type.
871   Expr *NDRangeArg = TheCall->getArg(0);
872   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
873     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
874         << TheCall->getDirectCallee() << "'ndrange_t'";
875     return true;
876   }
877 
878   Expr *BlockArg = TheCall->getArg(1);
879   if (!isBlockPointer(BlockArg)) {
880     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
881         << TheCall->getDirectCallee() << "block";
882     return true;
883   }
884   return checkOpenCLBlockArgs(S, BlockArg);
885 }
886 
887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
888 /// get_kernel_work_group_size
889 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
891   if (checkArgCount(S, TheCall, 1))
892     return true;
893 
894   Expr *BlockArg = TheCall->getArg(0);
895   if (!isBlockPointer(BlockArg)) {
896     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
897         << TheCall->getDirectCallee() << "block";
898     return true;
899   }
900   return checkOpenCLBlockArgs(S, BlockArg);
901 }
902 
903 /// Diagnose integer type and any valid implicit conversion to it.
904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
905                                       const QualType &IntType);
906 
907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
908                                             unsigned Start, unsigned End) {
909   bool IllegalParams = false;
910   for (unsigned I = Start; I <= End; ++I)
911     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
912                                               S.Context.getSizeType());
913   return IllegalParams;
914 }
915 
916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
917 /// 'local void*' parameter of passed block.
918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
919                                            Expr *BlockArg,
920                                            unsigned NumNonVarArgs) {
921   const BlockPointerType *BPT =
922       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
923   unsigned NumBlockParams =
924       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
925   unsigned TotalNumArgs = TheCall->getNumArgs();
926 
927   // For each argument passed to the block, a corresponding uint needs to
928   // be passed to describe the size of the local memory.
929   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
930     S.Diag(TheCall->getBeginLoc(),
931            diag::err_opencl_enqueue_kernel_local_size_args);
932     return true;
933   }
934 
935   // Check that the sizes of the local memory are specified by integers.
936   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
937                                          TotalNumArgs - 1);
938 }
939 
940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
941 /// overload formats specified in Table 6.13.17.1.
942 /// int enqueue_kernel(queue_t queue,
943 ///                    kernel_enqueue_flags_t flags,
944 ///                    const ndrange_t ndrange,
945 ///                    void (^block)(void))
946 /// int enqueue_kernel(queue_t queue,
947 ///                    kernel_enqueue_flags_t flags,
948 ///                    const ndrange_t ndrange,
949 ///                    uint num_events_in_wait_list,
950 ///                    clk_event_t *event_wait_list,
951 ///                    clk_event_t *event_ret,
952 ///                    void (^block)(void))
953 /// int enqueue_kernel(queue_t queue,
954 ///                    kernel_enqueue_flags_t flags,
955 ///                    const ndrange_t ndrange,
956 ///                    void (^block)(local void*, ...),
957 ///                    uint size0, ...)
958 /// int enqueue_kernel(queue_t queue,
959 ///                    kernel_enqueue_flags_t flags,
960 ///                    const ndrange_t ndrange,
961 ///                    uint num_events_in_wait_list,
962 ///                    clk_event_t *event_wait_list,
963 ///                    clk_event_t *event_ret,
964 ///                    void (^block)(local void*, ...),
965 ///                    uint size0, ...)
966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
967   unsigned NumArgs = TheCall->getNumArgs();
968 
969   if (NumArgs < 4) {
970     S.Diag(TheCall->getBeginLoc(),
971            diag::err_typecheck_call_too_few_args_at_least)
972         << 0 << 4 << NumArgs;
973     return true;
974   }
975 
976   Expr *Arg0 = TheCall->getArg(0);
977   Expr *Arg1 = TheCall->getArg(1);
978   Expr *Arg2 = TheCall->getArg(2);
979   Expr *Arg3 = TheCall->getArg(3);
980 
981   // First argument always needs to be a queue_t type.
982   if (!Arg0->getType()->isQueueT()) {
983     S.Diag(TheCall->getArg(0)->getBeginLoc(),
984            diag::err_opencl_builtin_expected_type)
985         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
986     return true;
987   }
988 
989   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
990   if (!Arg1->getType()->isIntegerType()) {
991     S.Diag(TheCall->getArg(1)->getBeginLoc(),
992            diag::err_opencl_builtin_expected_type)
993         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
994     return true;
995   }
996 
997   // Third argument is always an ndrange_t type.
998   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
999     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1000            diag::err_opencl_builtin_expected_type)
1001         << TheCall->getDirectCallee() << "'ndrange_t'";
1002     return true;
1003   }
1004 
1005   // With four arguments, there is only one form that the function could be
1006   // called in: no events and no variable arguments.
1007   if (NumArgs == 4) {
1008     // check that the last argument is the right block type.
1009     if (!isBlockPointer(Arg3)) {
1010       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1011           << TheCall->getDirectCallee() << "block";
1012       return true;
1013     }
1014     // we have a block type, check the prototype
1015     const BlockPointerType *BPT =
1016         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1017     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1018       S.Diag(Arg3->getBeginLoc(),
1019              diag::err_opencl_enqueue_kernel_blocks_no_args);
1020       return true;
1021     }
1022     return false;
1023   }
1024   // we can have block + varargs.
1025   if (isBlockPointer(Arg3))
1026     return (checkOpenCLBlockArgs(S, Arg3) ||
1027             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1028   // last two cases with either exactly 7 args or 7 args and varargs.
1029   if (NumArgs >= 7) {
1030     // check common block argument.
1031     Expr *Arg6 = TheCall->getArg(6);
1032     if (!isBlockPointer(Arg6)) {
1033       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1034           << TheCall->getDirectCallee() << "block";
1035       return true;
1036     }
1037     if (checkOpenCLBlockArgs(S, Arg6))
1038       return true;
1039 
1040     // Forth argument has to be any integer type.
1041     if (!Arg3->getType()->isIntegerType()) {
1042       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1043              diag::err_opencl_builtin_expected_type)
1044           << TheCall->getDirectCallee() << "integer";
1045       return true;
1046     }
1047     // check remaining common arguments.
1048     Expr *Arg4 = TheCall->getArg(4);
1049     Expr *Arg5 = TheCall->getArg(5);
1050 
1051     // Fifth argument is always passed as a pointer to clk_event_t.
1052     if (!Arg4->isNullPointerConstant(S.Context,
1053                                      Expr::NPC_ValueDependentIsNotNull) &&
1054         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1055       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1056              diag::err_opencl_builtin_expected_type)
1057           << TheCall->getDirectCallee()
1058           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1059       return true;
1060     }
1061 
1062     // Sixth argument is always passed as a pointer to clk_event_t.
1063     if (!Arg5->isNullPointerConstant(S.Context,
1064                                      Expr::NPC_ValueDependentIsNotNull) &&
1065         !(Arg5->getType()->isPointerType() &&
1066           Arg5->getType()->getPointeeType()->isClkEventT())) {
1067       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1068              diag::err_opencl_builtin_expected_type)
1069           << TheCall->getDirectCallee()
1070           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1071       return true;
1072     }
1073 
1074     if (NumArgs == 7)
1075       return false;
1076 
1077     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1078   }
1079 
1080   // None of the specific case has been detected, give generic error
1081   S.Diag(TheCall->getBeginLoc(),
1082          diag::err_opencl_enqueue_kernel_incorrect_args);
1083   return true;
1084 }
1085 
1086 /// Returns OpenCL access qual.
1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1088     return D->getAttr<OpenCLAccessAttr>();
1089 }
1090 
1091 /// Returns true if pipe element type is different from the pointer.
1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1093   const Expr *Arg0 = Call->getArg(0);
1094   // First argument type should always be pipe.
1095   if (!Arg0->getType()->isPipeType()) {
1096     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1097         << Call->getDirectCallee() << Arg0->getSourceRange();
1098     return true;
1099   }
1100   OpenCLAccessAttr *AccessQual =
1101       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1102   // Validates the access qualifier is compatible with the call.
1103   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1104   // read_only and write_only, and assumed to be read_only if no qualifier is
1105   // specified.
1106   switch (Call->getDirectCallee()->getBuiltinID()) {
1107   case Builtin::BIread_pipe:
1108   case Builtin::BIreserve_read_pipe:
1109   case Builtin::BIcommit_read_pipe:
1110   case Builtin::BIwork_group_reserve_read_pipe:
1111   case Builtin::BIsub_group_reserve_read_pipe:
1112   case Builtin::BIwork_group_commit_read_pipe:
1113   case Builtin::BIsub_group_commit_read_pipe:
1114     if (!(!AccessQual || AccessQual->isReadOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "read_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   case Builtin::BIwrite_pipe:
1122   case Builtin::BIreserve_write_pipe:
1123   case Builtin::BIcommit_write_pipe:
1124   case Builtin::BIwork_group_reserve_write_pipe:
1125   case Builtin::BIsub_group_reserve_write_pipe:
1126   case Builtin::BIwork_group_commit_write_pipe:
1127   case Builtin::BIsub_group_commit_write_pipe:
1128     if (!(AccessQual && AccessQual->isWriteOnly())) {
1129       S.Diag(Arg0->getBeginLoc(),
1130              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1131           << "write_only" << Arg0->getSourceRange();
1132       return true;
1133     }
1134     break;
1135   default:
1136     break;
1137   }
1138   return false;
1139 }
1140 
1141 /// Returns true if pipe element type is different from the pointer.
1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1143   const Expr *Arg0 = Call->getArg(0);
1144   const Expr *ArgIdx = Call->getArg(Idx);
1145   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1146   const QualType EltTy = PipeTy->getElementType();
1147   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1148   // The Idx argument should be a pointer and the type of the pointer and
1149   // the type of pipe element should also be the same.
1150   if (!ArgTy ||
1151       !S.Context.hasSameType(
1152           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1153     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1154         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1155         << ArgIdx->getType() << ArgIdx->getSourceRange();
1156     return true;
1157   }
1158   return false;
1159 }
1160 
1161 // Performs semantic analysis for the read/write_pipe call.
1162 // \param S Reference to the semantic analyzer.
1163 // \param Call A pointer to the builtin call.
1164 // \return True if a semantic error has been found, false otherwise.
1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1166   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1167   // functions have two forms.
1168   switch (Call->getNumArgs()) {
1169   case 2:
1170     if (checkOpenCLPipeArg(S, Call))
1171       return true;
1172     // The call with 2 arguments should be
1173     // read/write_pipe(pipe T, T*).
1174     // Check packet type T.
1175     if (checkOpenCLPipePacketType(S, Call, 1))
1176       return true;
1177     break;
1178 
1179   case 4: {
1180     if (checkOpenCLPipeArg(S, Call))
1181       return true;
1182     // The call with 4 arguments should be
1183     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1184     // Check reserve_id_t.
1185     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1186       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1187           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1188           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1189       return true;
1190     }
1191 
1192     // Check the index.
1193     const Expr *Arg2 = Call->getArg(2);
1194     if (!Arg2->getType()->isIntegerType() &&
1195         !Arg2->getType()->isUnsignedIntegerType()) {
1196       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1197           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1198           << Arg2->getType() << Arg2->getSourceRange();
1199       return true;
1200     }
1201 
1202     // Check packet type T.
1203     if (checkOpenCLPipePacketType(S, Call, 3))
1204       return true;
1205   } break;
1206   default:
1207     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1208         << Call->getDirectCallee() << Call->getSourceRange();
1209     return true;
1210   }
1211 
1212   return false;
1213 }
1214 
1215 // Performs a semantic analysis on the {work_group_/sub_group_
1216 //        /_}reserve_{read/write}_pipe
1217 // \param S Reference to the semantic analyzer.
1218 // \param Call The call to the builtin function to be analyzed.
1219 // \return True if a semantic error was found, false otherwise.
1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1221   if (checkArgCount(S, Call, 2))
1222     return true;
1223 
1224   if (checkOpenCLPipeArg(S, Call))
1225     return true;
1226 
1227   // Check the reserve size.
1228   if (!Call->getArg(1)->getType()->isIntegerType() &&
1229       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1230     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1231         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1232         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1233     return true;
1234   }
1235 
1236   // Since return type of reserve_read/write_pipe built-in function is
1237   // reserve_id_t, which is not defined in the builtin def file , we used int
1238   // as return type and need to override the return type of these functions.
1239   Call->setType(S.Context.OCLReserveIDTy);
1240 
1241   return false;
1242 }
1243 
1244 // Performs a semantic analysis on {work_group_/sub_group_
1245 //        /_}commit_{read/write}_pipe
1246 // \param S Reference to the semantic analyzer.
1247 // \param Call The call to the builtin function to be analyzed.
1248 // \return True if a semantic error was found, false otherwise.
1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1250   if (checkArgCount(S, Call, 2))
1251     return true;
1252 
1253   if (checkOpenCLPipeArg(S, Call))
1254     return true;
1255 
1256   // Check reserve_id_t.
1257   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1258     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1259         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1260         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1261     return true;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 // Performs a semantic analysis on the call to built-in Pipe
1268 //        Query Functions.
1269 // \param S Reference to the semantic analyzer.
1270 // \param Call The call to the builtin function to be analyzed.
1271 // \return True if a semantic error was found, false otherwise.
1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1273   if (checkArgCount(S, Call, 1))
1274     return true;
1275 
1276   if (!Call->getArg(0)->getType()->isPipeType()) {
1277     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1278         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1279     return true;
1280   }
1281 
1282   return false;
1283 }
1284 
1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1286 // Performs semantic analysis for the to_global/local/private call.
1287 // \param S Reference to the semantic analyzer.
1288 // \param BuiltinID ID of the builtin function.
1289 // \param Call A pointer to the builtin call.
1290 // \return True if a semantic error has been found, false otherwise.
1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1292                                     CallExpr *Call) {
1293   if (checkArgCount(S, Call, 1))
1294     return true;
1295 
1296   auto RT = Call->getArg(0)->getType();
1297   if (!RT->isPointerType() || RT->getPointeeType()
1298       .getAddressSpace() == LangAS::opencl_constant) {
1299     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1300         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1301     return true;
1302   }
1303 
1304   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1305     S.Diag(Call->getArg(0)->getBeginLoc(),
1306            diag::warn_opencl_generic_address_space_arg)
1307         << Call->getDirectCallee()->getNameInfo().getAsString()
1308         << Call->getArg(0)->getSourceRange();
1309   }
1310 
1311   RT = RT->getPointeeType();
1312   auto Qual = RT.getQualifiers();
1313   switch (BuiltinID) {
1314   case Builtin::BIto_global:
1315     Qual.setAddressSpace(LangAS::opencl_global);
1316     break;
1317   case Builtin::BIto_local:
1318     Qual.setAddressSpace(LangAS::opencl_local);
1319     break;
1320   case Builtin::BIto_private:
1321     Qual.setAddressSpace(LangAS::opencl_private);
1322     break;
1323   default:
1324     llvm_unreachable("Invalid builtin function");
1325   }
1326   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1327       RT.getUnqualifiedType(), Qual)));
1328 
1329   return false;
1330 }
1331 
1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1333   if (checkArgCount(S, TheCall, 1))
1334     return ExprError();
1335 
1336   // Compute __builtin_launder's parameter type from the argument.
1337   // The parameter type is:
1338   //  * The type of the argument if it's not an array or function type,
1339   //  Otherwise,
1340   //  * The decayed argument type.
1341   QualType ParamTy = [&]() {
1342     QualType ArgTy = TheCall->getArg(0)->getType();
1343     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1344       return S.Context.getPointerType(Ty->getElementType());
1345     if (ArgTy->isFunctionType()) {
1346       return S.Context.getPointerType(ArgTy);
1347     }
1348     return ArgTy;
1349   }();
1350 
1351   TheCall->setType(ParamTy);
1352 
1353   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1354     if (!ParamTy->isPointerType())
1355       return 0;
1356     if (ParamTy->isFunctionPointerType())
1357       return 1;
1358     if (ParamTy->isVoidPointerType())
1359       return 2;
1360     return llvm::Optional<unsigned>{};
1361   }();
1362   if (DiagSelect.hasValue()) {
1363     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1364         << DiagSelect.getValue() << TheCall->getSourceRange();
1365     return ExprError();
1366   }
1367 
1368   // We either have an incomplete class type, or we have a class template
1369   // whose instantiation has not been forced. Example:
1370   //
1371   //   template <class T> struct Foo { T value; };
1372   //   Foo<int> *p = nullptr;
1373   //   auto *d = __builtin_launder(p);
1374   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1375                             diag::err_incomplete_type))
1376     return ExprError();
1377 
1378   assert(ParamTy->getPointeeType()->isObjectType() &&
1379          "Unhandled non-object pointer case");
1380 
1381   InitializedEntity Entity =
1382       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1383   ExprResult Arg =
1384       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1385   if (Arg.isInvalid())
1386     return ExprError();
1387   TheCall->setArg(0, Arg.get());
1388 
1389   return TheCall;
1390 }
1391 
1392 // Emit an error and return true if the current architecture is not in the list
1393 // of supported architectures.
1394 static bool
1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1396                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1397   llvm::Triple::ArchType CurArch =
1398       S.getASTContext().getTargetInfo().getTriple().getArch();
1399   if (llvm::is_contained(SupportedArchs, CurArch))
1400     return false;
1401   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1402       << TheCall->getSourceRange();
1403   return true;
1404 }
1405 
1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1407                                  SourceLocation CallSiteLoc);
1408 
1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1410                                       CallExpr *TheCall) {
1411   switch (TI.getTriple().getArch()) {
1412   default:
1413     // Some builtins don't require additional checking, so just consider these
1414     // acceptable.
1415     return false;
1416   case llvm::Triple::arm:
1417   case llvm::Triple::armeb:
1418   case llvm::Triple::thumb:
1419   case llvm::Triple::thumbeb:
1420     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::aarch64:
1422   case llvm::Triple::aarch64_32:
1423   case llvm::Triple::aarch64_be:
1424     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1425   case llvm::Triple::bpfeb:
1426   case llvm::Triple::bpfel:
1427     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1428   case llvm::Triple::hexagon:
1429     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1430   case llvm::Triple::mips:
1431   case llvm::Triple::mipsel:
1432   case llvm::Triple::mips64:
1433   case llvm::Triple::mips64el:
1434     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1435   case llvm::Triple::systemz:
1436     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1437   case llvm::Triple::x86:
1438   case llvm::Triple::x86_64:
1439     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1440   case llvm::Triple::ppc:
1441   case llvm::Triple::ppcle:
1442   case llvm::Triple::ppc64:
1443   case llvm::Triple::ppc64le:
1444     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1445   case llvm::Triple::amdgcn:
1446     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1447   case llvm::Triple::riscv32:
1448   case llvm::Triple::riscv64:
1449     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1450   }
1451 }
1452 
1453 ExprResult
1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1455                                CallExpr *TheCall) {
1456   ExprResult TheCallResult(TheCall);
1457 
1458   // Find out if any arguments are required to be integer constant expressions.
1459   unsigned ICEArguments = 0;
1460   ASTContext::GetBuiltinTypeError Error;
1461   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1462   if (Error != ASTContext::GE_None)
1463     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1464 
1465   // If any arguments are required to be ICE's, check and diagnose.
1466   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1467     // Skip arguments not required to be ICE's.
1468     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1469 
1470     llvm::APSInt Result;
1471     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1472       return true;
1473     ICEArguments &= ~(1 << ArgNo);
1474   }
1475 
1476   switch (BuiltinID) {
1477   case Builtin::BI__builtin___CFStringMakeConstantString:
1478     assert(TheCall->getNumArgs() == 1 &&
1479            "Wrong # arguments to builtin CFStringMakeConstantString");
1480     if (CheckObjCString(TheCall->getArg(0)))
1481       return ExprError();
1482     break;
1483   case Builtin::BI__builtin_ms_va_start:
1484   case Builtin::BI__builtin_stdarg_start:
1485   case Builtin::BI__builtin_va_start:
1486     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1487       return ExprError();
1488     break;
1489   case Builtin::BI__va_start: {
1490     switch (Context.getTargetInfo().getTriple().getArch()) {
1491     case llvm::Triple::aarch64:
1492     case llvm::Triple::arm:
1493     case llvm::Triple::thumb:
1494       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1495         return ExprError();
1496       break;
1497     default:
1498       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1499         return ExprError();
1500       break;
1501     }
1502     break;
1503   }
1504 
1505   // The acquire, release, and no fence variants are ARM and AArch64 only.
1506   case Builtin::BI_interlockedbittestandset_acq:
1507   case Builtin::BI_interlockedbittestandset_rel:
1508   case Builtin::BI_interlockedbittestandset_nf:
1509   case Builtin::BI_interlockedbittestandreset_acq:
1510   case Builtin::BI_interlockedbittestandreset_rel:
1511   case Builtin::BI_interlockedbittestandreset_nf:
1512     if (CheckBuiltinTargetSupport(
1513             *this, BuiltinID, TheCall,
1514             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1515       return ExprError();
1516     break;
1517 
1518   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1519   case Builtin::BI_bittest64:
1520   case Builtin::BI_bittestandcomplement64:
1521   case Builtin::BI_bittestandreset64:
1522   case Builtin::BI_bittestandset64:
1523   case Builtin::BI_interlockedbittestandreset64:
1524   case Builtin::BI_interlockedbittestandset64:
1525     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1526                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1527                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1528       return ExprError();
1529     break;
1530 
1531   case Builtin::BI__builtin_isgreater:
1532   case Builtin::BI__builtin_isgreaterequal:
1533   case Builtin::BI__builtin_isless:
1534   case Builtin::BI__builtin_islessequal:
1535   case Builtin::BI__builtin_islessgreater:
1536   case Builtin::BI__builtin_isunordered:
1537     if (SemaBuiltinUnorderedCompare(TheCall))
1538       return ExprError();
1539     break;
1540   case Builtin::BI__builtin_fpclassify:
1541     if (SemaBuiltinFPClassification(TheCall, 6))
1542       return ExprError();
1543     break;
1544   case Builtin::BI__builtin_isfinite:
1545   case Builtin::BI__builtin_isinf:
1546   case Builtin::BI__builtin_isinf_sign:
1547   case Builtin::BI__builtin_isnan:
1548   case Builtin::BI__builtin_isnormal:
1549   case Builtin::BI__builtin_signbit:
1550   case Builtin::BI__builtin_signbitf:
1551   case Builtin::BI__builtin_signbitl:
1552     if (SemaBuiltinFPClassification(TheCall, 1))
1553       return ExprError();
1554     break;
1555   case Builtin::BI__builtin_shufflevector:
1556     return SemaBuiltinShuffleVector(TheCall);
1557     // TheCall will be freed by the smart pointer here, but that's fine, since
1558     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1559   case Builtin::BI__builtin_prefetch:
1560     if (SemaBuiltinPrefetch(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_alloca_with_align:
1564     if (SemaBuiltinAllocaWithAlign(TheCall))
1565       return ExprError();
1566     LLVM_FALLTHROUGH;
1567   case Builtin::BI__builtin_alloca:
1568     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1569         << TheCall->getDirectCallee();
1570     break;
1571   case Builtin::BI__arithmetic_fence:
1572     if (SemaBuiltinArithmeticFence(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__assume:
1576   case Builtin::BI__builtin_assume:
1577     if (SemaBuiltinAssume(TheCall))
1578       return ExprError();
1579     break;
1580   case Builtin::BI__builtin_assume_aligned:
1581     if (SemaBuiltinAssumeAligned(TheCall))
1582       return ExprError();
1583     break;
1584   case Builtin::BI__builtin_dynamic_object_size:
1585   case Builtin::BI__builtin_object_size:
1586     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1587       return ExprError();
1588     break;
1589   case Builtin::BI__builtin_longjmp:
1590     if (SemaBuiltinLongjmp(TheCall))
1591       return ExprError();
1592     break;
1593   case Builtin::BI__builtin_setjmp:
1594     if (SemaBuiltinSetjmp(TheCall))
1595       return ExprError();
1596     break;
1597   case Builtin::BI__builtin_classify_type:
1598     if (checkArgCount(*this, TheCall, 1)) return true;
1599     TheCall->setType(Context.IntTy);
1600     break;
1601   case Builtin::BI__builtin_complex:
1602     if (SemaBuiltinComplex(TheCall))
1603       return ExprError();
1604     break;
1605   case Builtin::BI__builtin_constant_p: {
1606     if (checkArgCount(*this, TheCall, 1)) return true;
1607     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1608     if (Arg.isInvalid()) return true;
1609     TheCall->setArg(0, Arg.get());
1610     TheCall->setType(Context.IntTy);
1611     break;
1612   }
1613   case Builtin::BI__builtin_launder:
1614     return SemaBuiltinLaunder(*this, TheCall);
1615   case Builtin::BI__sync_fetch_and_add:
1616   case Builtin::BI__sync_fetch_and_add_1:
1617   case Builtin::BI__sync_fetch_and_add_2:
1618   case Builtin::BI__sync_fetch_and_add_4:
1619   case Builtin::BI__sync_fetch_and_add_8:
1620   case Builtin::BI__sync_fetch_and_add_16:
1621   case Builtin::BI__sync_fetch_and_sub:
1622   case Builtin::BI__sync_fetch_and_sub_1:
1623   case Builtin::BI__sync_fetch_and_sub_2:
1624   case Builtin::BI__sync_fetch_and_sub_4:
1625   case Builtin::BI__sync_fetch_and_sub_8:
1626   case Builtin::BI__sync_fetch_and_sub_16:
1627   case Builtin::BI__sync_fetch_and_or:
1628   case Builtin::BI__sync_fetch_and_or_1:
1629   case Builtin::BI__sync_fetch_and_or_2:
1630   case Builtin::BI__sync_fetch_and_or_4:
1631   case Builtin::BI__sync_fetch_and_or_8:
1632   case Builtin::BI__sync_fetch_and_or_16:
1633   case Builtin::BI__sync_fetch_and_and:
1634   case Builtin::BI__sync_fetch_and_and_1:
1635   case Builtin::BI__sync_fetch_and_and_2:
1636   case Builtin::BI__sync_fetch_and_and_4:
1637   case Builtin::BI__sync_fetch_and_and_8:
1638   case Builtin::BI__sync_fetch_and_and_16:
1639   case Builtin::BI__sync_fetch_and_xor:
1640   case Builtin::BI__sync_fetch_and_xor_1:
1641   case Builtin::BI__sync_fetch_and_xor_2:
1642   case Builtin::BI__sync_fetch_and_xor_4:
1643   case Builtin::BI__sync_fetch_and_xor_8:
1644   case Builtin::BI__sync_fetch_and_xor_16:
1645   case Builtin::BI__sync_fetch_and_nand:
1646   case Builtin::BI__sync_fetch_and_nand_1:
1647   case Builtin::BI__sync_fetch_and_nand_2:
1648   case Builtin::BI__sync_fetch_and_nand_4:
1649   case Builtin::BI__sync_fetch_and_nand_8:
1650   case Builtin::BI__sync_fetch_and_nand_16:
1651   case Builtin::BI__sync_add_and_fetch:
1652   case Builtin::BI__sync_add_and_fetch_1:
1653   case Builtin::BI__sync_add_and_fetch_2:
1654   case Builtin::BI__sync_add_and_fetch_4:
1655   case Builtin::BI__sync_add_and_fetch_8:
1656   case Builtin::BI__sync_add_and_fetch_16:
1657   case Builtin::BI__sync_sub_and_fetch:
1658   case Builtin::BI__sync_sub_and_fetch_1:
1659   case Builtin::BI__sync_sub_and_fetch_2:
1660   case Builtin::BI__sync_sub_and_fetch_4:
1661   case Builtin::BI__sync_sub_and_fetch_8:
1662   case Builtin::BI__sync_sub_and_fetch_16:
1663   case Builtin::BI__sync_and_and_fetch:
1664   case Builtin::BI__sync_and_and_fetch_1:
1665   case Builtin::BI__sync_and_and_fetch_2:
1666   case Builtin::BI__sync_and_and_fetch_4:
1667   case Builtin::BI__sync_and_and_fetch_8:
1668   case Builtin::BI__sync_and_and_fetch_16:
1669   case Builtin::BI__sync_or_and_fetch:
1670   case Builtin::BI__sync_or_and_fetch_1:
1671   case Builtin::BI__sync_or_and_fetch_2:
1672   case Builtin::BI__sync_or_and_fetch_4:
1673   case Builtin::BI__sync_or_and_fetch_8:
1674   case Builtin::BI__sync_or_and_fetch_16:
1675   case Builtin::BI__sync_xor_and_fetch:
1676   case Builtin::BI__sync_xor_and_fetch_1:
1677   case Builtin::BI__sync_xor_and_fetch_2:
1678   case Builtin::BI__sync_xor_and_fetch_4:
1679   case Builtin::BI__sync_xor_and_fetch_8:
1680   case Builtin::BI__sync_xor_and_fetch_16:
1681   case Builtin::BI__sync_nand_and_fetch:
1682   case Builtin::BI__sync_nand_and_fetch_1:
1683   case Builtin::BI__sync_nand_and_fetch_2:
1684   case Builtin::BI__sync_nand_and_fetch_4:
1685   case Builtin::BI__sync_nand_and_fetch_8:
1686   case Builtin::BI__sync_nand_and_fetch_16:
1687   case Builtin::BI__sync_val_compare_and_swap:
1688   case Builtin::BI__sync_val_compare_and_swap_1:
1689   case Builtin::BI__sync_val_compare_and_swap_2:
1690   case Builtin::BI__sync_val_compare_and_swap_4:
1691   case Builtin::BI__sync_val_compare_and_swap_8:
1692   case Builtin::BI__sync_val_compare_and_swap_16:
1693   case Builtin::BI__sync_bool_compare_and_swap:
1694   case Builtin::BI__sync_bool_compare_and_swap_1:
1695   case Builtin::BI__sync_bool_compare_and_swap_2:
1696   case Builtin::BI__sync_bool_compare_and_swap_4:
1697   case Builtin::BI__sync_bool_compare_and_swap_8:
1698   case Builtin::BI__sync_bool_compare_and_swap_16:
1699   case Builtin::BI__sync_lock_test_and_set:
1700   case Builtin::BI__sync_lock_test_and_set_1:
1701   case Builtin::BI__sync_lock_test_and_set_2:
1702   case Builtin::BI__sync_lock_test_and_set_4:
1703   case Builtin::BI__sync_lock_test_and_set_8:
1704   case Builtin::BI__sync_lock_test_and_set_16:
1705   case Builtin::BI__sync_lock_release:
1706   case Builtin::BI__sync_lock_release_1:
1707   case Builtin::BI__sync_lock_release_2:
1708   case Builtin::BI__sync_lock_release_4:
1709   case Builtin::BI__sync_lock_release_8:
1710   case Builtin::BI__sync_lock_release_16:
1711   case Builtin::BI__sync_swap:
1712   case Builtin::BI__sync_swap_1:
1713   case Builtin::BI__sync_swap_2:
1714   case Builtin::BI__sync_swap_4:
1715   case Builtin::BI__sync_swap_8:
1716   case Builtin::BI__sync_swap_16:
1717     return SemaBuiltinAtomicOverloaded(TheCallResult);
1718   case Builtin::BI__sync_synchronize:
1719     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1720         << TheCall->getCallee()->getSourceRange();
1721     break;
1722   case Builtin::BI__builtin_nontemporal_load:
1723   case Builtin::BI__builtin_nontemporal_store:
1724     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1725   case Builtin::BI__builtin_memcpy_inline: {
1726     clang::Expr *SizeOp = TheCall->getArg(2);
1727     // We warn about copying to or from `nullptr` pointers when `size` is
1728     // greater than 0. When `size` is value dependent we cannot evaluate its
1729     // value so we bail out.
1730     if (SizeOp->isValueDependent())
1731       break;
1732     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1733       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1734       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1735     }
1736     break;
1737   }
1738 #define BUILTIN(ID, TYPE, ATTRS)
1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1740   case Builtin::BI##ID: \
1741     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1742 #include "clang/Basic/Builtins.def"
1743   case Builtin::BI__annotation:
1744     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_annotation:
1748     if (SemaBuiltinAnnotation(*this, TheCall))
1749       return ExprError();
1750     break;
1751   case Builtin::BI__builtin_addressof:
1752     if (SemaBuiltinAddressof(*this, TheCall))
1753       return ExprError();
1754     break;
1755   case Builtin::BI__builtin_is_aligned:
1756   case Builtin::BI__builtin_align_up:
1757   case Builtin::BI__builtin_align_down:
1758     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1759       return ExprError();
1760     break;
1761   case Builtin::BI__builtin_add_overflow:
1762   case Builtin::BI__builtin_sub_overflow:
1763   case Builtin::BI__builtin_mul_overflow:
1764     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1765       return ExprError();
1766     break;
1767   case Builtin::BI__builtin_operator_new:
1768   case Builtin::BI__builtin_operator_delete: {
1769     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1770     ExprResult Res =
1771         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1772     if (Res.isInvalid())
1773       CorrectDelayedTyposInExpr(TheCallResult.get());
1774     return Res;
1775   }
1776   case Builtin::BI__builtin_dump_struct: {
1777     // We first want to ensure we are called with 2 arguments
1778     if (checkArgCount(*this, TheCall, 2))
1779       return ExprError();
1780     // Ensure that the first argument is of type 'struct XX *'
1781     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1782     const QualType PtrArgType = PtrArg->getType();
1783     if (!PtrArgType->isPointerType() ||
1784         !PtrArgType->getPointeeType()->isRecordType()) {
1785       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1786           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1787           << "structure pointer";
1788       return ExprError();
1789     }
1790 
1791     // Ensure that the second argument is of type 'FunctionType'
1792     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1793     const QualType FnPtrArgType = FnPtrArg->getType();
1794     if (!FnPtrArgType->isPointerType()) {
1795       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1796           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1797           << FnPtrArgType << "'int (*)(const char *, ...)'";
1798       return ExprError();
1799     }
1800 
1801     const auto *FuncType =
1802         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1803 
1804     if (!FuncType) {
1805       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1806           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1807           << FnPtrArgType << "'int (*)(const char *, ...)'";
1808       return ExprError();
1809     }
1810 
1811     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1812       if (!FT->getNumParams()) {
1813         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1814             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1815             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1816         return ExprError();
1817       }
1818       QualType PT = FT->getParamType(0);
1819       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1820           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1821           !PT->getPointeeType().isConstQualified()) {
1822         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1823             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1824             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1825         return ExprError();
1826       }
1827     }
1828 
1829     TheCall->setType(Context.IntTy);
1830     break;
1831   }
1832   case Builtin::BI__builtin_expect_with_probability: {
1833     // We first want to ensure we are called with 3 arguments
1834     if (checkArgCount(*this, TheCall, 3))
1835       return ExprError();
1836     // then check probability is constant float in range [0.0, 1.0]
1837     const Expr *ProbArg = TheCall->getArg(2);
1838     SmallVector<PartialDiagnosticAt, 8> Notes;
1839     Expr::EvalResult Eval;
1840     Eval.Diag = &Notes;
1841     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1842         !Eval.Val.isFloat()) {
1843       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1844           << ProbArg->getSourceRange();
1845       for (const PartialDiagnosticAt &PDiag : Notes)
1846         Diag(PDiag.first, PDiag.second);
1847       return ExprError();
1848     }
1849     llvm::APFloat Probability = Eval.Val.getFloat();
1850     bool LoseInfo = false;
1851     Probability.convert(llvm::APFloat::IEEEdouble(),
1852                         llvm::RoundingMode::Dynamic, &LoseInfo);
1853     if (!(Probability >= llvm::APFloat(0.0) &&
1854           Probability <= llvm::APFloat(1.0))) {
1855       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1856           << ProbArg->getSourceRange();
1857       return ExprError();
1858     }
1859     break;
1860   }
1861   case Builtin::BI__builtin_preserve_access_index:
1862     if (SemaBuiltinPreserveAI(*this, TheCall))
1863       return ExprError();
1864     break;
1865   case Builtin::BI__builtin_call_with_static_chain:
1866     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1867       return ExprError();
1868     break;
1869   case Builtin::BI__exception_code:
1870   case Builtin::BI_exception_code:
1871     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1872                                  diag::err_seh___except_block))
1873       return ExprError();
1874     break;
1875   case Builtin::BI__exception_info:
1876   case Builtin::BI_exception_info:
1877     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1878                                  diag::err_seh___except_filter))
1879       return ExprError();
1880     break;
1881   case Builtin::BI__GetExceptionInfo:
1882     if (checkArgCount(*this, TheCall, 1))
1883       return ExprError();
1884 
1885     if (CheckCXXThrowOperand(
1886             TheCall->getBeginLoc(),
1887             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1888             TheCall))
1889       return ExprError();
1890 
1891     TheCall->setType(Context.VoidPtrTy);
1892     break;
1893   // OpenCL v2.0, s6.13.16 - Pipe functions
1894   case Builtin::BIread_pipe:
1895   case Builtin::BIwrite_pipe:
1896     // Since those two functions are declared with var args, we need a semantic
1897     // check for the argument.
1898     if (SemaBuiltinRWPipe(*this, TheCall))
1899       return ExprError();
1900     break;
1901   case Builtin::BIreserve_read_pipe:
1902   case Builtin::BIreserve_write_pipe:
1903   case Builtin::BIwork_group_reserve_read_pipe:
1904   case Builtin::BIwork_group_reserve_write_pipe:
1905     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIsub_group_reserve_read_pipe:
1909   case Builtin::BIsub_group_reserve_write_pipe:
1910     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1911         SemaBuiltinReserveRWPipe(*this, TheCall))
1912       return ExprError();
1913     break;
1914   case Builtin::BIcommit_read_pipe:
1915   case Builtin::BIcommit_write_pipe:
1916   case Builtin::BIwork_group_commit_read_pipe:
1917   case Builtin::BIwork_group_commit_write_pipe:
1918     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1919       return ExprError();
1920     break;
1921   case Builtin::BIsub_group_commit_read_pipe:
1922   case Builtin::BIsub_group_commit_write_pipe:
1923     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1924         SemaBuiltinCommitRWPipe(*this, TheCall))
1925       return ExprError();
1926     break;
1927   case Builtin::BIget_pipe_num_packets:
1928   case Builtin::BIget_pipe_max_packets:
1929     if (SemaBuiltinPipePackets(*this, TheCall))
1930       return ExprError();
1931     break;
1932   case Builtin::BIto_global:
1933   case Builtin::BIto_local:
1934   case Builtin::BIto_private:
1935     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1936       return ExprError();
1937     break;
1938   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1939   case Builtin::BIenqueue_kernel:
1940     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1941       return ExprError();
1942     break;
1943   case Builtin::BIget_kernel_work_group_size:
1944   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1945     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1946       return ExprError();
1947     break;
1948   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1949   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1950     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1951       return ExprError();
1952     break;
1953   case Builtin::BI__builtin_os_log_format:
1954     Cleanup.setExprNeedsCleanups(true);
1955     LLVM_FALLTHROUGH;
1956   case Builtin::BI__builtin_os_log_format_buffer_size:
1957     if (SemaBuiltinOSLogFormat(TheCall))
1958       return ExprError();
1959     break;
1960   case Builtin::BI__builtin_frame_address:
1961   case Builtin::BI__builtin_return_address: {
1962     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1963       return ExprError();
1964 
1965     // -Wframe-address warning if non-zero passed to builtin
1966     // return/frame address.
1967     Expr::EvalResult Result;
1968     if (!TheCall->getArg(0)->isValueDependent() &&
1969         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1970         Result.Val.getInt() != 0)
1971       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1972           << ((BuiltinID == Builtin::BI__builtin_return_address)
1973                   ? "__builtin_return_address"
1974                   : "__builtin_frame_address")
1975           << TheCall->getSourceRange();
1976     break;
1977   }
1978 
1979   case Builtin::BI__builtin_matrix_transpose:
1980     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1981 
1982   case Builtin::BI__builtin_matrix_column_major_load:
1983     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1984 
1985   case Builtin::BI__builtin_matrix_column_major_store:
1986     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1987 
1988   case Builtin::BI__builtin_get_device_side_mangled_name: {
1989     auto Check = [](CallExpr *TheCall) {
1990       if (TheCall->getNumArgs() != 1)
1991         return false;
1992       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1993       if (!DRE)
1994         return false;
1995       auto *D = DRE->getDecl();
1996       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1997         return false;
1998       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1999              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2000     };
2001     if (!Check(TheCall)) {
2002       Diag(TheCall->getBeginLoc(),
2003            diag::err_hip_invalid_args_builtin_mangled_name);
2004       return ExprError();
2005     }
2006   }
2007   }
2008 
2009   // Since the target specific builtins for each arch overlap, only check those
2010   // of the arch we are compiling for.
2011   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2012     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2013       assert(Context.getAuxTargetInfo() &&
2014              "Aux Target Builtin, but not an aux target?");
2015 
2016       if (CheckTSBuiltinFunctionCall(
2017               *Context.getAuxTargetInfo(),
2018               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2019         return ExprError();
2020     } else {
2021       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2022                                      TheCall))
2023         return ExprError();
2024     }
2025   }
2026 
2027   return TheCallResult;
2028 }
2029 
2030 // Get the valid immediate range for the specified NEON type code.
2031 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2032   NeonTypeFlags Type(t);
2033   int IsQuad = ForceQuad ? true : Type.isQuad();
2034   switch (Type.getEltType()) {
2035   case NeonTypeFlags::Int8:
2036   case NeonTypeFlags::Poly8:
2037     return shift ? 7 : (8 << IsQuad) - 1;
2038   case NeonTypeFlags::Int16:
2039   case NeonTypeFlags::Poly16:
2040     return shift ? 15 : (4 << IsQuad) - 1;
2041   case NeonTypeFlags::Int32:
2042     return shift ? 31 : (2 << IsQuad) - 1;
2043   case NeonTypeFlags::Int64:
2044   case NeonTypeFlags::Poly64:
2045     return shift ? 63 : (1 << IsQuad) - 1;
2046   case NeonTypeFlags::Poly128:
2047     return shift ? 127 : (1 << IsQuad) - 1;
2048   case NeonTypeFlags::Float16:
2049     assert(!shift && "cannot shift float types!");
2050     return (4 << IsQuad) - 1;
2051   case NeonTypeFlags::Float32:
2052     assert(!shift && "cannot shift float types!");
2053     return (2 << IsQuad) - 1;
2054   case NeonTypeFlags::Float64:
2055     assert(!shift && "cannot shift float types!");
2056     return (1 << IsQuad) - 1;
2057   case NeonTypeFlags::BFloat16:
2058     assert(!shift && "cannot shift float types!");
2059     return (4 << IsQuad) - 1;
2060   }
2061   llvm_unreachable("Invalid NeonTypeFlag!");
2062 }
2063 
2064 /// getNeonEltType - Return the QualType corresponding to the elements of
2065 /// the vector type specified by the NeonTypeFlags.  This is used to check
2066 /// the pointer arguments for Neon load/store intrinsics.
2067 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2068                                bool IsPolyUnsigned, bool IsInt64Long) {
2069   switch (Flags.getEltType()) {
2070   case NeonTypeFlags::Int8:
2071     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2072   case NeonTypeFlags::Int16:
2073     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2074   case NeonTypeFlags::Int32:
2075     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2076   case NeonTypeFlags::Int64:
2077     if (IsInt64Long)
2078       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2079     else
2080       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2081                                 : Context.LongLongTy;
2082   case NeonTypeFlags::Poly8:
2083     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2084   case NeonTypeFlags::Poly16:
2085     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2086   case NeonTypeFlags::Poly64:
2087     if (IsInt64Long)
2088       return Context.UnsignedLongTy;
2089     else
2090       return Context.UnsignedLongLongTy;
2091   case NeonTypeFlags::Poly128:
2092     break;
2093   case NeonTypeFlags::Float16:
2094     return Context.HalfTy;
2095   case NeonTypeFlags::Float32:
2096     return Context.FloatTy;
2097   case NeonTypeFlags::Float64:
2098     return Context.DoubleTy;
2099   case NeonTypeFlags::BFloat16:
2100     return Context.BFloat16Ty;
2101   }
2102   llvm_unreachable("Invalid NeonTypeFlag!");
2103 }
2104 
2105 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2106   // Range check SVE intrinsics that take immediate values.
2107   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2108 
2109   switch (BuiltinID) {
2110   default:
2111     return false;
2112 #define GET_SVE_IMMEDIATE_CHECK
2113 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2114 #undef GET_SVE_IMMEDIATE_CHECK
2115   }
2116 
2117   // Perform all the immediate checks for this builtin call.
2118   bool HasError = false;
2119   for (auto &I : ImmChecks) {
2120     int ArgNum, CheckTy, ElementSizeInBits;
2121     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2122 
2123     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2124 
2125     // Function that checks whether the operand (ArgNum) is an immediate
2126     // that is one of the predefined values.
2127     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2128                                    int ErrDiag) -> bool {
2129       // We can't check the value of a dependent argument.
2130       Expr *Arg = TheCall->getArg(ArgNum);
2131       if (Arg->isTypeDependent() || Arg->isValueDependent())
2132         return false;
2133 
2134       // Check constant-ness first.
2135       llvm::APSInt Imm;
2136       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2137         return true;
2138 
2139       if (!CheckImm(Imm.getSExtValue()))
2140         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2141       return false;
2142     };
2143 
2144     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2145     case SVETypeFlags::ImmCheck0_31:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2147         HasError = true;
2148       break;
2149     case SVETypeFlags::ImmCheck0_13:
2150       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2151         HasError = true;
2152       break;
2153     case SVETypeFlags::ImmCheck1_16:
2154       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2155         HasError = true;
2156       break;
2157     case SVETypeFlags::ImmCheck0_7:
2158       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckExtract:
2162       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2163                                       (2048 / ElementSizeInBits) - 1))
2164         HasError = true;
2165       break;
2166     case SVETypeFlags::ImmCheckShiftRight:
2167       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2168         HasError = true;
2169       break;
2170     case SVETypeFlags::ImmCheckShiftRightNarrow:
2171       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2172                                       ElementSizeInBits / 2))
2173         HasError = true;
2174       break;
2175     case SVETypeFlags::ImmCheckShiftLeft:
2176       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2177                                       ElementSizeInBits - 1))
2178         HasError = true;
2179       break;
2180     case SVETypeFlags::ImmCheckLaneIndex:
2181       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2182                                       (128 / (1 * ElementSizeInBits)) - 1))
2183         HasError = true;
2184       break;
2185     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2186       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2187                                       (128 / (2 * ElementSizeInBits)) - 1))
2188         HasError = true;
2189       break;
2190     case SVETypeFlags::ImmCheckLaneIndexDot:
2191       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2192                                       (128 / (4 * ElementSizeInBits)) - 1))
2193         HasError = true;
2194       break;
2195     case SVETypeFlags::ImmCheckComplexRot90_270:
2196       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2197                               diag::err_rotation_argument_to_cadd))
2198         HasError = true;
2199       break;
2200     case SVETypeFlags::ImmCheckComplexRotAll90:
2201       if (CheckImmediateInSet(
2202               [](int64_t V) {
2203                 return V == 0 || V == 90 || V == 180 || V == 270;
2204               },
2205               diag::err_rotation_argument_to_cmla))
2206         HasError = true;
2207       break;
2208     case SVETypeFlags::ImmCheck0_1:
2209       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2210         HasError = true;
2211       break;
2212     case SVETypeFlags::ImmCheck0_2:
2213       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2214         HasError = true;
2215       break;
2216     case SVETypeFlags::ImmCheck0_3:
2217       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2218         HasError = true;
2219       break;
2220     }
2221   }
2222 
2223   return HasError;
2224 }
2225 
2226 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2227                                         unsigned BuiltinID, CallExpr *TheCall) {
2228   llvm::APSInt Result;
2229   uint64_t mask = 0;
2230   unsigned TV = 0;
2231   int PtrArgNum = -1;
2232   bool HasConstPtr = false;
2233   switch (BuiltinID) {
2234 #define GET_NEON_OVERLOAD_CHECK
2235 #include "clang/Basic/arm_neon.inc"
2236 #include "clang/Basic/arm_fp16.inc"
2237 #undef GET_NEON_OVERLOAD_CHECK
2238   }
2239 
2240   // For NEON intrinsics which are overloaded on vector element type, validate
2241   // the immediate which specifies which variant to emit.
2242   unsigned ImmArg = TheCall->getNumArgs()-1;
2243   if (mask) {
2244     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2245       return true;
2246 
2247     TV = Result.getLimitedValue(64);
2248     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2249       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2250              << TheCall->getArg(ImmArg)->getSourceRange();
2251   }
2252 
2253   if (PtrArgNum >= 0) {
2254     // Check that pointer arguments have the specified type.
2255     Expr *Arg = TheCall->getArg(PtrArgNum);
2256     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2257       Arg = ICE->getSubExpr();
2258     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2259     QualType RHSTy = RHS.get()->getType();
2260 
2261     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2262     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2263                           Arch == llvm::Triple::aarch64_32 ||
2264                           Arch == llvm::Triple::aarch64_be;
2265     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2266     QualType EltTy =
2267         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2268     if (HasConstPtr)
2269       EltTy = EltTy.withConst();
2270     QualType LHSTy = Context.getPointerType(EltTy);
2271     AssignConvertType ConvTy;
2272     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2273     if (RHS.isInvalid())
2274       return true;
2275     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2276                                  RHS.get(), AA_Assigning))
2277       return true;
2278   }
2279 
2280   // For NEON intrinsics which take an immediate value as part of the
2281   // instruction, range check them here.
2282   unsigned i = 0, l = 0, u = 0;
2283   switch (BuiltinID) {
2284   default:
2285     return false;
2286   #define GET_NEON_IMMEDIATE_CHECK
2287   #include "clang/Basic/arm_neon.inc"
2288   #include "clang/Basic/arm_fp16.inc"
2289   #undef GET_NEON_IMMEDIATE_CHECK
2290   }
2291 
2292   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2293 }
2294 
2295 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2296   switch (BuiltinID) {
2297   default:
2298     return false;
2299   #include "clang/Basic/arm_mve_builtin_sema.inc"
2300   }
2301 }
2302 
2303 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2304                                        CallExpr *TheCall) {
2305   bool Err = false;
2306   switch (BuiltinID) {
2307   default:
2308     return false;
2309 #include "clang/Basic/arm_cde_builtin_sema.inc"
2310   }
2311 
2312   if (Err)
2313     return true;
2314 
2315   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2316 }
2317 
2318 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2319                                         const Expr *CoprocArg, bool WantCDE) {
2320   if (isConstantEvaluated())
2321     return false;
2322 
2323   // We can't check the value of a dependent argument.
2324   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2325     return false;
2326 
2327   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2328   int64_t CoprocNo = CoprocNoAP.getExtValue();
2329   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2330 
2331   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2332   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2333 
2334   if (IsCDECoproc != WantCDE)
2335     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2336            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2337 
2338   return false;
2339 }
2340 
2341 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2342                                         unsigned MaxWidth) {
2343   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2344           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2345           BuiltinID == ARM::BI__builtin_arm_strex ||
2346           BuiltinID == ARM::BI__builtin_arm_stlex ||
2347           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2348           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2349           BuiltinID == AArch64::BI__builtin_arm_strex ||
2350           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2351          "unexpected ARM builtin");
2352   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2353                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2354                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2355                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2356 
2357   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2358 
2359   // Ensure that we have the proper number of arguments.
2360   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2361     return true;
2362 
2363   // Inspect the pointer argument of the atomic builtin.  This should always be
2364   // a pointer type, whose element is an integral scalar or pointer type.
2365   // Because it is a pointer type, we don't have to worry about any implicit
2366   // casts here.
2367   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2368   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2369   if (PointerArgRes.isInvalid())
2370     return true;
2371   PointerArg = PointerArgRes.get();
2372 
2373   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2374   if (!pointerType) {
2375     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2376         << PointerArg->getType() << PointerArg->getSourceRange();
2377     return true;
2378   }
2379 
2380   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2381   // task is to insert the appropriate casts into the AST. First work out just
2382   // what the appropriate type is.
2383   QualType ValType = pointerType->getPointeeType();
2384   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2385   if (IsLdrex)
2386     AddrType.addConst();
2387 
2388   // Issue a warning if the cast is dodgy.
2389   CastKind CastNeeded = CK_NoOp;
2390   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2391     CastNeeded = CK_BitCast;
2392     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2393         << PointerArg->getType() << Context.getPointerType(AddrType)
2394         << AA_Passing << PointerArg->getSourceRange();
2395   }
2396 
2397   // Finally, do the cast and replace the argument with the corrected version.
2398   AddrType = Context.getPointerType(AddrType);
2399   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2400   if (PointerArgRes.isInvalid())
2401     return true;
2402   PointerArg = PointerArgRes.get();
2403 
2404   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2405 
2406   // In general, we allow ints, floats and pointers to be loaded and stored.
2407   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2408       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2409     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2410         << PointerArg->getType() << PointerArg->getSourceRange();
2411     return true;
2412   }
2413 
2414   // But ARM doesn't have instructions to deal with 128-bit versions.
2415   if (Context.getTypeSize(ValType) > MaxWidth) {
2416     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2417     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2418         << PointerArg->getType() << PointerArg->getSourceRange();
2419     return true;
2420   }
2421 
2422   switch (ValType.getObjCLifetime()) {
2423   case Qualifiers::OCL_None:
2424   case Qualifiers::OCL_ExplicitNone:
2425     // okay
2426     break;
2427 
2428   case Qualifiers::OCL_Weak:
2429   case Qualifiers::OCL_Strong:
2430   case Qualifiers::OCL_Autoreleasing:
2431     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2432         << ValType << PointerArg->getSourceRange();
2433     return true;
2434   }
2435 
2436   if (IsLdrex) {
2437     TheCall->setType(ValType);
2438     return false;
2439   }
2440 
2441   // Initialize the argument to be stored.
2442   ExprResult ValArg = TheCall->getArg(0);
2443   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2444       Context, ValType, /*consume*/ false);
2445   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2446   if (ValArg.isInvalid())
2447     return true;
2448   TheCall->setArg(0, ValArg.get());
2449 
2450   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2451   // but the custom checker bypasses all default analysis.
2452   TheCall->setType(Context.IntTy);
2453   return false;
2454 }
2455 
2456 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2457                                        CallExpr *TheCall) {
2458   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2459       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2460       BuiltinID == ARM::BI__builtin_arm_strex ||
2461       BuiltinID == ARM::BI__builtin_arm_stlex) {
2462     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2463   }
2464 
2465   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2466     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2467       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2468   }
2469 
2470   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2471       BuiltinID == ARM::BI__builtin_arm_wsr64)
2472     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2473 
2474   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2475       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2476       BuiltinID == ARM::BI__builtin_arm_wsr ||
2477       BuiltinID == ARM::BI__builtin_arm_wsrp)
2478     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2479 
2480   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2481     return true;
2482   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2483     return true;
2484   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2485     return true;
2486 
2487   // For intrinsics which take an immediate value as part of the instruction,
2488   // range check them here.
2489   // FIXME: VFP Intrinsics should error if VFP not present.
2490   switch (BuiltinID) {
2491   default: return false;
2492   case ARM::BI__builtin_arm_ssat:
2493     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2494   case ARM::BI__builtin_arm_usat:
2495     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2496   case ARM::BI__builtin_arm_ssat16:
2497     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2498   case ARM::BI__builtin_arm_usat16:
2499     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2500   case ARM::BI__builtin_arm_vcvtr_f:
2501   case ARM::BI__builtin_arm_vcvtr_d:
2502     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2503   case ARM::BI__builtin_arm_dmb:
2504   case ARM::BI__builtin_arm_dsb:
2505   case ARM::BI__builtin_arm_isb:
2506   case ARM::BI__builtin_arm_dbg:
2507     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2508   case ARM::BI__builtin_arm_cdp:
2509   case ARM::BI__builtin_arm_cdp2:
2510   case ARM::BI__builtin_arm_mcr:
2511   case ARM::BI__builtin_arm_mcr2:
2512   case ARM::BI__builtin_arm_mrc:
2513   case ARM::BI__builtin_arm_mrc2:
2514   case ARM::BI__builtin_arm_mcrr:
2515   case ARM::BI__builtin_arm_mcrr2:
2516   case ARM::BI__builtin_arm_mrrc:
2517   case ARM::BI__builtin_arm_mrrc2:
2518   case ARM::BI__builtin_arm_ldc:
2519   case ARM::BI__builtin_arm_ldcl:
2520   case ARM::BI__builtin_arm_ldc2:
2521   case ARM::BI__builtin_arm_ldc2l:
2522   case ARM::BI__builtin_arm_stc:
2523   case ARM::BI__builtin_arm_stcl:
2524   case ARM::BI__builtin_arm_stc2:
2525   case ARM::BI__builtin_arm_stc2l:
2526     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2527            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2528                                         /*WantCDE*/ false);
2529   }
2530 }
2531 
2532 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2533                                            unsigned BuiltinID,
2534                                            CallExpr *TheCall) {
2535   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2536       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2537       BuiltinID == AArch64::BI__builtin_arm_strex ||
2538       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2539     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2540   }
2541 
2542   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2543     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2544       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2545       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2546       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2547   }
2548 
2549   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2550       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2551     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2552 
2553   // Memory Tagging Extensions (MTE) Intrinsics
2554   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2555       BuiltinID == AArch64::BI__builtin_arm_addg ||
2556       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2557       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2558       BuiltinID == AArch64::BI__builtin_arm_stg ||
2559       BuiltinID == AArch64::BI__builtin_arm_subp) {
2560     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2561   }
2562 
2563   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2564       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2565       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2566       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2567     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2568 
2569   // Only check the valid encoding range. Any constant in this range would be
2570   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2571   // an exception for incorrect registers. This matches MSVC behavior.
2572   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2573       BuiltinID == AArch64::BI_WriteStatusReg)
2574     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2575 
2576   if (BuiltinID == AArch64::BI__getReg)
2577     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2578 
2579   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2580     return true;
2581 
2582   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2583     return true;
2584 
2585   // For intrinsics which take an immediate value as part of the instruction,
2586   // range check them here.
2587   unsigned i = 0, l = 0, u = 0;
2588   switch (BuiltinID) {
2589   default: return false;
2590   case AArch64::BI__builtin_arm_dmb:
2591   case AArch64::BI__builtin_arm_dsb:
2592   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2593   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2594   }
2595 
2596   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2597 }
2598 
2599 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2600   if (Arg->getType()->getAsPlaceholderType())
2601     return false;
2602 
2603   // The first argument needs to be a record field access.
2604   // If it is an array element access, we delay decision
2605   // to BPF backend to check whether the access is a
2606   // field access or not.
2607   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2608           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2609           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2610 }
2611 
2612 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2613                             QualType VectorTy, QualType EltTy) {
2614   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2615   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2616     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2617         << Call->getSourceRange() << VectorEltTy << EltTy;
2618     return false;
2619   }
2620   return true;
2621 }
2622 
2623 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2624   QualType ArgType = Arg->getType();
2625   if (ArgType->getAsPlaceholderType())
2626     return false;
2627 
2628   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2629   // format:
2630   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2631   //   2. <type> var;
2632   //      __builtin_preserve_type_info(var, flag);
2633   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2634       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2635     return false;
2636 
2637   // Typedef type.
2638   if (ArgType->getAs<TypedefType>())
2639     return true;
2640 
2641   // Record type or Enum type.
2642   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2643   if (const auto *RT = Ty->getAs<RecordType>()) {
2644     if (!RT->getDecl()->getDeclName().isEmpty())
2645       return true;
2646   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2647     if (!ET->getDecl()->getDeclName().isEmpty())
2648       return true;
2649   }
2650 
2651   return false;
2652 }
2653 
2654 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2655   QualType ArgType = Arg->getType();
2656   if (ArgType->getAsPlaceholderType())
2657     return false;
2658 
2659   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2660   // format:
2661   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2662   //                                 flag);
2663   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2664   if (!UO)
2665     return false;
2666 
2667   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2668   if (!CE)
2669     return false;
2670   if (CE->getCastKind() != CK_IntegralToPointer &&
2671       CE->getCastKind() != CK_NullToPointer)
2672     return false;
2673 
2674   // The integer must be from an EnumConstantDecl.
2675   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2676   if (!DR)
2677     return false;
2678 
2679   const EnumConstantDecl *Enumerator =
2680       dyn_cast<EnumConstantDecl>(DR->getDecl());
2681   if (!Enumerator)
2682     return false;
2683 
2684   // The type must be EnumType.
2685   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2686   const auto *ET = Ty->getAs<EnumType>();
2687   if (!ET)
2688     return false;
2689 
2690   // The enum value must be supported.
2691   for (auto *EDI : ET->getDecl()->enumerators()) {
2692     if (EDI == Enumerator)
2693       return true;
2694   }
2695 
2696   return false;
2697 }
2698 
2699 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2700                                        CallExpr *TheCall) {
2701   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2702           BuiltinID == BPF::BI__builtin_btf_type_id ||
2703           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2704           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2705          "unexpected BPF builtin");
2706 
2707   if (checkArgCount(*this, TheCall, 2))
2708     return true;
2709 
2710   // The second argument needs to be a constant int
2711   Expr *Arg = TheCall->getArg(1);
2712   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2713   diag::kind kind;
2714   if (!Value) {
2715     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2716       kind = diag::err_preserve_field_info_not_const;
2717     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2718       kind = diag::err_btf_type_id_not_const;
2719     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2720       kind = diag::err_preserve_type_info_not_const;
2721     else
2722       kind = diag::err_preserve_enum_value_not_const;
2723     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2724     return true;
2725   }
2726 
2727   // The first argument
2728   Arg = TheCall->getArg(0);
2729   bool InvalidArg = false;
2730   bool ReturnUnsignedInt = true;
2731   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2732     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2733       InvalidArg = true;
2734       kind = diag::err_preserve_field_info_not_field;
2735     }
2736   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2737     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2738       InvalidArg = true;
2739       kind = diag::err_preserve_type_info_invalid;
2740     }
2741   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2742     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2743       InvalidArg = true;
2744       kind = diag::err_preserve_enum_value_invalid;
2745     }
2746     ReturnUnsignedInt = false;
2747   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2748     ReturnUnsignedInt = false;
2749   }
2750 
2751   if (InvalidArg) {
2752     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2753     return true;
2754   }
2755 
2756   if (ReturnUnsignedInt)
2757     TheCall->setType(Context.UnsignedIntTy);
2758   else
2759     TheCall->setType(Context.UnsignedLongTy);
2760   return false;
2761 }
2762 
2763 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2764   struct ArgInfo {
2765     uint8_t OpNum;
2766     bool IsSigned;
2767     uint8_t BitWidth;
2768     uint8_t Align;
2769   };
2770   struct BuiltinInfo {
2771     unsigned BuiltinID;
2772     ArgInfo Infos[2];
2773   };
2774 
2775   static BuiltinInfo Infos[] = {
2776     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2777     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2778     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2779     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2780     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2781     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2782     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2783     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2784     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2785     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2786     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2787 
2788     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2791     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2792     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2793     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2799 
2800     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2852                                                       {{ 1, false, 6,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2860                                                       {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2867                                                        { 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2869                                                        { 2, false, 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2871                                                        { 3, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2873                                                        { 3, false, 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2890                                                       {{ 2, false, 4,  0 },
2891                                                        { 3, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2893                                                       {{ 2, false, 4,  0 },
2894                                                        { 3, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2896                                                       {{ 2, false, 4,  0 },
2897                                                        { 3, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2899                                                       {{ 2, false, 4,  0 },
2900                                                        { 3, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2912                                                        { 2, false, 5,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2914                                                        { 2, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2924                                                       {{ 1, false, 4,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2927                                                       {{ 1, false, 4,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2948                                                       {{ 3, false, 1,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2953                                                       {{ 3, false, 1,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2958                                                       {{ 3, false, 1,  0 }} },
2959   };
2960 
2961   // Use a dynamically initialized static to sort the table exactly once on
2962   // first run.
2963   static const bool SortOnce =
2964       (llvm::sort(Infos,
2965                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2966                    return LHS.BuiltinID < RHS.BuiltinID;
2967                  }),
2968        true);
2969   (void)SortOnce;
2970 
2971   const BuiltinInfo *F = llvm::partition_point(
2972       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2973   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2974     return false;
2975 
2976   bool Error = false;
2977 
2978   for (const ArgInfo &A : F->Infos) {
2979     // Ignore empty ArgInfo elements.
2980     if (A.BitWidth == 0)
2981       continue;
2982 
2983     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2984     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2985     if (!A.Align) {
2986       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2987     } else {
2988       unsigned M = 1 << A.Align;
2989       Min *= M;
2990       Max *= M;
2991       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2992                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2993     }
2994   }
2995   return Error;
2996 }
2997 
2998 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2999                                            CallExpr *TheCall) {
3000   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3001 }
3002 
3003 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3004                                         unsigned BuiltinID, CallExpr *TheCall) {
3005   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3006          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3007 }
3008 
3009 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3010                                CallExpr *TheCall) {
3011 
3012   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3013       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3014     if (!TI.hasFeature("dsp"))
3015       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3016   }
3017 
3018   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3019       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3020     if (!TI.hasFeature("dspr2"))
3021       return Diag(TheCall->getBeginLoc(),
3022                   diag::err_mips_builtin_requires_dspr2);
3023   }
3024 
3025   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3026       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3027     if (!TI.hasFeature("msa"))
3028       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3029   }
3030 
3031   return false;
3032 }
3033 
3034 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3035 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3036 // ordering for DSP is unspecified. MSA is ordered by the data format used
3037 // by the underlying instruction i.e., df/m, df/n and then by size.
3038 //
3039 // FIXME: The size tests here should instead be tablegen'd along with the
3040 //        definitions from include/clang/Basic/BuiltinsMips.def.
3041 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3042 //        be too.
3043 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3044   unsigned i = 0, l = 0, u = 0, m = 0;
3045   switch (BuiltinID) {
3046   default: return false;
3047   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3048   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3049   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3050   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3051   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3052   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3053   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3054   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3055   // df/m field.
3056   // These intrinsics take an unsigned 3 bit immediate.
3057   case Mips::BI__builtin_msa_bclri_b:
3058   case Mips::BI__builtin_msa_bnegi_b:
3059   case Mips::BI__builtin_msa_bseti_b:
3060   case Mips::BI__builtin_msa_sat_s_b:
3061   case Mips::BI__builtin_msa_sat_u_b:
3062   case Mips::BI__builtin_msa_slli_b:
3063   case Mips::BI__builtin_msa_srai_b:
3064   case Mips::BI__builtin_msa_srari_b:
3065   case Mips::BI__builtin_msa_srli_b:
3066   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3067   case Mips::BI__builtin_msa_binsli_b:
3068   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3069   // These intrinsics take an unsigned 4 bit immediate.
3070   case Mips::BI__builtin_msa_bclri_h:
3071   case Mips::BI__builtin_msa_bnegi_h:
3072   case Mips::BI__builtin_msa_bseti_h:
3073   case Mips::BI__builtin_msa_sat_s_h:
3074   case Mips::BI__builtin_msa_sat_u_h:
3075   case Mips::BI__builtin_msa_slli_h:
3076   case Mips::BI__builtin_msa_srai_h:
3077   case Mips::BI__builtin_msa_srari_h:
3078   case Mips::BI__builtin_msa_srli_h:
3079   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3080   case Mips::BI__builtin_msa_binsli_h:
3081   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3082   // These intrinsics take an unsigned 5 bit immediate.
3083   // The first block of intrinsics actually have an unsigned 5 bit field,
3084   // not a df/n field.
3085   case Mips::BI__builtin_msa_cfcmsa:
3086   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3087   case Mips::BI__builtin_msa_clei_u_b:
3088   case Mips::BI__builtin_msa_clei_u_h:
3089   case Mips::BI__builtin_msa_clei_u_w:
3090   case Mips::BI__builtin_msa_clei_u_d:
3091   case Mips::BI__builtin_msa_clti_u_b:
3092   case Mips::BI__builtin_msa_clti_u_h:
3093   case Mips::BI__builtin_msa_clti_u_w:
3094   case Mips::BI__builtin_msa_clti_u_d:
3095   case Mips::BI__builtin_msa_maxi_u_b:
3096   case Mips::BI__builtin_msa_maxi_u_h:
3097   case Mips::BI__builtin_msa_maxi_u_w:
3098   case Mips::BI__builtin_msa_maxi_u_d:
3099   case Mips::BI__builtin_msa_mini_u_b:
3100   case Mips::BI__builtin_msa_mini_u_h:
3101   case Mips::BI__builtin_msa_mini_u_w:
3102   case Mips::BI__builtin_msa_mini_u_d:
3103   case Mips::BI__builtin_msa_addvi_b:
3104   case Mips::BI__builtin_msa_addvi_h:
3105   case Mips::BI__builtin_msa_addvi_w:
3106   case Mips::BI__builtin_msa_addvi_d:
3107   case Mips::BI__builtin_msa_bclri_w:
3108   case Mips::BI__builtin_msa_bnegi_w:
3109   case Mips::BI__builtin_msa_bseti_w:
3110   case Mips::BI__builtin_msa_sat_s_w:
3111   case Mips::BI__builtin_msa_sat_u_w:
3112   case Mips::BI__builtin_msa_slli_w:
3113   case Mips::BI__builtin_msa_srai_w:
3114   case Mips::BI__builtin_msa_srari_w:
3115   case Mips::BI__builtin_msa_srli_w:
3116   case Mips::BI__builtin_msa_srlri_w:
3117   case Mips::BI__builtin_msa_subvi_b:
3118   case Mips::BI__builtin_msa_subvi_h:
3119   case Mips::BI__builtin_msa_subvi_w:
3120   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3121   case Mips::BI__builtin_msa_binsli_w:
3122   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3123   // These intrinsics take an unsigned 6 bit immediate.
3124   case Mips::BI__builtin_msa_bclri_d:
3125   case Mips::BI__builtin_msa_bnegi_d:
3126   case Mips::BI__builtin_msa_bseti_d:
3127   case Mips::BI__builtin_msa_sat_s_d:
3128   case Mips::BI__builtin_msa_sat_u_d:
3129   case Mips::BI__builtin_msa_slli_d:
3130   case Mips::BI__builtin_msa_srai_d:
3131   case Mips::BI__builtin_msa_srari_d:
3132   case Mips::BI__builtin_msa_srli_d:
3133   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3134   case Mips::BI__builtin_msa_binsli_d:
3135   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3136   // These intrinsics take a signed 5 bit immediate.
3137   case Mips::BI__builtin_msa_ceqi_b:
3138   case Mips::BI__builtin_msa_ceqi_h:
3139   case Mips::BI__builtin_msa_ceqi_w:
3140   case Mips::BI__builtin_msa_ceqi_d:
3141   case Mips::BI__builtin_msa_clti_s_b:
3142   case Mips::BI__builtin_msa_clti_s_h:
3143   case Mips::BI__builtin_msa_clti_s_w:
3144   case Mips::BI__builtin_msa_clti_s_d:
3145   case Mips::BI__builtin_msa_clei_s_b:
3146   case Mips::BI__builtin_msa_clei_s_h:
3147   case Mips::BI__builtin_msa_clei_s_w:
3148   case Mips::BI__builtin_msa_clei_s_d:
3149   case Mips::BI__builtin_msa_maxi_s_b:
3150   case Mips::BI__builtin_msa_maxi_s_h:
3151   case Mips::BI__builtin_msa_maxi_s_w:
3152   case Mips::BI__builtin_msa_maxi_s_d:
3153   case Mips::BI__builtin_msa_mini_s_b:
3154   case Mips::BI__builtin_msa_mini_s_h:
3155   case Mips::BI__builtin_msa_mini_s_w:
3156   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3157   // These intrinsics take an unsigned 8 bit immediate.
3158   case Mips::BI__builtin_msa_andi_b:
3159   case Mips::BI__builtin_msa_nori_b:
3160   case Mips::BI__builtin_msa_ori_b:
3161   case Mips::BI__builtin_msa_shf_b:
3162   case Mips::BI__builtin_msa_shf_h:
3163   case Mips::BI__builtin_msa_shf_w:
3164   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3165   case Mips::BI__builtin_msa_bseli_b:
3166   case Mips::BI__builtin_msa_bmnzi_b:
3167   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3168   // df/n format
3169   // These intrinsics take an unsigned 4 bit immediate.
3170   case Mips::BI__builtin_msa_copy_s_b:
3171   case Mips::BI__builtin_msa_copy_u_b:
3172   case Mips::BI__builtin_msa_insve_b:
3173   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3174   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3175   // These intrinsics take an unsigned 3 bit immediate.
3176   case Mips::BI__builtin_msa_copy_s_h:
3177   case Mips::BI__builtin_msa_copy_u_h:
3178   case Mips::BI__builtin_msa_insve_h:
3179   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3180   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3181   // These intrinsics take an unsigned 2 bit immediate.
3182   case Mips::BI__builtin_msa_copy_s_w:
3183   case Mips::BI__builtin_msa_copy_u_w:
3184   case Mips::BI__builtin_msa_insve_w:
3185   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3186   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3187   // These intrinsics take an unsigned 1 bit immediate.
3188   case Mips::BI__builtin_msa_copy_s_d:
3189   case Mips::BI__builtin_msa_copy_u_d:
3190   case Mips::BI__builtin_msa_insve_d:
3191   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3192   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3193   // Memory offsets and immediate loads.
3194   // These intrinsics take a signed 10 bit immediate.
3195   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3196   case Mips::BI__builtin_msa_ldi_h:
3197   case Mips::BI__builtin_msa_ldi_w:
3198   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3199   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3200   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3201   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3202   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3203   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3204   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3205   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3206   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3207   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3208   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3209   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3210   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3211   }
3212 
3213   if (!m)
3214     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3215 
3216   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3217          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3218 }
3219 
3220 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3221 /// advancing the pointer over the consumed characters. The decoded type is
3222 /// returned. If the decoded type represents a constant integer with a
3223 /// constraint on its value then Mask is set to that value. The type descriptors
3224 /// used in Str are specific to PPC MMA builtins and are documented in the file
3225 /// defining the PPC builtins.
3226 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3227                                         unsigned &Mask) {
3228   bool RequireICE = false;
3229   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3230   switch (*Str++) {
3231   case 'V':
3232     return Context.getVectorType(Context.UnsignedCharTy, 16,
3233                                  VectorType::VectorKind::AltiVecVector);
3234   case 'i': {
3235     char *End;
3236     unsigned size = strtoul(Str, &End, 10);
3237     assert(End != Str && "Missing constant parameter constraint");
3238     Str = End;
3239     Mask = size;
3240     return Context.IntTy;
3241   }
3242   case 'W': {
3243     char *End;
3244     unsigned size = strtoul(Str, &End, 10);
3245     assert(End != Str && "Missing PowerPC MMA type size");
3246     Str = End;
3247     QualType Type;
3248     switch (size) {
3249   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3250     case size: Type = Context.Id##Ty; break;
3251   #include "clang/Basic/PPCTypes.def"
3252     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3253     }
3254     bool CheckVectorArgs = false;
3255     while (!CheckVectorArgs) {
3256       switch (*Str++) {
3257       case '*':
3258         Type = Context.getPointerType(Type);
3259         break;
3260       case 'C':
3261         Type = Type.withConst();
3262         break;
3263       default:
3264         CheckVectorArgs = true;
3265         --Str;
3266         break;
3267       }
3268     }
3269     return Type;
3270   }
3271   default:
3272     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3273   }
3274 }
3275 
3276 static bool isPPC_64Builtin(unsigned BuiltinID) {
3277   // These builtins only work on PPC 64bit targets.
3278   switch (BuiltinID) {
3279   case PPC::BI__builtin_divde:
3280   case PPC::BI__builtin_divdeu:
3281   case PPC::BI__builtin_bpermd:
3282   case PPC::BI__builtin_ppc_ldarx:
3283   case PPC::BI__builtin_ppc_stdcx:
3284   case PPC::BI__builtin_ppc_tdw:
3285   case PPC::BI__builtin_ppc_trapd:
3286   case PPC::BI__builtin_ppc_cmpeqb:
3287   case PPC::BI__builtin_ppc_setb:
3288   case PPC::BI__builtin_ppc_mulhd:
3289   case PPC::BI__builtin_ppc_mulhdu:
3290   case PPC::BI__builtin_ppc_maddhd:
3291   case PPC::BI__builtin_ppc_maddhdu:
3292   case PPC::BI__builtin_ppc_maddld:
3293   case PPC::BI__builtin_ppc_load8r:
3294   case PPC::BI__builtin_ppc_store8r:
3295   case PPC::BI__builtin_ppc_insert_exp:
3296   case PPC::BI__builtin_ppc_extract_sig:
3297   case PPC::BI__builtin_ppc_addex:
3298     return true;
3299   }
3300   return false;
3301 }
3302 
3303 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3304                              StringRef FeatureToCheck, unsigned DiagID,
3305                              StringRef DiagArg = "") {
3306   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3307     return false;
3308 
3309   if (DiagArg.empty())
3310     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3311   else
3312     S.Diag(TheCall->getBeginLoc(), DiagID)
3313         << DiagArg << TheCall->getSourceRange();
3314 
3315   return true;
3316 }
3317 
3318 /// Returns true if the argument consists of one contiguous run of 1s with any
3319 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3320 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3321 /// since all 1s are not contiguous.
3322 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3323   llvm::APSInt Result;
3324   // We can't check the value of a dependent argument.
3325   Expr *Arg = TheCall->getArg(ArgNum);
3326   if (Arg->isTypeDependent() || Arg->isValueDependent())
3327     return false;
3328 
3329   // Check constant-ness first.
3330   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3331     return true;
3332 
3333   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3334   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3335     return false;
3336 
3337   return Diag(TheCall->getBeginLoc(),
3338               diag::err_argument_not_contiguous_bit_field)
3339          << ArgNum << Arg->getSourceRange();
3340 }
3341 
3342 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3343                                        CallExpr *TheCall) {
3344   unsigned i = 0, l = 0, u = 0;
3345   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3346   llvm::APSInt Result;
3347 
3348   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3349     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3350            << TheCall->getSourceRange();
3351 
3352   switch (BuiltinID) {
3353   default: return false;
3354   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3355   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3356     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3357            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3358   case PPC::BI__builtin_altivec_dss:
3359     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3360   case PPC::BI__builtin_tbegin:
3361   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3362   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3363   case PPC::BI__builtin_tabortwc:
3364   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3365   case PPC::BI__builtin_tabortwci:
3366   case PPC::BI__builtin_tabortdci:
3367     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3368            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3369   case PPC::BI__builtin_altivec_dst:
3370   case PPC::BI__builtin_altivec_dstt:
3371   case PPC::BI__builtin_altivec_dstst:
3372   case PPC::BI__builtin_altivec_dststt:
3373     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3374   case PPC::BI__builtin_vsx_xxpermdi:
3375   case PPC::BI__builtin_vsx_xxsldwi:
3376     return SemaBuiltinVSX(TheCall);
3377   case PPC::BI__builtin_divwe:
3378   case PPC::BI__builtin_divweu:
3379   case PPC::BI__builtin_divde:
3380   case PPC::BI__builtin_divdeu:
3381     return SemaFeatureCheck(*this, TheCall, "extdiv",
3382                             diag::err_ppc_builtin_only_on_arch, "7");
3383   case PPC::BI__builtin_bpermd:
3384     return SemaFeatureCheck(*this, TheCall, "bpermd",
3385                             diag::err_ppc_builtin_only_on_arch, "7");
3386   case PPC::BI__builtin_unpack_vector_int128:
3387     return SemaFeatureCheck(*this, TheCall, "vsx",
3388                             diag::err_ppc_builtin_only_on_arch, "7") ||
3389            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3390   case PPC::BI__builtin_pack_vector_int128:
3391     return SemaFeatureCheck(*this, TheCall, "vsx",
3392                             diag::err_ppc_builtin_only_on_arch, "7");
3393   case PPC::BI__builtin_altivec_vgnb:
3394      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3395   case PPC::BI__builtin_altivec_vec_replace_elt:
3396   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3397     QualType VecTy = TheCall->getArg(0)->getType();
3398     QualType EltTy = TheCall->getArg(1)->getType();
3399     unsigned Width = Context.getIntWidth(EltTy);
3400     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3401            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3402   }
3403   case PPC::BI__builtin_vsx_xxeval:
3404      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3405   case PPC::BI__builtin_altivec_vsldbi:
3406      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3407   case PPC::BI__builtin_altivec_vsrdbi:
3408      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3409   case PPC::BI__builtin_vsx_xxpermx:
3410      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3411   case PPC::BI__builtin_ppc_tw:
3412   case PPC::BI__builtin_ppc_tdw:
3413     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3414   case PPC::BI__builtin_ppc_cmpeqb:
3415   case PPC::BI__builtin_ppc_setb:
3416   case PPC::BI__builtin_ppc_maddhd:
3417   case PPC::BI__builtin_ppc_maddhdu:
3418   case PPC::BI__builtin_ppc_maddld:
3419     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3420                             diag::err_ppc_builtin_only_on_arch, "9");
3421   case PPC::BI__builtin_ppc_cmprb:
3422     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3423                             diag::err_ppc_builtin_only_on_arch, "9") ||
3424            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3425   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3426   // be a constant that represents a contiguous bit field.
3427   case PPC::BI__builtin_ppc_rlwnm:
3428     return SemaBuiltinConstantArg(TheCall, 1, Result) ||
3429            SemaValueIsRunOfOnes(TheCall, 2);
3430   case PPC::BI__builtin_ppc_rlwimi:
3431   case PPC::BI__builtin_ppc_rldimi:
3432     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3433            SemaValueIsRunOfOnes(TheCall, 3);
3434   case PPC::BI__builtin_ppc_extract_exp:
3435   case PPC::BI__builtin_ppc_extract_sig:
3436   case PPC::BI__builtin_ppc_insert_exp:
3437     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3438                             diag::err_ppc_builtin_only_on_arch, "9");
3439   case PPC::BI__builtin_ppc_addex: {
3440     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3441                          diag::err_ppc_builtin_only_on_arch, "9") ||
3442         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3443       return true;
3444     // Output warning for reserved values 1 to 3.
3445     int ArgValue =
3446         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3447     if (ArgValue != 0)
3448       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3449           << ArgValue;
3450     return false;
3451   }
3452   case PPC::BI__builtin_ppc_mtfsb0:
3453   case PPC::BI__builtin_ppc_mtfsb1:
3454     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3455   case PPC::BI__builtin_ppc_mtfsf:
3456     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3457   case PPC::BI__builtin_ppc_mtfsfi:
3458     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3459            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3460   case PPC::BI__builtin_ppc_alignx:
3461     return SemaBuiltinConstantArgPower2(TheCall, 0);
3462   case PPC::BI__builtin_ppc_rdlam:
3463     return SemaValueIsRunOfOnes(TheCall, 2);
3464   case PPC::BI__builtin_ppc_icbt:
3465   case PPC::BI__builtin_ppc_sthcx:
3466   case PPC::BI__builtin_ppc_stbcx:
3467   case PPC::BI__builtin_ppc_lharx:
3468   case PPC::BI__builtin_ppc_lbarx:
3469     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3470                             diag::err_ppc_builtin_only_on_arch, "8");
3471   case PPC::BI__builtin_vsx_ldrmb:
3472   case PPC::BI__builtin_vsx_strmb:
3473     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3474                             diag::err_ppc_builtin_only_on_arch, "8") ||
3475            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3476 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3477   case PPC::BI__builtin_##Name: \
3478     return SemaBuiltinPPCMMACall(TheCall, Types);
3479 #include "clang/Basic/BuiltinsPPC.def"
3480   }
3481   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3482 }
3483 
3484 // Check if the given type is a non-pointer PPC MMA type. This function is used
3485 // in Sema to prevent invalid uses of restricted PPC MMA types.
3486 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3487   if (Type->isPointerType() || Type->isArrayType())
3488     return false;
3489 
3490   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3491 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3492   if (false
3493 #include "clang/Basic/PPCTypes.def"
3494      ) {
3495     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3496     return true;
3497   }
3498   return false;
3499 }
3500 
3501 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3502                                           CallExpr *TheCall) {
3503   // position of memory order and scope arguments in the builtin
3504   unsigned OrderIndex, ScopeIndex;
3505   switch (BuiltinID) {
3506   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3507   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3508   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3509   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3510     OrderIndex = 2;
3511     ScopeIndex = 3;
3512     break;
3513   case AMDGPU::BI__builtin_amdgcn_fence:
3514     OrderIndex = 0;
3515     ScopeIndex = 1;
3516     break;
3517   default:
3518     return false;
3519   }
3520 
3521   ExprResult Arg = TheCall->getArg(OrderIndex);
3522   auto ArgExpr = Arg.get();
3523   Expr::EvalResult ArgResult;
3524 
3525   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3526     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3527            << ArgExpr->getType();
3528   auto Ord = ArgResult.Val.getInt().getZExtValue();
3529 
3530   // Check valididty of memory ordering as per C11 / C++11's memody model.
3531   // Only fence needs check. Atomic dec/inc allow all memory orders.
3532   if (!llvm::isValidAtomicOrderingCABI(Ord))
3533     return Diag(ArgExpr->getBeginLoc(),
3534                 diag::warn_atomic_op_has_invalid_memory_order)
3535            << ArgExpr->getSourceRange();
3536   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3537   case llvm::AtomicOrderingCABI::relaxed:
3538   case llvm::AtomicOrderingCABI::consume:
3539     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3540       return Diag(ArgExpr->getBeginLoc(),
3541                   diag::warn_atomic_op_has_invalid_memory_order)
3542              << ArgExpr->getSourceRange();
3543     break;
3544   case llvm::AtomicOrderingCABI::acquire:
3545   case llvm::AtomicOrderingCABI::release:
3546   case llvm::AtomicOrderingCABI::acq_rel:
3547   case llvm::AtomicOrderingCABI::seq_cst:
3548     break;
3549   }
3550 
3551   Arg = TheCall->getArg(ScopeIndex);
3552   ArgExpr = Arg.get();
3553   Expr::EvalResult ArgResult1;
3554   // Check that sync scope is a constant literal
3555   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3556     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3557            << ArgExpr->getType();
3558 
3559   return false;
3560 }
3561 
3562 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3563   llvm::APSInt Result;
3564 
3565   // We can't check the value of a dependent argument.
3566   Expr *Arg = TheCall->getArg(ArgNum);
3567   if (Arg->isTypeDependent() || Arg->isValueDependent())
3568     return false;
3569 
3570   // Check constant-ness first.
3571   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3572     return true;
3573 
3574   int64_t Val = Result.getSExtValue();
3575   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3576     return false;
3577 
3578   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3579          << Arg->getSourceRange();
3580 }
3581 
3582 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3583                                          unsigned BuiltinID,
3584                                          CallExpr *TheCall) {
3585   // CodeGenFunction can also detect this, but this gives a better error
3586   // message.
3587   bool FeatureMissing = false;
3588   SmallVector<StringRef> ReqFeatures;
3589   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3590   Features.split(ReqFeatures, ',');
3591 
3592   // Check if each required feature is included
3593   for (StringRef F : ReqFeatures) {
3594     if (TI.hasFeature(F))
3595       continue;
3596 
3597     // If the feature is 64bit, alter the string so it will print better in
3598     // the diagnostic.
3599     if (F == "64bit")
3600       F = "RV64";
3601 
3602     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3603     F.consume_front("experimental-");
3604     std::string FeatureStr = F.str();
3605     FeatureStr[0] = std::toupper(FeatureStr[0]);
3606 
3607     // Error message
3608     FeatureMissing = true;
3609     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3610         << TheCall->getSourceRange() << StringRef(FeatureStr);
3611   }
3612 
3613   if (FeatureMissing)
3614     return true;
3615 
3616   switch (BuiltinID) {
3617   case RISCV::BI__builtin_rvv_vsetvli:
3618     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3619            CheckRISCVLMUL(TheCall, 2);
3620   case RISCV::BI__builtin_rvv_vsetvlimax:
3621     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3622            CheckRISCVLMUL(TheCall, 1);
3623   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3624   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3625   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3626   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3627   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3628   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3629   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3630   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3631   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3632   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3633   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3634   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3635   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3636   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3637   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3638   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3639   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3640   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3641   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3642   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3643   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3644   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3645   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3646   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3647   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3648   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3649   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3650   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3651   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3652   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3653     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3654   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3655   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3656   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3657   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3658   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3659   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3660   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3661   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3662   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3663   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3664   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3665   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3666   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3667   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3668   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3669   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3670   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3671   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3672   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3673   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3674     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3675   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3676   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3677   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3678   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3679   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3680   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3681   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3682   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3683   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3684   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3685     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3686   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3687   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3688   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3689   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3690   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3691   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3692   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3693   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3694   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3695   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3696   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3697   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3698   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3699   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3700   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3701   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3702   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3703   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3704   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3705   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3706   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3707   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3708   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3709   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3710   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3711   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3712   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3713   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3714   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3715   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3716     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3717   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3718   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3719   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3720   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3721   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3722   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3723   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3724   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3725   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3726   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3727   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3728   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3729   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3730   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3731   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3732   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3733   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3734   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3735   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3736   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3737     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3738   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3739   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3740   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3741   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3742   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3743   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3744   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3745   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3746   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3747   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3748     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3749   }
3750 
3751   return false;
3752 }
3753 
3754 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3755                                            CallExpr *TheCall) {
3756   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3757     Expr *Arg = TheCall->getArg(0);
3758     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3759       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3760         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3761                << Arg->getSourceRange();
3762   }
3763 
3764   // For intrinsics which take an immediate value as part of the instruction,
3765   // range check them here.
3766   unsigned i = 0, l = 0, u = 0;
3767   switch (BuiltinID) {
3768   default: return false;
3769   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3770   case SystemZ::BI__builtin_s390_verimb:
3771   case SystemZ::BI__builtin_s390_verimh:
3772   case SystemZ::BI__builtin_s390_verimf:
3773   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3774   case SystemZ::BI__builtin_s390_vfaeb:
3775   case SystemZ::BI__builtin_s390_vfaeh:
3776   case SystemZ::BI__builtin_s390_vfaef:
3777   case SystemZ::BI__builtin_s390_vfaebs:
3778   case SystemZ::BI__builtin_s390_vfaehs:
3779   case SystemZ::BI__builtin_s390_vfaefs:
3780   case SystemZ::BI__builtin_s390_vfaezb:
3781   case SystemZ::BI__builtin_s390_vfaezh:
3782   case SystemZ::BI__builtin_s390_vfaezf:
3783   case SystemZ::BI__builtin_s390_vfaezbs:
3784   case SystemZ::BI__builtin_s390_vfaezhs:
3785   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3786   case SystemZ::BI__builtin_s390_vfisb:
3787   case SystemZ::BI__builtin_s390_vfidb:
3788     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3789            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3790   case SystemZ::BI__builtin_s390_vftcisb:
3791   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3792   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3793   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3794   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3795   case SystemZ::BI__builtin_s390_vstrcb:
3796   case SystemZ::BI__builtin_s390_vstrch:
3797   case SystemZ::BI__builtin_s390_vstrcf:
3798   case SystemZ::BI__builtin_s390_vstrczb:
3799   case SystemZ::BI__builtin_s390_vstrczh:
3800   case SystemZ::BI__builtin_s390_vstrczf:
3801   case SystemZ::BI__builtin_s390_vstrcbs:
3802   case SystemZ::BI__builtin_s390_vstrchs:
3803   case SystemZ::BI__builtin_s390_vstrcfs:
3804   case SystemZ::BI__builtin_s390_vstrczbs:
3805   case SystemZ::BI__builtin_s390_vstrczhs:
3806   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3807   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3808   case SystemZ::BI__builtin_s390_vfminsb:
3809   case SystemZ::BI__builtin_s390_vfmaxsb:
3810   case SystemZ::BI__builtin_s390_vfmindb:
3811   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3812   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3813   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3814   case SystemZ::BI__builtin_s390_vclfnhs:
3815   case SystemZ::BI__builtin_s390_vclfnls:
3816   case SystemZ::BI__builtin_s390_vcfn:
3817   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3818   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3819   }
3820   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3821 }
3822 
3823 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3824 /// This checks that the target supports __builtin_cpu_supports and
3825 /// that the string argument is constant and valid.
3826 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3827                                    CallExpr *TheCall) {
3828   Expr *Arg = TheCall->getArg(0);
3829 
3830   // Check if the argument is a string literal.
3831   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3832     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3833            << Arg->getSourceRange();
3834 
3835   // Check the contents of the string.
3836   StringRef Feature =
3837       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3838   if (!TI.validateCpuSupports(Feature))
3839     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3840            << Arg->getSourceRange();
3841   return false;
3842 }
3843 
3844 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3845 /// This checks that the target supports __builtin_cpu_is and
3846 /// that the string argument is constant and valid.
3847 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3848   Expr *Arg = TheCall->getArg(0);
3849 
3850   // Check if the argument is a string literal.
3851   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3852     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3853            << Arg->getSourceRange();
3854 
3855   // Check the contents of the string.
3856   StringRef Feature =
3857       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3858   if (!TI.validateCpuIs(Feature))
3859     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3860            << Arg->getSourceRange();
3861   return false;
3862 }
3863 
3864 // Check if the rounding mode is legal.
3865 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3866   // Indicates if this instruction has rounding control or just SAE.
3867   bool HasRC = false;
3868 
3869   unsigned ArgNum = 0;
3870   switch (BuiltinID) {
3871   default:
3872     return false;
3873   case X86::BI__builtin_ia32_vcvttsd2si32:
3874   case X86::BI__builtin_ia32_vcvttsd2si64:
3875   case X86::BI__builtin_ia32_vcvttsd2usi32:
3876   case X86::BI__builtin_ia32_vcvttsd2usi64:
3877   case X86::BI__builtin_ia32_vcvttss2si32:
3878   case X86::BI__builtin_ia32_vcvttss2si64:
3879   case X86::BI__builtin_ia32_vcvttss2usi32:
3880   case X86::BI__builtin_ia32_vcvttss2usi64:
3881   case X86::BI__builtin_ia32_vcvttsh2si32:
3882   case X86::BI__builtin_ia32_vcvttsh2si64:
3883   case X86::BI__builtin_ia32_vcvttsh2usi32:
3884   case X86::BI__builtin_ia32_vcvttsh2usi64:
3885     ArgNum = 1;
3886     break;
3887   case X86::BI__builtin_ia32_maxpd512:
3888   case X86::BI__builtin_ia32_maxps512:
3889   case X86::BI__builtin_ia32_minpd512:
3890   case X86::BI__builtin_ia32_minps512:
3891   case X86::BI__builtin_ia32_maxph512:
3892   case X86::BI__builtin_ia32_minph512:
3893     ArgNum = 2;
3894     break;
3895   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3896   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3897   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3898   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3899   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3900   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3901   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3902   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3903   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3904   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3905   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3906   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3907   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3908   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3909   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3910   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3911   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3912   case X86::BI__builtin_ia32_exp2pd_mask:
3913   case X86::BI__builtin_ia32_exp2ps_mask:
3914   case X86::BI__builtin_ia32_getexppd512_mask:
3915   case X86::BI__builtin_ia32_getexpps512_mask:
3916   case X86::BI__builtin_ia32_rcp28pd_mask:
3917   case X86::BI__builtin_ia32_rcp28ps_mask:
3918   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3919   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3920   case X86::BI__builtin_ia32_vcomisd:
3921   case X86::BI__builtin_ia32_vcomiss:
3922   case X86::BI__builtin_ia32_vcomish:
3923   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3924     ArgNum = 3;
3925     break;
3926   case X86::BI__builtin_ia32_cmppd512_mask:
3927   case X86::BI__builtin_ia32_cmpps512_mask:
3928   case X86::BI__builtin_ia32_cmpsd_mask:
3929   case X86::BI__builtin_ia32_cmpss_mask:
3930   case X86::BI__builtin_ia32_cmpsh_mask:
3931   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3932   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3933   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3934   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3935   case X86::BI__builtin_ia32_getexpss128_round_mask:
3936   case X86::BI__builtin_ia32_getmantpd512_mask:
3937   case X86::BI__builtin_ia32_getmantps512_mask:
3938   case X86::BI__builtin_ia32_maxsd_round_mask:
3939   case X86::BI__builtin_ia32_maxss_round_mask:
3940   case X86::BI__builtin_ia32_maxsh_round_mask:
3941   case X86::BI__builtin_ia32_minsd_round_mask:
3942   case X86::BI__builtin_ia32_minss_round_mask:
3943   case X86::BI__builtin_ia32_minsh_round_mask:
3944   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3945   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3946   case X86::BI__builtin_ia32_reducepd512_mask:
3947   case X86::BI__builtin_ia32_reduceps512_mask:
3948   case X86::BI__builtin_ia32_rndscalepd_mask:
3949   case X86::BI__builtin_ia32_rndscaleps_mask:
3950   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3951   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3952     ArgNum = 4;
3953     break;
3954   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3955   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3956   case X86::BI__builtin_ia32_fixupimmps512_mask:
3957   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3958   case X86::BI__builtin_ia32_fixupimmsd_mask:
3959   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3960   case X86::BI__builtin_ia32_fixupimmss_mask:
3961   case X86::BI__builtin_ia32_fixupimmss_maskz:
3962   case X86::BI__builtin_ia32_getmantsd_round_mask:
3963   case X86::BI__builtin_ia32_getmantss_round_mask:
3964   case X86::BI__builtin_ia32_rangepd512_mask:
3965   case X86::BI__builtin_ia32_rangeps512_mask:
3966   case X86::BI__builtin_ia32_rangesd128_round_mask:
3967   case X86::BI__builtin_ia32_rangess128_round_mask:
3968   case X86::BI__builtin_ia32_reducesd_mask:
3969   case X86::BI__builtin_ia32_reducess_mask:
3970   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3971   case X86::BI__builtin_ia32_rndscaless_round_mask:
3972     ArgNum = 5;
3973     break;
3974   case X86::BI__builtin_ia32_vcvtsd2si64:
3975   case X86::BI__builtin_ia32_vcvtsd2si32:
3976   case X86::BI__builtin_ia32_vcvtsd2usi32:
3977   case X86::BI__builtin_ia32_vcvtsd2usi64:
3978   case X86::BI__builtin_ia32_vcvtss2si32:
3979   case X86::BI__builtin_ia32_vcvtss2si64:
3980   case X86::BI__builtin_ia32_vcvtss2usi32:
3981   case X86::BI__builtin_ia32_vcvtss2usi64:
3982   case X86::BI__builtin_ia32_vcvtsh2si32:
3983   case X86::BI__builtin_ia32_vcvtsh2si64:
3984   case X86::BI__builtin_ia32_vcvtsh2usi32:
3985   case X86::BI__builtin_ia32_vcvtsh2usi64:
3986   case X86::BI__builtin_ia32_sqrtpd512:
3987   case X86::BI__builtin_ia32_sqrtps512:
3988     ArgNum = 1;
3989     HasRC = true;
3990     break;
3991   case X86::BI__builtin_ia32_addph512:
3992   case X86::BI__builtin_ia32_divph512:
3993   case X86::BI__builtin_ia32_mulph512:
3994   case X86::BI__builtin_ia32_subph512:
3995   case X86::BI__builtin_ia32_addpd512:
3996   case X86::BI__builtin_ia32_addps512:
3997   case X86::BI__builtin_ia32_divpd512:
3998   case X86::BI__builtin_ia32_divps512:
3999   case X86::BI__builtin_ia32_mulpd512:
4000   case X86::BI__builtin_ia32_mulps512:
4001   case X86::BI__builtin_ia32_subpd512:
4002   case X86::BI__builtin_ia32_subps512:
4003   case X86::BI__builtin_ia32_cvtsi2sd64:
4004   case X86::BI__builtin_ia32_cvtsi2ss32:
4005   case X86::BI__builtin_ia32_cvtsi2ss64:
4006   case X86::BI__builtin_ia32_cvtusi2sd64:
4007   case X86::BI__builtin_ia32_cvtusi2ss32:
4008   case X86::BI__builtin_ia32_cvtusi2ss64:
4009   case X86::BI__builtin_ia32_vcvtusi2sh:
4010   case X86::BI__builtin_ia32_vcvtusi642sh:
4011   case X86::BI__builtin_ia32_vcvtsi2sh:
4012   case X86::BI__builtin_ia32_vcvtsi642sh:
4013     ArgNum = 2;
4014     HasRC = true;
4015     break;
4016   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4017   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4018   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4019   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4020   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4021   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4022   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4023   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4024   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4025   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4026   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4027   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4028   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4029   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4030   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4031   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4032   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4033   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4034   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4035   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4036   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4037   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4038   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4039   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4040   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4041   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4042   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4043   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4044   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4045     ArgNum = 3;
4046     HasRC = true;
4047     break;
4048   case X86::BI__builtin_ia32_addsh_round_mask:
4049   case X86::BI__builtin_ia32_addss_round_mask:
4050   case X86::BI__builtin_ia32_addsd_round_mask:
4051   case X86::BI__builtin_ia32_divsh_round_mask:
4052   case X86::BI__builtin_ia32_divss_round_mask:
4053   case X86::BI__builtin_ia32_divsd_round_mask:
4054   case X86::BI__builtin_ia32_mulsh_round_mask:
4055   case X86::BI__builtin_ia32_mulss_round_mask:
4056   case X86::BI__builtin_ia32_mulsd_round_mask:
4057   case X86::BI__builtin_ia32_subsh_round_mask:
4058   case X86::BI__builtin_ia32_subss_round_mask:
4059   case X86::BI__builtin_ia32_subsd_round_mask:
4060   case X86::BI__builtin_ia32_scalefpd512_mask:
4061   case X86::BI__builtin_ia32_scalefps512_mask:
4062   case X86::BI__builtin_ia32_scalefsd_round_mask:
4063   case X86::BI__builtin_ia32_scalefss_round_mask:
4064   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4065   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4066   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4067   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4068   case X86::BI__builtin_ia32_sqrtss_round_mask:
4069   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4070   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4071   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4072   case X86::BI__builtin_ia32_vfmaddss3_mask:
4073   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4074   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4075   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4076   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4077   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4078   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4079   case X86::BI__builtin_ia32_vfmaddps512_mask:
4080   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4081   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4082   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4083   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4084   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4085   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4086   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4087   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4088   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4089   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4090   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4091     ArgNum = 4;
4092     HasRC = true;
4093     break;
4094   }
4095 
4096   llvm::APSInt Result;
4097 
4098   // We can't check the value of a dependent argument.
4099   Expr *Arg = TheCall->getArg(ArgNum);
4100   if (Arg->isTypeDependent() || Arg->isValueDependent())
4101     return false;
4102 
4103   // Check constant-ness first.
4104   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4105     return true;
4106 
4107   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4108   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4109   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4110   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4111   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4112       Result == 8/*ROUND_NO_EXC*/ ||
4113       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4114       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4115     return false;
4116 
4117   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4118          << Arg->getSourceRange();
4119 }
4120 
4121 // Check if the gather/scatter scale is legal.
4122 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4123                                              CallExpr *TheCall) {
4124   unsigned ArgNum = 0;
4125   switch (BuiltinID) {
4126   default:
4127     return false;
4128   case X86::BI__builtin_ia32_gatherpfdpd:
4129   case X86::BI__builtin_ia32_gatherpfdps:
4130   case X86::BI__builtin_ia32_gatherpfqpd:
4131   case X86::BI__builtin_ia32_gatherpfqps:
4132   case X86::BI__builtin_ia32_scatterpfdpd:
4133   case X86::BI__builtin_ia32_scatterpfdps:
4134   case X86::BI__builtin_ia32_scatterpfqpd:
4135   case X86::BI__builtin_ia32_scatterpfqps:
4136     ArgNum = 3;
4137     break;
4138   case X86::BI__builtin_ia32_gatherd_pd:
4139   case X86::BI__builtin_ia32_gatherd_pd256:
4140   case X86::BI__builtin_ia32_gatherq_pd:
4141   case X86::BI__builtin_ia32_gatherq_pd256:
4142   case X86::BI__builtin_ia32_gatherd_ps:
4143   case X86::BI__builtin_ia32_gatherd_ps256:
4144   case X86::BI__builtin_ia32_gatherq_ps:
4145   case X86::BI__builtin_ia32_gatherq_ps256:
4146   case X86::BI__builtin_ia32_gatherd_q:
4147   case X86::BI__builtin_ia32_gatherd_q256:
4148   case X86::BI__builtin_ia32_gatherq_q:
4149   case X86::BI__builtin_ia32_gatherq_q256:
4150   case X86::BI__builtin_ia32_gatherd_d:
4151   case X86::BI__builtin_ia32_gatherd_d256:
4152   case X86::BI__builtin_ia32_gatherq_d:
4153   case X86::BI__builtin_ia32_gatherq_d256:
4154   case X86::BI__builtin_ia32_gather3div2df:
4155   case X86::BI__builtin_ia32_gather3div2di:
4156   case X86::BI__builtin_ia32_gather3div4df:
4157   case X86::BI__builtin_ia32_gather3div4di:
4158   case X86::BI__builtin_ia32_gather3div4sf:
4159   case X86::BI__builtin_ia32_gather3div4si:
4160   case X86::BI__builtin_ia32_gather3div8sf:
4161   case X86::BI__builtin_ia32_gather3div8si:
4162   case X86::BI__builtin_ia32_gather3siv2df:
4163   case X86::BI__builtin_ia32_gather3siv2di:
4164   case X86::BI__builtin_ia32_gather3siv4df:
4165   case X86::BI__builtin_ia32_gather3siv4di:
4166   case X86::BI__builtin_ia32_gather3siv4sf:
4167   case X86::BI__builtin_ia32_gather3siv4si:
4168   case X86::BI__builtin_ia32_gather3siv8sf:
4169   case X86::BI__builtin_ia32_gather3siv8si:
4170   case X86::BI__builtin_ia32_gathersiv8df:
4171   case X86::BI__builtin_ia32_gathersiv16sf:
4172   case X86::BI__builtin_ia32_gatherdiv8df:
4173   case X86::BI__builtin_ia32_gatherdiv16sf:
4174   case X86::BI__builtin_ia32_gathersiv8di:
4175   case X86::BI__builtin_ia32_gathersiv16si:
4176   case X86::BI__builtin_ia32_gatherdiv8di:
4177   case X86::BI__builtin_ia32_gatherdiv16si:
4178   case X86::BI__builtin_ia32_scatterdiv2df:
4179   case X86::BI__builtin_ia32_scatterdiv2di:
4180   case X86::BI__builtin_ia32_scatterdiv4df:
4181   case X86::BI__builtin_ia32_scatterdiv4di:
4182   case X86::BI__builtin_ia32_scatterdiv4sf:
4183   case X86::BI__builtin_ia32_scatterdiv4si:
4184   case X86::BI__builtin_ia32_scatterdiv8sf:
4185   case X86::BI__builtin_ia32_scatterdiv8si:
4186   case X86::BI__builtin_ia32_scattersiv2df:
4187   case X86::BI__builtin_ia32_scattersiv2di:
4188   case X86::BI__builtin_ia32_scattersiv4df:
4189   case X86::BI__builtin_ia32_scattersiv4di:
4190   case X86::BI__builtin_ia32_scattersiv4sf:
4191   case X86::BI__builtin_ia32_scattersiv4si:
4192   case X86::BI__builtin_ia32_scattersiv8sf:
4193   case X86::BI__builtin_ia32_scattersiv8si:
4194   case X86::BI__builtin_ia32_scattersiv8df:
4195   case X86::BI__builtin_ia32_scattersiv16sf:
4196   case X86::BI__builtin_ia32_scatterdiv8df:
4197   case X86::BI__builtin_ia32_scatterdiv16sf:
4198   case X86::BI__builtin_ia32_scattersiv8di:
4199   case X86::BI__builtin_ia32_scattersiv16si:
4200   case X86::BI__builtin_ia32_scatterdiv8di:
4201   case X86::BI__builtin_ia32_scatterdiv16si:
4202     ArgNum = 4;
4203     break;
4204   }
4205 
4206   llvm::APSInt Result;
4207 
4208   // We can't check the value of a dependent argument.
4209   Expr *Arg = TheCall->getArg(ArgNum);
4210   if (Arg->isTypeDependent() || Arg->isValueDependent())
4211     return false;
4212 
4213   // Check constant-ness first.
4214   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4215     return true;
4216 
4217   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4218     return false;
4219 
4220   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4221          << Arg->getSourceRange();
4222 }
4223 
4224 enum { TileRegLow = 0, TileRegHigh = 7 };
4225 
4226 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4227                                              ArrayRef<int> ArgNums) {
4228   for (int ArgNum : ArgNums) {
4229     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4230       return true;
4231   }
4232   return false;
4233 }
4234 
4235 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4236                                         ArrayRef<int> ArgNums) {
4237   // Because the max number of tile register is TileRegHigh + 1, so here we use
4238   // each bit to represent the usage of them in bitset.
4239   std::bitset<TileRegHigh + 1> ArgValues;
4240   for (int ArgNum : ArgNums) {
4241     Expr *Arg = TheCall->getArg(ArgNum);
4242     if (Arg->isTypeDependent() || Arg->isValueDependent())
4243       continue;
4244 
4245     llvm::APSInt Result;
4246     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4247       return true;
4248     int ArgExtValue = Result.getExtValue();
4249     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4250            "Incorrect tile register num.");
4251     if (ArgValues.test(ArgExtValue))
4252       return Diag(TheCall->getBeginLoc(),
4253                   diag::err_x86_builtin_tile_arg_duplicate)
4254              << TheCall->getArg(ArgNum)->getSourceRange();
4255     ArgValues.set(ArgExtValue);
4256   }
4257   return false;
4258 }
4259 
4260 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4261                                                 ArrayRef<int> ArgNums) {
4262   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4263          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4264 }
4265 
4266 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4267   switch (BuiltinID) {
4268   default:
4269     return false;
4270   case X86::BI__builtin_ia32_tileloadd64:
4271   case X86::BI__builtin_ia32_tileloaddt164:
4272   case X86::BI__builtin_ia32_tilestored64:
4273   case X86::BI__builtin_ia32_tilezero:
4274     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4275   case X86::BI__builtin_ia32_tdpbssd:
4276   case X86::BI__builtin_ia32_tdpbsud:
4277   case X86::BI__builtin_ia32_tdpbusd:
4278   case X86::BI__builtin_ia32_tdpbuud:
4279   case X86::BI__builtin_ia32_tdpbf16ps:
4280     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4281   }
4282 }
4283 static bool isX86_32Builtin(unsigned BuiltinID) {
4284   // These builtins only work on x86-32 targets.
4285   switch (BuiltinID) {
4286   case X86::BI__builtin_ia32_readeflags_u32:
4287   case X86::BI__builtin_ia32_writeeflags_u32:
4288     return true;
4289   }
4290 
4291   return false;
4292 }
4293 
4294 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4295                                        CallExpr *TheCall) {
4296   if (BuiltinID == X86::BI__builtin_cpu_supports)
4297     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4298 
4299   if (BuiltinID == X86::BI__builtin_cpu_is)
4300     return SemaBuiltinCpuIs(*this, TI, TheCall);
4301 
4302   // Check for 32-bit only builtins on a 64-bit target.
4303   const llvm::Triple &TT = TI.getTriple();
4304   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4305     return Diag(TheCall->getCallee()->getBeginLoc(),
4306                 diag::err_32_bit_builtin_64_bit_tgt);
4307 
4308   // If the intrinsic has rounding or SAE make sure its valid.
4309   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4310     return true;
4311 
4312   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4313   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4314     return true;
4315 
4316   // If the intrinsic has a tile arguments, make sure they are valid.
4317   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4318     return true;
4319 
4320   // For intrinsics which take an immediate value as part of the instruction,
4321   // range check them here.
4322   int i = 0, l = 0, u = 0;
4323   switch (BuiltinID) {
4324   default:
4325     return false;
4326   case X86::BI__builtin_ia32_vec_ext_v2si:
4327   case X86::BI__builtin_ia32_vec_ext_v2di:
4328   case X86::BI__builtin_ia32_vextractf128_pd256:
4329   case X86::BI__builtin_ia32_vextractf128_ps256:
4330   case X86::BI__builtin_ia32_vextractf128_si256:
4331   case X86::BI__builtin_ia32_extract128i256:
4332   case X86::BI__builtin_ia32_extractf64x4_mask:
4333   case X86::BI__builtin_ia32_extracti64x4_mask:
4334   case X86::BI__builtin_ia32_extractf32x8_mask:
4335   case X86::BI__builtin_ia32_extracti32x8_mask:
4336   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4337   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4338   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4339   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4340     i = 1; l = 0; u = 1;
4341     break;
4342   case X86::BI__builtin_ia32_vec_set_v2di:
4343   case X86::BI__builtin_ia32_vinsertf128_pd256:
4344   case X86::BI__builtin_ia32_vinsertf128_ps256:
4345   case X86::BI__builtin_ia32_vinsertf128_si256:
4346   case X86::BI__builtin_ia32_insert128i256:
4347   case X86::BI__builtin_ia32_insertf32x8:
4348   case X86::BI__builtin_ia32_inserti32x8:
4349   case X86::BI__builtin_ia32_insertf64x4:
4350   case X86::BI__builtin_ia32_inserti64x4:
4351   case X86::BI__builtin_ia32_insertf64x2_256:
4352   case X86::BI__builtin_ia32_inserti64x2_256:
4353   case X86::BI__builtin_ia32_insertf32x4_256:
4354   case X86::BI__builtin_ia32_inserti32x4_256:
4355     i = 2; l = 0; u = 1;
4356     break;
4357   case X86::BI__builtin_ia32_vpermilpd:
4358   case X86::BI__builtin_ia32_vec_ext_v4hi:
4359   case X86::BI__builtin_ia32_vec_ext_v4si:
4360   case X86::BI__builtin_ia32_vec_ext_v4sf:
4361   case X86::BI__builtin_ia32_vec_ext_v4di:
4362   case X86::BI__builtin_ia32_extractf32x4_mask:
4363   case X86::BI__builtin_ia32_extracti32x4_mask:
4364   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4365   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4366     i = 1; l = 0; u = 3;
4367     break;
4368   case X86::BI_mm_prefetch:
4369   case X86::BI__builtin_ia32_vec_ext_v8hi:
4370   case X86::BI__builtin_ia32_vec_ext_v8si:
4371     i = 1; l = 0; u = 7;
4372     break;
4373   case X86::BI__builtin_ia32_sha1rnds4:
4374   case X86::BI__builtin_ia32_blendpd:
4375   case X86::BI__builtin_ia32_shufpd:
4376   case X86::BI__builtin_ia32_vec_set_v4hi:
4377   case X86::BI__builtin_ia32_vec_set_v4si:
4378   case X86::BI__builtin_ia32_vec_set_v4di:
4379   case X86::BI__builtin_ia32_shuf_f32x4_256:
4380   case X86::BI__builtin_ia32_shuf_f64x2_256:
4381   case X86::BI__builtin_ia32_shuf_i32x4_256:
4382   case X86::BI__builtin_ia32_shuf_i64x2_256:
4383   case X86::BI__builtin_ia32_insertf64x2_512:
4384   case X86::BI__builtin_ia32_inserti64x2_512:
4385   case X86::BI__builtin_ia32_insertf32x4:
4386   case X86::BI__builtin_ia32_inserti32x4:
4387     i = 2; l = 0; u = 3;
4388     break;
4389   case X86::BI__builtin_ia32_vpermil2pd:
4390   case X86::BI__builtin_ia32_vpermil2pd256:
4391   case X86::BI__builtin_ia32_vpermil2ps:
4392   case X86::BI__builtin_ia32_vpermil2ps256:
4393     i = 3; l = 0; u = 3;
4394     break;
4395   case X86::BI__builtin_ia32_cmpb128_mask:
4396   case X86::BI__builtin_ia32_cmpw128_mask:
4397   case X86::BI__builtin_ia32_cmpd128_mask:
4398   case X86::BI__builtin_ia32_cmpq128_mask:
4399   case X86::BI__builtin_ia32_cmpb256_mask:
4400   case X86::BI__builtin_ia32_cmpw256_mask:
4401   case X86::BI__builtin_ia32_cmpd256_mask:
4402   case X86::BI__builtin_ia32_cmpq256_mask:
4403   case X86::BI__builtin_ia32_cmpb512_mask:
4404   case X86::BI__builtin_ia32_cmpw512_mask:
4405   case X86::BI__builtin_ia32_cmpd512_mask:
4406   case X86::BI__builtin_ia32_cmpq512_mask:
4407   case X86::BI__builtin_ia32_ucmpb128_mask:
4408   case X86::BI__builtin_ia32_ucmpw128_mask:
4409   case X86::BI__builtin_ia32_ucmpd128_mask:
4410   case X86::BI__builtin_ia32_ucmpq128_mask:
4411   case X86::BI__builtin_ia32_ucmpb256_mask:
4412   case X86::BI__builtin_ia32_ucmpw256_mask:
4413   case X86::BI__builtin_ia32_ucmpd256_mask:
4414   case X86::BI__builtin_ia32_ucmpq256_mask:
4415   case X86::BI__builtin_ia32_ucmpb512_mask:
4416   case X86::BI__builtin_ia32_ucmpw512_mask:
4417   case X86::BI__builtin_ia32_ucmpd512_mask:
4418   case X86::BI__builtin_ia32_ucmpq512_mask:
4419   case X86::BI__builtin_ia32_vpcomub:
4420   case X86::BI__builtin_ia32_vpcomuw:
4421   case X86::BI__builtin_ia32_vpcomud:
4422   case X86::BI__builtin_ia32_vpcomuq:
4423   case X86::BI__builtin_ia32_vpcomb:
4424   case X86::BI__builtin_ia32_vpcomw:
4425   case X86::BI__builtin_ia32_vpcomd:
4426   case X86::BI__builtin_ia32_vpcomq:
4427   case X86::BI__builtin_ia32_vec_set_v8hi:
4428   case X86::BI__builtin_ia32_vec_set_v8si:
4429     i = 2; l = 0; u = 7;
4430     break;
4431   case X86::BI__builtin_ia32_vpermilpd256:
4432   case X86::BI__builtin_ia32_roundps:
4433   case X86::BI__builtin_ia32_roundpd:
4434   case X86::BI__builtin_ia32_roundps256:
4435   case X86::BI__builtin_ia32_roundpd256:
4436   case X86::BI__builtin_ia32_getmantpd128_mask:
4437   case X86::BI__builtin_ia32_getmantpd256_mask:
4438   case X86::BI__builtin_ia32_getmantps128_mask:
4439   case X86::BI__builtin_ia32_getmantps256_mask:
4440   case X86::BI__builtin_ia32_getmantpd512_mask:
4441   case X86::BI__builtin_ia32_getmantps512_mask:
4442   case X86::BI__builtin_ia32_vec_ext_v16qi:
4443   case X86::BI__builtin_ia32_vec_ext_v16hi:
4444     i = 1; l = 0; u = 15;
4445     break;
4446   case X86::BI__builtin_ia32_pblendd128:
4447   case X86::BI__builtin_ia32_blendps:
4448   case X86::BI__builtin_ia32_blendpd256:
4449   case X86::BI__builtin_ia32_shufpd256:
4450   case X86::BI__builtin_ia32_roundss:
4451   case X86::BI__builtin_ia32_roundsd:
4452   case X86::BI__builtin_ia32_rangepd128_mask:
4453   case X86::BI__builtin_ia32_rangepd256_mask:
4454   case X86::BI__builtin_ia32_rangepd512_mask:
4455   case X86::BI__builtin_ia32_rangeps128_mask:
4456   case X86::BI__builtin_ia32_rangeps256_mask:
4457   case X86::BI__builtin_ia32_rangeps512_mask:
4458   case X86::BI__builtin_ia32_getmantsd_round_mask:
4459   case X86::BI__builtin_ia32_getmantss_round_mask:
4460   case X86::BI__builtin_ia32_vec_set_v16qi:
4461   case X86::BI__builtin_ia32_vec_set_v16hi:
4462     i = 2; l = 0; u = 15;
4463     break;
4464   case X86::BI__builtin_ia32_vec_ext_v32qi:
4465     i = 1; l = 0; u = 31;
4466     break;
4467   case X86::BI__builtin_ia32_cmpps:
4468   case X86::BI__builtin_ia32_cmpss:
4469   case X86::BI__builtin_ia32_cmppd:
4470   case X86::BI__builtin_ia32_cmpsd:
4471   case X86::BI__builtin_ia32_cmpps256:
4472   case X86::BI__builtin_ia32_cmppd256:
4473   case X86::BI__builtin_ia32_cmpps128_mask:
4474   case X86::BI__builtin_ia32_cmppd128_mask:
4475   case X86::BI__builtin_ia32_cmpps256_mask:
4476   case X86::BI__builtin_ia32_cmppd256_mask:
4477   case X86::BI__builtin_ia32_cmpps512_mask:
4478   case X86::BI__builtin_ia32_cmppd512_mask:
4479   case X86::BI__builtin_ia32_cmpsd_mask:
4480   case X86::BI__builtin_ia32_cmpss_mask:
4481   case X86::BI__builtin_ia32_vec_set_v32qi:
4482     i = 2; l = 0; u = 31;
4483     break;
4484   case X86::BI__builtin_ia32_permdf256:
4485   case X86::BI__builtin_ia32_permdi256:
4486   case X86::BI__builtin_ia32_permdf512:
4487   case X86::BI__builtin_ia32_permdi512:
4488   case X86::BI__builtin_ia32_vpermilps:
4489   case X86::BI__builtin_ia32_vpermilps256:
4490   case X86::BI__builtin_ia32_vpermilpd512:
4491   case X86::BI__builtin_ia32_vpermilps512:
4492   case X86::BI__builtin_ia32_pshufd:
4493   case X86::BI__builtin_ia32_pshufd256:
4494   case X86::BI__builtin_ia32_pshufd512:
4495   case X86::BI__builtin_ia32_pshufhw:
4496   case X86::BI__builtin_ia32_pshufhw256:
4497   case X86::BI__builtin_ia32_pshufhw512:
4498   case X86::BI__builtin_ia32_pshuflw:
4499   case X86::BI__builtin_ia32_pshuflw256:
4500   case X86::BI__builtin_ia32_pshuflw512:
4501   case X86::BI__builtin_ia32_vcvtps2ph:
4502   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4503   case X86::BI__builtin_ia32_vcvtps2ph256:
4504   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4505   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4506   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4507   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4508   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4509   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4510   case X86::BI__builtin_ia32_rndscaleps_mask:
4511   case X86::BI__builtin_ia32_rndscalepd_mask:
4512   case X86::BI__builtin_ia32_reducepd128_mask:
4513   case X86::BI__builtin_ia32_reducepd256_mask:
4514   case X86::BI__builtin_ia32_reducepd512_mask:
4515   case X86::BI__builtin_ia32_reduceps128_mask:
4516   case X86::BI__builtin_ia32_reduceps256_mask:
4517   case X86::BI__builtin_ia32_reduceps512_mask:
4518   case X86::BI__builtin_ia32_prold512:
4519   case X86::BI__builtin_ia32_prolq512:
4520   case X86::BI__builtin_ia32_prold128:
4521   case X86::BI__builtin_ia32_prold256:
4522   case X86::BI__builtin_ia32_prolq128:
4523   case X86::BI__builtin_ia32_prolq256:
4524   case X86::BI__builtin_ia32_prord512:
4525   case X86::BI__builtin_ia32_prorq512:
4526   case X86::BI__builtin_ia32_prord128:
4527   case X86::BI__builtin_ia32_prord256:
4528   case X86::BI__builtin_ia32_prorq128:
4529   case X86::BI__builtin_ia32_prorq256:
4530   case X86::BI__builtin_ia32_fpclasspd128_mask:
4531   case X86::BI__builtin_ia32_fpclasspd256_mask:
4532   case X86::BI__builtin_ia32_fpclassps128_mask:
4533   case X86::BI__builtin_ia32_fpclassps256_mask:
4534   case X86::BI__builtin_ia32_fpclassps512_mask:
4535   case X86::BI__builtin_ia32_fpclasspd512_mask:
4536   case X86::BI__builtin_ia32_fpclasssd_mask:
4537   case X86::BI__builtin_ia32_fpclassss_mask:
4538   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4539   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4540   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4541   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4542   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4543   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4544   case X86::BI__builtin_ia32_kshiftliqi:
4545   case X86::BI__builtin_ia32_kshiftlihi:
4546   case X86::BI__builtin_ia32_kshiftlisi:
4547   case X86::BI__builtin_ia32_kshiftlidi:
4548   case X86::BI__builtin_ia32_kshiftriqi:
4549   case X86::BI__builtin_ia32_kshiftrihi:
4550   case X86::BI__builtin_ia32_kshiftrisi:
4551   case X86::BI__builtin_ia32_kshiftridi:
4552     i = 1; l = 0; u = 255;
4553     break;
4554   case X86::BI__builtin_ia32_vperm2f128_pd256:
4555   case X86::BI__builtin_ia32_vperm2f128_ps256:
4556   case X86::BI__builtin_ia32_vperm2f128_si256:
4557   case X86::BI__builtin_ia32_permti256:
4558   case X86::BI__builtin_ia32_pblendw128:
4559   case X86::BI__builtin_ia32_pblendw256:
4560   case X86::BI__builtin_ia32_blendps256:
4561   case X86::BI__builtin_ia32_pblendd256:
4562   case X86::BI__builtin_ia32_palignr128:
4563   case X86::BI__builtin_ia32_palignr256:
4564   case X86::BI__builtin_ia32_palignr512:
4565   case X86::BI__builtin_ia32_alignq512:
4566   case X86::BI__builtin_ia32_alignd512:
4567   case X86::BI__builtin_ia32_alignd128:
4568   case X86::BI__builtin_ia32_alignd256:
4569   case X86::BI__builtin_ia32_alignq128:
4570   case X86::BI__builtin_ia32_alignq256:
4571   case X86::BI__builtin_ia32_vcomisd:
4572   case X86::BI__builtin_ia32_vcomiss:
4573   case X86::BI__builtin_ia32_shuf_f32x4:
4574   case X86::BI__builtin_ia32_shuf_f64x2:
4575   case X86::BI__builtin_ia32_shuf_i32x4:
4576   case X86::BI__builtin_ia32_shuf_i64x2:
4577   case X86::BI__builtin_ia32_shufpd512:
4578   case X86::BI__builtin_ia32_shufps:
4579   case X86::BI__builtin_ia32_shufps256:
4580   case X86::BI__builtin_ia32_shufps512:
4581   case X86::BI__builtin_ia32_dbpsadbw128:
4582   case X86::BI__builtin_ia32_dbpsadbw256:
4583   case X86::BI__builtin_ia32_dbpsadbw512:
4584   case X86::BI__builtin_ia32_vpshldd128:
4585   case X86::BI__builtin_ia32_vpshldd256:
4586   case X86::BI__builtin_ia32_vpshldd512:
4587   case X86::BI__builtin_ia32_vpshldq128:
4588   case X86::BI__builtin_ia32_vpshldq256:
4589   case X86::BI__builtin_ia32_vpshldq512:
4590   case X86::BI__builtin_ia32_vpshldw128:
4591   case X86::BI__builtin_ia32_vpshldw256:
4592   case X86::BI__builtin_ia32_vpshldw512:
4593   case X86::BI__builtin_ia32_vpshrdd128:
4594   case X86::BI__builtin_ia32_vpshrdd256:
4595   case X86::BI__builtin_ia32_vpshrdd512:
4596   case X86::BI__builtin_ia32_vpshrdq128:
4597   case X86::BI__builtin_ia32_vpshrdq256:
4598   case X86::BI__builtin_ia32_vpshrdq512:
4599   case X86::BI__builtin_ia32_vpshrdw128:
4600   case X86::BI__builtin_ia32_vpshrdw256:
4601   case X86::BI__builtin_ia32_vpshrdw512:
4602     i = 2; l = 0; u = 255;
4603     break;
4604   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4605   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4606   case X86::BI__builtin_ia32_fixupimmps512_mask:
4607   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4608   case X86::BI__builtin_ia32_fixupimmsd_mask:
4609   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4610   case X86::BI__builtin_ia32_fixupimmss_mask:
4611   case X86::BI__builtin_ia32_fixupimmss_maskz:
4612   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4613   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4614   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4615   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4616   case X86::BI__builtin_ia32_fixupimmps128_mask:
4617   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4618   case X86::BI__builtin_ia32_fixupimmps256_mask:
4619   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4620   case X86::BI__builtin_ia32_pternlogd512_mask:
4621   case X86::BI__builtin_ia32_pternlogd512_maskz:
4622   case X86::BI__builtin_ia32_pternlogq512_mask:
4623   case X86::BI__builtin_ia32_pternlogq512_maskz:
4624   case X86::BI__builtin_ia32_pternlogd128_mask:
4625   case X86::BI__builtin_ia32_pternlogd128_maskz:
4626   case X86::BI__builtin_ia32_pternlogd256_mask:
4627   case X86::BI__builtin_ia32_pternlogd256_maskz:
4628   case X86::BI__builtin_ia32_pternlogq128_mask:
4629   case X86::BI__builtin_ia32_pternlogq128_maskz:
4630   case X86::BI__builtin_ia32_pternlogq256_mask:
4631   case X86::BI__builtin_ia32_pternlogq256_maskz:
4632     i = 3; l = 0; u = 255;
4633     break;
4634   case X86::BI__builtin_ia32_gatherpfdpd:
4635   case X86::BI__builtin_ia32_gatherpfdps:
4636   case X86::BI__builtin_ia32_gatherpfqpd:
4637   case X86::BI__builtin_ia32_gatherpfqps:
4638   case X86::BI__builtin_ia32_scatterpfdpd:
4639   case X86::BI__builtin_ia32_scatterpfdps:
4640   case X86::BI__builtin_ia32_scatterpfqpd:
4641   case X86::BI__builtin_ia32_scatterpfqps:
4642     i = 4; l = 2; u = 3;
4643     break;
4644   case X86::BI__builtin_ia32_reducesd_mask:
4645   case X86::BI__builtin_ia32_reducess_mask:
4646   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4647   case X86::BI__builtin_ia32_rndscaless_round_mask:
4648     i = 4; l = 0; u = 255;
4649     break;
4650   }
4651 
4652   // Note that we don't force a hard error on the range check here, allowing
4653   // template-generated or macro-generated dead code to potentially have out-of-
4654   // range values. These need to code generate, but don't need to necessarily
4655   // make any sense. We use a warning that defaults to an error.
4656   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4657 }
4658 
4659 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4660 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4661 /// Returns true when the format fits the function and the FormatStringInfo has
4662 /// been populated.
4663 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4664                                FormatStringInfo *FSI) {
4665   FSI->HasVAListArg = Format->getFirstArg() == 0;
4666   FSI->FormatIdx = Format->getFormatIdx() - 1;
4667   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4668 
4669   // The way the format attribute works in GCC, the implicit this argument
4670   // of member functions is counted. However, it doesn't appear in our own
4671   // lists, so decrement format_idx in that case.
4672   if (IsCXXMember) {
4673     if(FSI->FormatIdx == 0)
4674       return false;
4675     --FSI->FormatIdx;
4676     if (FSI->FirstDataArg != 0)
4677       --FSI->FirstDataArg;
4678   }
4679   return true;
4680 }
4681 
4682 /// Checks if a the given expression evaluates to null.
4683 ///
4684 /// Returns true if the value evaluates to null.
4685 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4686   // If the expression has non-null type, it doesn't evaluate to null.
4687   if (auto nullability
4688         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4689     if (*nullability == NullabilityKind::NonNull)
4690       return false;
4691   }
4692 
4693   // As a special case, transparent unions initialized with zero are
4694   // considered null for the purposes of the nonnull attribute.
4695   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4696     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4697       if (const CompoundLiteralExpr *CLE =
4698           dyn_cast<CompoundLiteralExpr>(Expr))
4699         if (const InitListExpr *ILE =
4700             dyn_cast<InitListExpr>(CLE->getInitializer()))
4701           Expr = ILE->getInit(0);
4702   }
4703 
4704   bool Result;
4705   return (!Expr->isValueDependent() &&
4706           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4707           !Result);
4708 }
4709 
4710 static void CheckNonNullArgument(Sema &S,
4711                                  const Expr *ArgExpr,
4712                                  SourceLocation CallSiteLoc) {
4713   if (CheckNonNullExpr(S, ArgExpr))
4714     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4715                           S.PDiag(diag::warn_null_arg)
4716                               << ArgExpr->getSourceRange());
4717 }
4718 
4719 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4720   FormatStringInfo FSI;
4721   if ((GetFormatStringType(Format) == FST_NSString) &&
4722       getFormatStringInfo(Format, false, &FSI)) {
4723     Idx = FSI.FormatIdx;
4724     return true;
4725   }
4726   return false;
4727 }
4728 
4729 /// Diagnose use of %s directive in an NSString which is being passed
4730 /// as formatting string to formatting method.
4731 static void
4732 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4733                                         const NamedDecl *FDecl,
4734                                         Expr **Args,
4735                                         unsigned NumArgs) {
4736   unsigned Idx = 0;
4737   bool Format = false;
4738   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4739   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4740     Idx = 2;
4741     Format = true;
4742   }
4743   else
4744     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4745       if (S.GetFormatNSStringIdx(I, Idx)) {
4746         Format = true;
4747         break;
4748       }
4749     }
4750   if (!Format || NumArgs <= Idx)
4751     return;
4752   const Expr *FormatExpr = Args[Idx];
4753   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4754     FormatExpr = CSCE->getSubExpr();
4755   const StringLiteral *FormatString;
4756   if (const ObjCStringLiteral *OSL =
4757       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4758     FormatString = OSL->getString();
4759   else
4760     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4761   if (!FormatString)
4762     return;
4763   if (S.FormatStringHasSArg(FormatString)) {
4764     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4765       << "%s" << 1 << 1;
4766     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4767       << FDecl->getDeclName();
4768   }
4769 }
4770 
4771 /// Determine whether the given type has a non-null nullability annotation.
4772 static bool isNonNullType(ASTContext &ctx, QualType type) {
4773   if (auto nullability = type->getNullability(ctx))
4774     return *nullability == NullabilityKind::NonNull;
4775 
4776   return false;
4777 }
4778 
4779 static void CheckNonNullArguments(Sema &S,
4780                                   const NamedDecl *FDecl,
4781                                   const FunctionProtoType *Proto,
4782                                   ArrayRef<const Expr *> Args,
4783                                   SourceLocation CallSiteLoc) {
4784   assert((FDecl || Proto) && "Need a function declaration or prototype");
4785 
4786   // Already checked by by constant evaluator.
4787   if (S.isConstantEvaluated())
4788     return;
4789   // Check the attributes attached to the method/function itself.
4790   llvm::SmallBitVector NonNullArgs;
4791   if (FDecl) {
4792     // Handle the nonnull attribute on the function/method declaration itself.
4793     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4794       if (!NonNull->args_size()) {
4795         // Easy case: all pointer arguments are nonnull.
4796         for (const auto *Arg : Args)
4797           if (S.isValidPointerAttrType(Arg->getType()))
4798             CheckNonNullArgument(S, Arg, CallSiteLoc);
4799         return;
4800       }
4801 
4802       for (const ParamIdx &Idx : NonNull->args()) {
4803         unsigned IdxAST = Idx.getASTIndex();
4804         if (IdxAST >= Args.size())
4805           continue;
4806         if (NonNullArgs.empty())
4807           NonNullArgs.resize(Args.size());
4808         NonNullArgs.set(IdxAST);
4809       }
4810     }
4811   }
4812 
4813   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4814     // Handle the nonnull attribute on the parameters of the
4815     // function/method.
4816     ArrayRef<ParmVarDecl*> parms;
4817     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4818       parms = FD->parameters();
4819     else
4820       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4821 
4822     unsigned ParamIndex = 0;
4823     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4824          I != E; ++I, ++ParamIndex) {
4825       const ParmVarDecl *PVD = *I;
4826       if (PVD->hasAttr<NonNullAttr>() ||
4827           isNonNullType(S.Context, PVD->getType())) {
4828         if (NonNullArgs.empty())
4829           NonNullArgs.resize(Args.size());
4830 
4831         NonNullArgs.set(ParamIndex);
4832       }
4833     }
4834   } else {
4835     // If we have a non-function, non-method declaration but no
4836     // function prototype, try to dig out the function prototype.
4837     if (!Proto) {
4838       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4839         QualType type = VD->getType().getNonReferenceType();
4840         if (auto pointerType = type->getAs<PointerType>())
4841           type = pointerType->getPointeeType();
4842         else if (auto blockType = type->getAs<BlockPointerType>())
4843           type = blockType->getPointeeType();
4844         // FIXME: data member pointers?
4845 
4846         // Dig out the function prototype, if there is one.
4847         Proto = type->getAs<FunctionProtoType>();
4848       }
4849     }
4850 
4851     // Fill in non-null argument information from the nullability
4852     // information on the parameter types (if we have them).
4853     if (Proto) {
4854       unsigned Index = 0;
4855       for (auto paramType : Proto->getParamTypes()) {
4856         if (isNonNullType(S.Context, paramType)) {
4857           if (NonNullArgs.empty())
4858             NonNullArgs.resize(Args.size());
4859 
4860           NonNullArgs.set(Index);
4861         }
4862 
4863         ++Index;
4864       }
4865     }
4866   }
4867 
4868   // Check for non-null arguments.
4869   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4870        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4871     if (NonNullArgs[ArgIndex])
4872       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4873   }
4874 }
4875 
4876 /// Warn if a pointer or reference argument passed to a function points to an
4877 /// object that is less aligned than the parameter. This can happen when
4878 /// creating a typedef with a lower alignment than the original type and then
4879 /// calling functions defined in terms of the original type.
4880 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4881                              StringRef ParamName, QualType ArgTy,
4882                              QualType ParamTy) {
4883 
4884   // If a function accepts a pointer or reference type
4885   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4886     return;
4887 
4888   // If the parameter is a pointer type, get the pointee type for the
4889   // argument too. If the parameter is a reference type, don't try to get
4890   // the pointee type for the argument.
4891   if (ParamTy->isPointerType())
4892     ArgTy = ArgTy->getPointeeType();
4893 
4894   // Remove reference or pointer
4895   ParamTy = ParamTy->getPointeeType();
4896 
4897   // Find expected alignment, and the actual alignment of the passed object.
4898   // getTypeAlignInChars requires complete types
4899   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4900       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4901       ArgTy->isUndeducedType())
4902     return;
4903 
4904   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4905   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4906 
4907   // If the argument is less aligned than the parameter, there is a
4908   // potential alignment issue.
4909   if (ArgAlign < ParamAlign)
4910     Diag(Loc, diag::warn_param_mismatched_alignment)
4911         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4912         << ParamName << FDecl;
4913 }
4914 
4915 /// Handles the checks for format strings, non-POD arguments to vararg
4916 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4917 /// attributes.
4918 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4919                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4920                      bool IsMemberFunction, SourceLocation Loc,
4921                      SourceRange Range, VariadicCallType CallType) {
4922   // FIXME: We should check as much as we can in the template definition.
4923   if (CurContext->isDependentContext())
4924     return;
4925 
4926   // Printf and scanf checking.
4927   llvm::SmallBitVector CheckedVarArgs;
4928   if (FDecl) {
4929     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4930       // Only create vector if there are format attributes.
4931       CheckedVarArgs.resize(Args.size());
4932 
4933       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4934                            CheckedVarArgs);
4935     }
4936   }
4937 
4938   // Refuse POD arguments that weren't caught by the format string
4939   // checks above.
4940   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4941   if (CallType != VariadicDoesNotApply &&
4942       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4943     unsigned NumParams = Proto ? Proto->getNumParams()
4944                        : FDecl && isa<FunctionDecl>(FDecl)
4945                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4946                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4947                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4948                        : 0;
4949 
4950     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4951       // Args[ArgIdx] can be null in malformed code.
4952       if (const Expr *Arg = Args[ArgIdx]) {
4953         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4954           checkVariadicArgument(Arg, CallType);
4955       }
4956     }
4957   }
4958 
4959   if (FDecl || Proto) {
4960     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4961 
4962     // Type safety checking.
4963     if (FDecl) {
4964       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4965         CheckArgumentWithTypeTag(I, Args, Loc);
4966     }
4967   }
4968 
4969   // Check that passed arguments match the alignment of original arguments.
4970   // Try to get the missing prototype from the declaration.
4971   if (!Proto && FDecl) {
4972     const auto *FT = FDecl->getFunctionType();
4973     if (isa_and_nonnull<FunctionProtoType>(FT))
4974       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4975   }
4976   if (Proto) {
4977     // For variadic functions, we may have more args than parameters.
4978     // For some K&R functions, we may have less args than parameters.
4979     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4980     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4981       // Args[ArgIdx] can be null in malformed code.
4982       if (const Expr *Arg = Args[ArgIdx]) {
4983         if (Arg->containsErrors())
4984           continue;
4985 
4986         QualType ParamTy = Proto->getParamType(ArgIdx);
4987         QualType ArgTy = Arg->getType();
4988         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4989                           ArgTy, ParamTy);
4990       }
4991     }
4992   }
4993 
4994   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4995     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4996     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4997     if (!Arg->isValueDependent()) {
4998       Expr::EvalResult Align;
4999       if (Arg->EvaluateAsInt(Align, Context)) {
5000         const llvm::APSInt &I = Align.Val.getInt();
5001         if (!I.isPowerOf2())
5002           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5003               << Arg->getSourceRange();
5004 
5005         if (I > Sema::MaximumAlignment)
5006           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5007               << Arg->getSourceRange() << Sema::MaximumAlignment;
5008       }
5009     }
5010   }
5011 
5012   if (FD)
5013     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5014 }
5015 
5016 /// CheckConstructorCall - Check a constructor call for correctness and safety
5017 /// properties not enforced by the C type system.
5018 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5019                                 ArrayRef<const Expr *> Args,
5020                                 const FunctionProtoType *Proto,
5021                                 SourceLocation Loc) {
5022   VariadicCallType CallType =
5023       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5024 
5025   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5026   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5027                     Context.getPointerType(Ctor->getThisObjectType()));
5028 
5029   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5030             Loc, SourceRange(), CallType);
5031 }
5032 
5033 /// CheckFunctionCall - Check a direct function call for various correctness
5034 /// and safety properties not strictly enforced by the C type system.
5035 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5036                              const FunctionProtoType *Proto) {
5037   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5038                               isa<CXXMethodDecl>(FDecl);
5039   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5040                           IsMemberOperatorCall;
5041   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5042                                                   TheCall->getCallee());
5043   Expr** Args = TheCall->getArgs();
5044   unsigned NumArgs = TheCall->getNumArgs();
5045 
5046   Expr *ImplicitThis = nullptr;
5047   if (IsMemberOperatorCall) {
5048     // If this is a call to a member operator, hide the first argument
5049     // from checkCall.
5050     // FIXME: Our choice of AST representation here is less than ideal.
5051     ImplicitThis = Args[0];
5052     ++Args;
5053     --NumArgs;
5054   } else if (IsMemberFunction)
5055     ImplicitThis =
5056         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5057 
5058   if (ImplicitThis) {
5059     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5060     // used.
5061     QualType ThisType = ImplicitThis->getType();
5062     if (!ThisType->isPointerType()) {
5063       assert(!ThisType->isReferenceType());
5064       ThisType = Context.getPointerType(ThisType);
5065     }
5066 
5067     QualType ThisTypeFromDecl =
5068         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5069 
5070     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5071                       ThisTypeFromDecl);
5072   }
5073 
5074   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5075             IsMemberFunction, TheCall->getRParenLoc(),
5076             TheCall->getCallee()->getSourceRange(), CallType);
5077 
5078   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5079   // None of the checks below are needed for functions that don't have
5080   // simple names (e.g., C++ conversion functions).
5081   if (!FnInfo)
5082     return false;
5083 
5084   CheckTCBEnforcement(TheCall, FDecl);
5085 
5086   CheckAbsoluteValueFunction(TheCall, FDecl);
5087   CheckMaxUnsignedZero(TheCall, FDecl);
5088 
5089   if (getLangOpts().ObjC)
5090     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5091 
5092   unsigned CMId = FDecl->getMemoryFunctionKind();
5093 
5094   // Handle memory setting and copying functions.
5095   switch (CMId) {
5096   case 0:
5097     return false;
5098   case Builtin::BIstrlcpy: // fallthrough
5099   case Builtin::BIstrlcat:
5100     CheckStrlcpycatArguments(TheCall, FnInfo);
5101     break;
5102   case Builtin::BIstrncat:
5103     CheckStrncatArguments(TheCall, FnInfo);
5104     break;
5105   case Builtin::BIfree:
5106     CheckFreeArguments(TheCall);
5107     break;
5108   default:
5109     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5110   }
5111 
5112   return false;
5113 }
5114 
5115 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5116                                ArrayRef<const Expr *> Args) {
5117   VariadicCallType CallType =
5118       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5119 
5120   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5121             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5122             CallType);
5123 
5124   return false;
5125 }
5126 
5127 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5128                             const FunctionProtoType *Proto) {
5129   QualType Ty;
5130   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5131     Ty = V->getType().getNonReferenceType();
5132   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5133     Ty = F->getType().getNonReferenceType();
5134   else
5135     return false;
5136 
5137   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5138       !Ty->isFunctionProtoType())
5139     return false;
5140 
5141   VariadicCallType CallType;
5142   if (!Proto || !Proto->isVariadic()) {
5143     CallType = VariadicDoesNotApply;
5144   } else if (Ty->isBlockPointerType()) {
5145     CallType = VariadicBlock;
5146   } else { // Ty->isFunctionPointerType()
5147     CallType = VariadicFunction;
5148   }
5149 
5150   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5151             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5152             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5153             TheCall->getCallee()->getSourceRange(), CallType);
5154 
5155   return false;
5156 }
5157 
5158 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5159 /// such as function pointers returned from functions.
5160 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5161   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5162                                                   TheCall->getCallee());
5163   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5164             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5165             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5166             TheCall->getCallee()->getSourceRange(), CallType);
5167 
5168   return false;
5169 }
5170 
5171 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5172   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5173     return false;
5174 
5175   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5176   switch (Op) {
5177   case AtomicExpr::AO__c11_atomic_init:
5178   case AtomicExpr::AO__opencl_atomic_init:
5179     llvm_unreachable("There is no ordering argument for an init");
5180 
5181   case AtomicExpr::AO__c11_atomic_load:
5182   case AtomicExpr::AO__opencl_atomic_load:
5183   case AtomicExpr::AO__atomic_load_n:
5184   case AtomicExpr::AO__atomic_load:
5185     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5186            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5187 
5188   case AtomicExpr::AO__c11_atomic_store:
5189   case AtomicExpr::AO__opencl_atomic_store:
5190   case AtomicExpr::AO__atomic_store:
5191   case AtomicExpr::AO__atomic_store_n:
5192     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5193            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5194            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5195 
5196   default:
5197     return true;
5198   }
5199 }
5200 
5201 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5202                                          AtomicExpr::AtomicOp Op) {
5203   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5204   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5205   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5206   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5207                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5208                          Op);
5209 }
5210 
5211 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5212                                  SourceLocation RParenLoc, MultiExprArg Args,
5213                                  AtomicExpr::AtomicOp Op,
5214                                  AtomicArgumentOrder ArgOrder) {
5215   // All the non-OpenCL operations take one of the following forms.
5216   // The OpenCL operations take the __c11 forms with one extra argument for
5217   // synchronization scope.
5218   enum {
5219     // C    __c11_atomic_init(A *, C)
5220     Init,
5221 
5222     // C    __c11_atomic_load(A *, int)
5223     Load,
5224 
5225     // void __atomic_load(A *, CP, int)
5226     LoadCopy,
5227 
5228     // void __atomic_store(A *, CP, int)
5229     Copy,
5230 
5231     // C    __c11_atomic_add(A *, M, int)
5232     Arithmetic,
5233 
5234     // C    __atomic_exchange_n(A *, CP, int)
5235     Xchg,
5236 
5237     // void __atomic_exchange(A *, C *, CP, int)
5238     GNUXchg,
5239 
5240     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5241     C11CmpXchg,
5242 
5243     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5244     GNUCmpXchg
5245   } Form = Init;
5246 
5247   const unsigned NumForm = GNUCmpXchg + 1;
5248   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5249   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5250   // where:
5251   //   C is an appropriate type,
5252   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5253   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5254   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5255   //   the int parameters are for orderings.
5256 
5257   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5258       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5259       "need to update code for modified forms");
5260   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5261                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5262                         AtomicExpr::AO__atomic_load,
5263                 "need to update code for modified C11 atomics");
5264   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5265                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5266   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5267                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5268                IsOpenCL;
5269   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5270              Op == AtomicExpr::AO__atomic_store_n ||
5271              Op == AtomicExpr::AO__atomic_exchange_n ||
5272              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5273   bool IsAddSub = false;
5274 
5275   switch (Op) {
5276   case AtomicExpr::AO__c11_atomic_init:
5277   case AtomicExpr::AO__opencl_atomic_init:
5278     Form = Init;
5279     break;
5280 
5281   case AtomicExpr::AO__c11_atomic_load:
5282   case AtomicExpr::AO__opencl_atomic_load:
5283   case AtomicExpr::AO__atomic_load_n:
5284     Form = Load;
5285     break;
5286 
5287   case AtomicExpr::AO__atomic_load:
5288     Form = LoadCopy;
5289     break;
5290 
5291   case AtomicExpr::AO__c11_atomic_store:
5292   case AtomicExpr::AO__opencl_atomic_store:
5293   case AtomicExpr::AO__atomic_store:
5294   case AtomicExpr::AO__atomic_store_n:
5295     Form = Copy;
5296     break;
5297 
5298   case AtomicExpr::AO__c11_atomic_fetch_add:
5299   case AtomicExpr::AO__c11_atomic_fetch_sub:
5300   case AtomicExpr::AO__opencl_atomic_fetch_add:
5301   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5302   case AtomicExpr::AO__atomic_fetch_add:
5303   case AtomicExpr::AO__atomic_fetch_sub:
5304   case AtomicExpr::AO__atomic_add_fetch:
5305   case AtomicExpr::AO__atomic_sub_fetch:
5306     IsAddSub = true;
5307     Form = Arithmetic;
5308     break;
5309   case AtomicExpr::AO__c11_atomic_fetch_and:
5310   case AtomicExpr::AO__c11_atomic_fetch_or:
5311   case AtomicExpr::AO__c11_atomic_fetch_xor:
5312   case AtomicExpr::AO__opencl_atomic_fetch_and:
5313   case AtomicExpr::AO__opencl_atomic_fetch_or:
5314   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5315   case AtomicExpr::AO__atomic_fetch_and:
5316   case AtomicExpr::AO__atomic_fetch_or:
5317   case AtomicExpr::AO__atomic_fetch_xor:
5318   case AtomicExpr::AO__atomic_fetch_nand:
5319   case AtomicExpr::AO__atomic_and_fetch:
5320   case AtomicExpr::AO__atomic_or_fetch:
5321   case AtomicExpr::AO__atomic_xor_fetch:
5322   case AtomicExpr::AO__atomic_nand_fetch:
5323     Form = Arithmetic;
5324     break;
5325   case AtomicExpr::AO__c11_atomic_fetch_min:
5326   case AtomicExpr::AO__c11_atomic_fetch_max:
5327   case AtomicExpr::AO__opencl_atomic_fetch_min:
5328   case AtomicExpr::AO__opencl_atomic_fetch_max:
5329   case AtomicExpr::AO__atomic_min_fetch:
5330   case AtomicExpr::AO__atomic_max_fetch:
5331   case AtomicExpr::AO__atomic_fetch_min:
5332   case AtomicExpr::AO__atomic_fetch_max:
5333     Form = Arithmetic;
5334     break;
5335 
5336   case AtomicExpr::AO__c11_atomic_exchange:
5337   case AtomicExpr::AO__opencl_atomic_exchange:
5338   case AtomicExpr::AO__atomic_exchange_n:
5339     Form = Xchg;
5340     break;
5341 
5342   case AtomicExpr::AO__atomic_exchange:
5343     Form = GNUXchg;
5344     break;
5345 
5346   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5347   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5348   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5349   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5350     Form = C11CmpXchg;
5351     break;
5352 
5353   case AtomicExpr::AO__atomic_compare_exchange:
5354   case AtomicExpr::AO__atomic_compare_exchange_n:
5355     Form = GNUCmpXchg;
5356     break;
5357   }
5358 
5359   unsigned AdjustedNumArgs = NumArgs[Form];
5360   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5361     ++AdjustedNumArgs;
5362   // Check we have the right number of arguments.
5363   if (Args.size() < AdjustedNumArgs) {
5364     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5365         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5366         << ExprRange;
5367     return ExprError();
5368   } else if (Args.size() > AdjustedNumArgs) {
5369     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5370          diag::err_typecheck_call_too_many_args)
5371         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5372         << ExprRange;
5373     return ExprError();
5374   }
5375 
5376   // Inspect the first argument of the atomic operation.
5377   Expr *Ptr = Args[0];
5378   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5379   if (ConvertedPtr.isInvalid())
5380     return ExprError();
5381 
5382   Ptr = ConvertedPtr.get();
5383   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5384   if (!pointerType) {
5385     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5386         << Ptr->getType() << Ptr->getSourceRange();
5387     return ExprError();
5388   }
5389 
5390   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5391   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5392   QualType ValType = AtomTy; // 'C'
5393   if (IsC11) {
5394     if (!AtomTy->isAtomicType()) {
5395       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5396           << Ptr->getType() << Ptr->getSourceRange();
5397       return ExprError();
5398     }
5399     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5400         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5401       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5402           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5403           << Ptr->getSourceRange();
5404       return ExprError();
5405     }
5406     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5407   } else if (Form != Load && Form != LoadCopy) {
5408     if (ValType.isConstQualified()) {
5409       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5410           << Ptr->getType() << Ptr->getSourceRange();
5411       return ExprError();
5412     }
5413   }
5414 
5415   // For an arithmetic operation, the implied arithmetic must be well-formed.
5416   if (Form == Arithmetic) {
5417     // gcc does not enforce these rules for GNU atomics, but we do so for
5418     // sanity.
5419     auto IsAllowedValueType = [&](QualType ValType) {
5420       if (ValType->isIntegerType())
5421         return true;
5422       if (ValType->isPointerType())
5423         return true;
5424       if (!ValType->isFloatingType())
5425         return false;
5426       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5427       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5428           &Context.getTargetInfo().getLongDoubleFormat() ==
5429               &llvm::APFloat::x87DoubleExtended())
5430         return false;
5431       return true;
5432     };
5433     if (IsAddSub && !IsAllowedValueType(ValType)) {
5434       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5435           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5436       return ExprError();
5437     }
5438     if (!IsAddSub && !ValType->isIntegerType()) {
5439       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5440           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5441       return ExprError();
5442     }
5443     if (IsC11 && ValType->isPointerType() &&
5444         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5445                             diag::err_incomplete_type)) {
5446       return ExprError();
5447     }
5448   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5449     // For __atomic_*_n operations, the value type must be a scalar integral or
5450     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5451     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5452         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5453     return ExprError();
5454   }
5455 
5456   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5457       !AtomTy->isScalarType()) {
5458     // For GNU atomics, require a trivially-copyable type. This is not part of
5459     // the GNU atomics specification, but we enforce it for sanity.
5460     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5461         << Ptr->getType() << Ptr->getSourceRange();
5462     return ExprError();
5463   }
5464 
5465   switch (ValType.getObjCLifetime()) {
5466   case Qualifiers::OCL_None:
5467   case Qualifiers::OCL_ExplicitNone:
5468     // okay
5469     break;
5470 
5471   case Qualifiers::OCL_Weak:
5472   case Qualifiers::OCL_Strong:
5473   case Qualifiers::OCL_Autoreleasing:
5474     // FIXME: Can this happen? By this point, ValType should be known
5475     // to be trivially copyable.
5476     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5477         << ValType << Ptr->getSourceRange();
5478     return ExprError();
5479   }
5480 
5481   // All atomic operations have an overload which takes a pointer to a volatile
5482   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5483   // into the result or the other operands. Similarly atomic_load takes a
5484   // pointer to a const 'A'.
5485   ValType.removeLocalVolatile();
5486   ValType.removeLocalConst();
5487   QualType ResultType = ValType;
5488   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5489       Form == Init)
5490     ResultType = Context.VoidTy;
5491   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5492     ResultType = Context.BoolTy;
5493 
5494   // The type of a parameter passed 'by value'. In the GNU atomics, such
5495   // arguments are actually passed as pointers.
5496   QualType ByValType = ValType; // 'CP'
5497   bool IsPassedByAddress = false;
5498   if (!IsC11 && !IsN) {
5499     ByValType = Ptr->getType();
5500     IsPassedByAddress = true;
5501   }
5502 
5503   SmallVector<Expr *, 5> APIOrderedArgs;
5504   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5505     APIOrderedArgs.push_back(Args[0]);
5506     switch (Form) {
5507     case Init:
5508     case Load:
5509       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5510       break;
5511     case LoadCopy:
5512     case Copy:
5513     case Arithmetic:
5514     case Xchg:
5515       APIOrderedArgs.push_back(Args[2]); // Val1
5516       APIOrderedArgs.push_back(Args[1]); // Order
5517       break;
5518     case GNUXchg:
5519       APIOrderedArgs.push_back(Args[2]); // Val1
5520       APIOrderedArgs.push_back(Args[3]); // Val2
5521       APIOrderedArgs.push_back(Args[1]); // Order
5522       break;
5523     case C11CmpXchg:
5524       APIOrderedArgs.push_back(Args[2]); // Val1
5525       APIOrderedArgs.push_back(Args[4]); // Val2
5526       APIOrderedArgs.push_back(Args[1]); // Order
5527       APIOrderedArgs.push_back(Args[3]); // OrderFail
5528       break;
5529     case GNUCmpXchg:
5530       APIOrderedArgs.push_back(Args[2]); // Val1
5531       APIOrderedArgs.push_back(Args[4]); // Val2
5532       APIOrderedArgs.push_back(Args[5]); // Weak
5533       APIOrderedArgs.push_back(Args[1]); // Order
5534       APIOrderedArgs.push_back(Args[3]); // OrderFail
5535       break;
5536     }
5537   } else
5538     APIOrderedArgs.append(Args.begin(), Args.end());
5539 
5540   // The first argument's non-CV pointer type is used to deduce the type of
5541   // subsequent arguments, except for:
5542   //  - weak flag (always converted to bool)
5543   //  - memory order (always converted to int)
5544   //  - scope  (always converted to int)
5545   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5546     QualType Ty;
5547     if (i < NumVals[Form] + 1) {
5548       switch (i) {
5549       case 0:
5550         // The first argument is always a pointer. It has a fixed type.
5551         // It is always dereferenced, a nullptr is undefined.
5552         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5553         // Nothing else to do: we already know all we want about this pointer.
5554         continue;
5555       case 1:
5556         // The second argument is the non-atomic operand. For arithmetic, this
5557         // is always passed by value, and for a compare_exchange it is always
5558         // passed by address. For the rest, GNU uses by-address and C11 uses
5559         // by-value.
5560         assert(Form != Load);
5561         if (Form == Arithmetic && ValType->isPointerType())
5562           Ty = Context.getPointerDiffType();
5563         else if (Form == Init || Form == Arithmetic)
5564           Ty = ValType;
5565         else if (Form == Copy || Form == Xchg) {
5566           if (IsPassedByAddress) {
5567             // The value pointer is always dereferenced, a nullptr is undefined.
5568             CheckNonNullArgument(*this, APIOrderedArgs[i],
5569                                  ExprRange.getBegin());
5570           }
5571           Ty = ByValType;
5572         } else {
5573           Expr *ValArg = APIOrderedArgs[i];
5574           // The value pointer is always dereferenced, a nullptr is undefined.
5575           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5576           LangAS AS = LangAS::Default;
5577           // Keep address space of non-atomic pointer type.
5578           if (const PointerType *PtrTy =
5579                   ValArg->getType()->getAs<PointerType>()) {
5580             AS = PtrTy->getPointeeType().getAddressSpace();
5581           }
5582           Ty = Context.getPointerType(
5583               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5584         }
5585         break;
5586       case 2:
5587         // The third argument to compare_exchange / GNU exchange is the desired
5588         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5589         if (IsPassedByAddress)
5590           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5591         Ty = ByValType;
5592         break;
5593       case 3:
5594         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5595         Ty = Context.BoolTy;
5596         break;
5597       }
5598     } else {
5599       // The order(s) and scope are always converted to int.
5600       Ty = Context.IntTy;
5601     }
5602 
5603     InitializedEntity Entity =
5604         InitializedEntity::InitializeParameter(Context, Ty, false);
5605     ExprResult Arg = APIOrderedArgs[i];
5606     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5607     if (Arg.isInvalid())
5608       return true;
5609     APIOrderedArgs[i] = Arg.get();
5610   }
5611 
5612   // Permute the arguments into a 'consistent' order.
5613   SmallVector<Expr*, 5> SubExprs;
5614   SubExprs.push_back(Ptr);
5615   switch (Form) {
5616   case Init:
5617     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5618     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5619     break;
5620   case Load:
5621     SubExprs.push_back(APIOrderedArgs[1]); // Order
5622     break;
5623   case LoadCopy:
5624   case Copy:
5625   case Arithmetic:
5626   case Xchg:
5627     SubExprs.push_back(APIOrderedArgs[2]); // Order
5628     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5629     break;
5630   case GNUXchg:
5631     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5632     SubExprs.push_back(APIOrderedArgs[3]); // Order
5633     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5634     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5635     break;
5636   case C11CmpXchg:
5637     SubExprs.push_back(APIOrderedArgs[3]); // Order
5638     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5639     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5640     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5641     break;
5642   case GNUCmpXchg:
5643     SubExprs.push_back(APIOrderedArgs[4]); // Order
5644     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5645     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5646     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5647     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5648     break;
5649   }
5650 
5651   if (SubExprs.size() >= 2 && Form != Init) {
5652     if (Optional<llvm::APSInt> Result =
5653             SubExprs[1]->getIntegerConstantExpr(Context))
5654       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5655         Diag(SubExprs[1]->getBeginLoc(),
5656              diag::warn_atomic_op_has_invalid_memory_order)
5657             << SubExprs[1]->getSourceRange();
5658   }
5659 
5660   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5661     auto *Scope = Args[Args.size() - 1];
5662     if (Optional<llvm::APSInt> Result =
5663             Scope->getIntegerConstantExpr(Context)) {
5664       if (!ScopeModel->isValid(Result->getZExtValue()))
5665         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5666             << Scope->getSourceRange();
5667     }
5668     SubExprs.push_back(Scope);
5669   }
5670 
5671   AtomicExpr *AE = new (Context)
5672       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5673 
5674   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5675        Op == AtomicExpr::AO__c11_atomic_store ||
5676        Op == AtomicExpr::AO__opencl_atomic_load ||
5677        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5678       Context.AtomicUsesUnsupportedLibcall(AE))
5679     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5680         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5681              Op == AtomicExpr::AO__opencl_atomic_load)
5682                 ? 0
5683                 : 1);
5684 
5685   if (ValType->isExtIntType()) {
5686     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5687     return ExprError();
5688   }
5689 
5690   return AE;
5691 }
5692 
5693 /// checkBuiltinArgument - Given a call to a builtin function, perform
5694 /// normal type-checking on the given argument, updating the call in
5695 /// place.  This is useful when a builtin function requires custom
5696 /// type-checking for some of its arguments but not necessarily all of
5697 /// them.
5698 ///
5699 /// Returns true on error.
5700 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5701   FunctionDecl *Fn = E->getDirectCallee();
5702   assert(Fn && "builtin call without direct callee!");
5703 
5704   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5705   InitializedEntity Entity =
5706     InitializedEntity::InitializeParameter(S.Context, Param);
5707 
5708   ExprResult Arg = E->getArg(0);
5709   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5710   if (Arg.isInvalid())
5711     return true;
5712 
5713   E->setArg(ArgIndex, Arg.get());
5714   return false;
5715 }
5716 
5717 /// We have a call to a function like __sync_fetch_and_add, which is an
5718 /// overloaded function based on the pointer type of its first argument.
5719 /// The main BuildCallExpr routines have already promoted the types of
5720 /// arguments because all of these calls are prototyped as void(...).
5721 ///
5722 /// This function goes through and does final semantic checking for these
5723 /// builtins, as well as generating any warnings.
5724 ExprResult
5725 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5726   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5727   Expr *Callee = TheCall->getCallee();
5728   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5729   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5730 
5731   // Ensure that we have at least one argument to do type inference from.
5732   if (TheCall->getNumArgs() < 1) {
5733     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5734         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5735     return ExprError();
5736   }
5737 
5738   // Inspect the first argument of the atomic builtin.  This should always be
5739   // a pointer type, whose element is an integral scalar or pointer type.
5740   // Because it is a pointer type, we don't have to worry about any implicit
5741   // casts here.
5742   // FIXME: We don't allow floating point scalars as input.
5743   Expr *FirstArg = TheCall->getArg(0);
5744   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5745   if (FirstArgResult.isInvalid())
5746     return ExprError();
5747   FirstArg = FirstArgResult.get();
5748   TheCall->setArg(0, FirstArg);
5749 
5750   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5751   if (!pointerType) {
5752     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5753         << FirstArg->getType() << FirstArg->getSourceRange();
5754     return ExprError();
5755   }
5756 
5757   QualType ValType = pointerType->getPointeeType();
5758   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5759       !ValType->isBlockPointerType()) {
5760     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5761         << FirstArg->getType() << FirstArg->getSourceRange();
5762     return ExprError();
5763   }
5764 
5765   if (ValType.isConstQualified()) {
5766     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5767         << FirstArg->getType() << FirstArg->getSourceRange();
5768     return ExprError();
5769   }
5770 
5771   switch (ValType.getObjCLifetime()) {
5772   case Qualifiers::OCL_None:
5773   case Qualifiers::OCL_ExplicitNone:
5774     // okay
5775     break;
5776 
5777   case Qualifiers::OCL_Weak:
5778   case Qualifiers::OCL_Strong:
5779   case Qualifiers::OCL_Autoreleasing:
5780     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5781         << ValType << FirstArg->getSourceRange();
5782     return ExprError();
5783   }
5784 
5785   // Strip any qualifiers off ValType.
5786   ValType = ValType.getUnqualifiedType();
5787 
5788   // The majority of builtins return a value, but a few have special return
5789   // types, so allow them to override appropriately below.
5790   QualType ResultType = ValType;
5791 
5792   // We need to figure out which concrete builtin this maps onto.  For example,
5793   // __sync_fetch_and_add with a 2 byte object turns into
5794   // __sync_fetch_and_add_2.
5795 #define BUILTIN_ROW(x) \
5796   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5797     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5798 
5799   static const unsigned BuiltinIndices[][5] = {
5800     BUILTIN_ROW(__sync_fetch_and_add),
5801     BUILTIN_ROW(__sync_fetch_and_sub),
5802     BUILTIN_ROW(__sync_fetch_and_or),
5803     BUILTIN_ROW(__sync_fetch_and_and),
5804     BUILTIN_ROW(__sync_fetch_and_xor),
5805     BUILTIN_ROW(__sync_fetch_and_nand),
5806 
5807     BUILTIN_ROW(__sync_add_and_fetch),
5808     BUILTIN_ROW(__sync_sub_and_fetch),
5809     BUILTIN_ROW(__sync_and_and_fetch),
5810     BUILTIN_ROW(__sync_or_and_fetch),
5811     BUILTIN_ROW(__sync_xor_and_fetch),
5812     BUILTIN_ROW(__sync_nand_and_fetch),
5813 
5814     BUILTIN_ROW(__sync_val_compare_and_swap),
5815     BUILTIN_ROW(__sync_bool_compare_and_swap),
5816     BUILTIN_ROW(__sync_lock_test_and_set),
5817     BUILTIN_ROW(__sync_lock_release),
5818     BUILTIN_ROW(__sync_swap)
5819   };
5820 #undef BUILTIN_ROW
5821 
5822   // Determine the index of the size.
5823   unsigned SizeIndex;
5824   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5825   case 1: SizeIndex = 0; break;
5826   case 2: SizeIndex = 1; break;
5827   case 4: SizeIndex = 2; break;
5828   case 8: SizeIndex = 3; break;
5829   case 16: SizeIndex = 4; break;
5830   default:
5831     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5832         << FirstArg->getType() << FirstArg->getSourceRange();
5833     return ExprError();
5834   }
5835 
5836   // Each of these builtins has one pointer argument, followed by some number of
5837   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5838   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5839   // as the number of fixed args.
5840   unsigned BuiltinID = FDecl->getBuiltinID();
5841   unsigned BuiltinIndex, NumFixed = 1;
5842   bool WarnAboutSemanticsChange = false;
5843   switch (BuiltinID) {
5844   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5845   case Builtin::BI__sync_fetch_and_add:
5846   case Builtin::BI__sync_fetch_and_add_1:
5847   case Builtin::BI__sync_fetch_and_add_2:
5848   case Builtin::BI__sync_fetch_and_add_4:
5849   case Builtin::BI__sync_fetch_and_add_8:
5850   case Builtin::BI__sync_fetch_and_add_16:
5851     BuiltinIndex = 0;
5852     break;
5853 
5854   case Builtin::BI__sync_fetch_and_sub:
5855   case Builtin::BI__sync_fetch_and_sub_1:
5856   case Builtin::BI__sync_fetch_and_sub_2:
5857   case Builtin::BI__sync_fetch_and_sub_4:
5858   case Builtin::BI__sync_fetch_and_sub_8:
5859   case Builtin::BI__sync_fetch_and_sub_16:
5860     BuiltinIndex = 1;
5861     break;
5862 
5863   case Builtin::BI__sync_fetch_and_or:
5864   case Builtin::BI__sync_fetch_and_or_1:
5865   case Builtin::BI__sync_fetch_and_or_2:
5866   case Builtin::BI__sync_fetch_and_or_4:
5867   case Builtin::BI__sync_fetch_and_or_8:
5868   case Builtin::BI__sync_fetch_and_or_16:
5869     BuiltinIndex = 2;
5870     break;
5871 
5872   case Builtin::BI__sync_fetch_and_and:
5873   case Builtin::BI__sync_fetch_and_and_1:
5874   case Builtin::BI__sync_fetch_and_and_2:
5875   case Builtin::BI__sync_fetch_and_and_4:
5876   case Builtin::BI__sync_fetch_and_and_8:
5877   case Builtin::BI__sync_fetch_and_and_16:
5878     BuiltinIndex = 3;
5879     break;
5880 
5881   case Builtin::BI__sync_fetch_and_xor:
5882   case Builtin::BI__sync_fetch_and_xor_1:
5883   case Builtin::BI__sync_fetch_and_xor_2:
5884   case Builtin::BI__sync_fetch_and_xor_4:
5885   case Builtin::BI__sync_fetch_and_xor_8:
5886   case Builtin::BI__sync_fetch_and_xor_16:
5887     BuiltinIndex = 4;
5888     break;
5889 
5890   case Builtin::BI__sync_fetch_and_nand:
5891   case Builtin::BI__sync_fetch_and_nand_1:
5892   case Builtin::BI__sync_fetch_and_nand_2:
5893   case Builtin::BI__sync_fetch_and_nand_4:
5894   case Builtin::BI__sync_fetch_and_nand_8:
5895   case Builtin::BI__sync_fetch_and_nand_16:
5896     BuiltinIndex = 5;
5897     WarnAboutSemanticsChange = true;
5898     break;
5899 
5900   case Builtin::BI__sync_add_and_fetch:
5901   case Builtin::BI__sync_add_and_fetch_1:
5902   case Builtin::BI__sync_add_and_fetch_2:
5903   case Builtin::BI__sync_add_and_fetch_4:
5904   case Builtin::BI__sync_add_and_fetch_8:
5905   case Builtin::BI__sync_add_and_fetch_16:
5906     BuiltinIndex = 6;
5907     break;
5908 
5909   case Builtin::BI__sync_sub_and_fetch:
5910   case Builtin::BI__sync_sub_and_fetch_1:
5911   case Builtin::BI__sync_sub_and_fetch_2:
5912   case Builtin::BI__sync_sub_and_fetch_4:
5913   case Builtin::BI__sync_sub_and_fetch_8:
5914   case Builtin::BI__sync_sub_and_fetch_16:
5915     BuiltinIndex = 7;
5916     break;
5917 
5918   case Builtin::BI__sync_and_and_fetch:
5919   case Builtin::BI__sync_and_and_fetch_1:
5920   case Builtin::BI__sync_and_and_fetch_2:
5921   case Builtin::BI__sync_and_and_fetch_4:
5922   case Builtin::BI__sync_and_and_fetch_8:
5923   case Builtin::BI__sync_and_and_fetch_16:
5924     BuiltinIndex = 8;
5925     break;
5926 
5927   case Builtin::BI__sync_or_and_fetch:
5928   case Builtin::BI__sync_or_and_fetch_1:
5929   case Builtin::BI__sync_or_and_fetch_2:
5930   case Builtin::BI__sync_or_and_fetch_4:
5931   case Builtin::BI__sync_or_and_fetch_8:
5932   case Builtin::BI__sync_or_and_fetch_16:
5933     BuiltinIndex = 9;
5934     break;
5935 
5936   case Builtin::BI__sync_xor_and_fetch:
5937   case Builtin::BI__sync_xor_and_fetch_1:
5938   case Builtin::BI__sync_xor_and_fetch_2:
5939   case Builtin::BI__sync_xor_and_fetch_4:
5940   case Builtin::BI__sync_xor_and_fetch_8:
5941   case Builtin::BI__sync_xor_and_fetch_16:
5942     BuiltinIndex = 10;
5943     break;
5944 
5945   case Builtin::BI__sync_nand_and_fetch:
5946   case Builtin::BI__sync_nand_and_fetch_1:
5947   case Builtin::BI__sync_nand_and_fetch_2:
5948   case Builtin::BI__sync_nand_and_fetch_4:
5949   case Builtin::BI__sync_nand_and_fetch_8:
5950   case Builtin::BI__sync_nand_and_fetch_16:
5951     BuiltinIndex = 11;
5952     WarnAboutSemanticsChange = true;
5953     break;
5954 
5955   case Builtin::BI__sync_val_compare_and_swap:
5956   case Builtin::BI__sync_val_compare_and_swap_1:
5957   case Builtin::BI__sync_val_compare_and_swap_2:
5958   case Builtin::BI__sync_val_compare_and_swap_4:
5959   case Builtin::BI__sync_val_compare_and_swap_8:
5960   case Builtin::BI__sync_val_compare_and_swap_16:
5961     BuiltinIndex = 12;
5962     NumFixed = 2;
5963     break;
5964 
5965   case Builtin::BI__sync_bool_compare_and_swap:
5966   case Builtin::BI__sync_bool_compare_and_swap_1:
5967   case Builtin::BI__sync_bool_compare_and_swap_2:
5968   case Builtin::BI__sync_bool_compare_and_swap_4:
5969   case Builtin::BI__sync_bool_compare_and_swap_8:
5970   case Builtin::BI__sync_bool_compare_and_swap_16:
5971     BuiltinIndex = 13;
5972     NumFixed = 2;
5973     ResultType = Context.BoolTy;
5974     break;
5975 
5976   case Builtin::BI__sync_lock_test_and_set:
5977   case Builtin::BI__sync_lock_test_and_set_1:
5978   case Builtin::BI__sync_lock_test_and_set_2:
5979   case Builtin::BI__sync_lock_test_and_set_4:
5980   case Builtin::BI__sync_lock_test_and_set_8:
5981   case Builtin::BI__sync_lock_test_and_set_16:
5982     BuiltinIndex = 14;
5983     break;
5984 
5985   case Builtin::BI__sync_lock_release:
5986   case Builtin::BI__sync_lock_release_1:
5987   case Builtin::BI__sync_lock_release_2:
5988   case Builtin::BI__sync_lock_release_4:
5989   case Builtin::BI__sync_lock_release_8:
5990   case Builtin::BI__sync_lock_release_16:
5991     BuiltinIndex = 15;
5992     NumFixed = 0;
5993     ResultType = Context.VoidTy;
5994     break;
5995 
5996   case Builtin::BI__sync_swap:
5997   case Builtin::BI__sync_swap_1:
5998   case Builtin::BI__sync_swap_2:
5999   case Builtin::BI__sync_swap_4:
6000   case Builtin::BI__sync_swap_8:
6001   case Builtin::BI__sync_swap_16:
6002     BuiltinIndex = 16;
6003     break;
6004   }
6005 
6006   // Now that we know how many fixed arguments we expect, first check that we
6007   // have at least that many.
6008   if (TheCall->getNumArgs() < 1+NumFixed) {
6009     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6010         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6011         << Callee->getSourceRange();
6012     return ExprError();
6013   }
6014 
6015   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6016       << Callee->getSourceRange();
6017 
6018   if (WarnAboutSemanticsChange) {
6019     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6020         << Callee->getSourceRange();
6021   }
6022 
6023   // Get the decl for the concrete builtin from this, we can tell what the
6024   // concrete integer type we should convert to is.
6025   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6026   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6027   FunctionDecl *NewBuiltinDecl;
6028   if (NewBuiltinID == BuiltinID)
6029     NewBuiltinDecl = FDecl;
6030   else {
6031     // Perform builtin lookup to avoid redeclaring it.
6032     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6033     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6034     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6035     assert(Res.getFoundDecl());
6036     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6037     if (!NewBuiltinDecl)
6038       return ExprError();
6039   }
6040 
6041   // The first argument --- the pointer --- has a fixed type; we
6042   // deduce the types of the rest of the arguments accordingly.  Walk
6043   // the remaining arguments, converting them to the deduced value type.
6044   for (unsigned i = 0; i != NumFixed; ++i) {
6045     ExprResult Arg = TheCall->getArg(i+1);
6046 
6047     // GCC does an implicit conversion to the pointer or integer ValType.  This
6048     // can fail in some cases (1i -> int**), check for this error case now.
6049     // Initialize the argument.
6050     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6051                                                    ValType, /*consume*/ false);
6052     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6053     if (Arg.isInvalid())
6054       return ExprError();
6055 
6056     // Okay, we have something that *can* be converted to the right type.  Check
6057     // to see if there is a potentially weird extension going on here.  This can
6058     // happen when you do an atomic operation on something like an char* and
6059     // pass in 42.  The 42 gets converted to char.  This is even more strange
6060     // for things like 45.123 -> char, etc.
6061     // FIXME: Do this check.
6062     TheCall->setArg(i+1, Arg.get());
6063   }
6064 
6065   // Create a new DeclRefExpr to refer to the new decl.
6066   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6067       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6068       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6069       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6070 
6071   // Set the callee in the CallExpr.
6072   // FIXME: This loses syntactic information.
6073   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6074   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6075                                               CK_BuiltinFnToFnPtr);
6076   TheCall->setCallee(PromotedCall.get());
6077 
6078   // Change the result type of the call to match the original value type. This
6079   // is arbitrary, but the codegen for these builtins ins design to handle it
6080   // gracefully.
6081   TheCall->setType(ResultType);
6082 
6083   // Prohibit use of _ExtInt with atomic builtins.
6084   // The arguments would have already been converted to the first argument's
6085   // type, so only need to check the first argument.
6086   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6087   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6088     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6089     return ExprError();
6090   }
6091 
6092   return TheCallResult;
6093 }
6094 
6095 /// SemaBuiltinNontemporalOverloaded - We have a call to
6096 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6097 /// overloaded function based on the pointer type of its last argument.
6098 ///
6099 /// This function goes through and does final semantic checking for these
6100 /// builtins.
6101 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6102   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6103   DeclRefExpr *DRE =
6104       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6105   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6106   unsigned BuiltinID = FDecl->getBuiltinID();
6107   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6108           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6109          "Unexpected nontemporal load/store builtin!");
6110   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6111   unsigned numArgs = isStore ? 2 : 1;
6112 
6113   // Ensure that we have the proper number of arguments.
6114   if (checkArgCount(*this, TheCall, numArgs))
6115     return ExprError();
6116 
6117   // Inspect the last argument of the nontemporal builtin.  This should always
6118   // be a pointer type, from which we imply the type of the memory access.
6119   // Because it is a pointer type, we don't have to worry about any implicit
6120   // casts here.
6121   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6122   ExprResult PointerArgResult =
6123       DefaultFunctionArrayLvalueConversion(PointerArg);
6124 
6125   if (PointerArgResult.isInvalid())
6126     return ExprError();
6127   PointerArg = PointerArgResult.get();
6128   TheCall->setArg(numArgs - 1, PointerArg);
6129 
6130   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6131   if (!pointerType) {
6132     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6133         << PointerArg->getType() << PointerArg->getSourceRange();
6134     return ExprError();
6135   }
6136 
6137   QualType ValType = pointerType->getPointeeType();
6138 
6139   // Strip any qualifiers off ValType.
6140   ValType = ValType.getUnqualifiedType();
6141   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6142       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6143       !ValType->isVectorType()) {
6144     Diag(DRE->getBeginLoc(),
6145          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6146         << PointerArg->getType() << PointerArg->getSourceRange();
6147     return ExprError();
6148   }
6149 
6150   if (!isStore) {
6151     TheCall->setType(ValType);
6152     return TheCallResult;
6153   }
6154 
6155   ExprResult ValArg = TheCall->getArg(0);
6156   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6157       Context, ValType, /*consume*/ false);
6158   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6159   if (ValArg.isInvalid())
6160     return ExprError();
6161 
6162   TheCall->setArg(0, ValArg.get());
6163   TheCall->setType(Context.VoidTy);
6164   return TheCallResult;
6165 }
6166 
6167 /// CheckObjCString - Checks that the argument to the builtin
6168 /// CFString constructor is correct
6169 /// Note: It might also make sense to do the UTF-16 conversion here (would
6170 /// simplify the backend).
6171 bool Sema::CheckObjCString(Expr *Arg) {
6172   Arg = Arg->IgnoreParenCasts();
6173   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6174 
6175   if (!Literal || !Literal->isAscii()) {
6176     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6177         << Arg->getSourceRange();
6178     return true;
6179   }
6180 
6181   if (Literal->containsNonAsciiOrNull()) {
6182     StringRef String = Literal->getString();
6183     unsigned NumBytes = String.size();
6184     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6185     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6186     llvm::UTF16 *ToPtr = &ToBuf[0];
6187 
6188     llvm::ConversionResult Result =
6189         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6190                                  ToPtr + NumBytes, llvm::strictConversion);
6191     // Check for conversion failure.
6192     if (Result != llvm::conversionOK)
6193       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6194           << Arg->getSourceRange();
6195   }
6196   return false;
6197 }
6198 
6199 /// CheckObjCString - Checks that the format string argument to the os_log()
6200 /// and os_trace() functions is correct, and converts it to const char *.
6201 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6202   Arg = Arg->IgnoreParenCasts();
6203   auto *Literal = dyn_cast<StringLiteral>(Arg);
6204   if (!Literal) {
6205     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6206       Literal = ObjcLiteral->getString();
6207     }
6208   }
6209 
6210   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6211     return ExprError(
6212         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6213         << Arg->getSourceRange());
6214   }
6215 
6216   ExprResult Result(Literal);
6217   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6218   InitializedEntity Entity =
6219       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6220   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6221   return Result;
6222 }
6223 
6224 /// Check that the user is calling the appropriate va_start builtin for the
6225 /// target and calling convention.
6226 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6227   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6228   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6229   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6230                     TT.getArch() == llvm::Triple::aarch64_32);
6231   bool IsWindows = TT.isOSWindows();
6232   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6233   if (IsX64 || IsAArch64) {
6234     CallingConv CC = CC_C;
6235     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6236       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6237     if (IsMSVAStart) {
6238       // Don't allow this in System V ABI functions.
6239       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6240         return S.Diag(Fn->getBeginLoc(),
6241                       diag::err_ms_va_start_used_in_sysv_function);
6242     } else {
6243       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6244       // On x64 Windows, don't allow this in System V ABI functions.
6245       // (Yes, that means there's no corresponding way to support variadic
6246       // System V ABI functions on Windows.)
6247       if ((IsWindows && CC == CC_X86_64SysV) ||
6248           (!IsWindows && CC == CC_Win64))
6249         return S.Diag(Fn->getBeginLoc(),
6250                       diag::err_va_start_used_in_wrong_abi_function)
6251                << !IsWindows;
6252     }
6253     return false;
6254   }
6255 
6256   if (IsMSVAStart)
6257     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6258   return false;
6259 }
6260 
6261 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6262                                              ParmVarDecl **LastParam = nullptr) {
6263   // Determine whether the current function, block, or obj-c method is variadic
6264   // and get its parameter list.
6265   bool IsVariadic = false;
6266   ArrayRef<ParmVarDecl *> Params;
6267   DeclContext *Caller = S.CurContext;
6268   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6269     IsVariadic = Block->isVariadic();
6270     Params = Block->parameters();
6271   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6272     IsVariadic = FD->isVariadic();
6273     Params = FD->parameters();
6274   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6275     IsVariadic = MD->isVariadic();
6276     // FIXME: This isn't correct for methods (results in bogus warning).
6277     Params = MD->parameters();
6278   } else if (isa<CapturedDecl>(Caller)) {
6279     // We don't support va_start in a CapturedDecl.
6280     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6281     return true;
6282   } else {
6283     // This must be some other declcontext that parses exprs.
6284     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6285     return true;
6286   }
6287 
6288   if (!IsVariadic) {
6289     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6290     return true;
6291   }
6292 
6293   if (LastParam)
6294     *LastParam = Params.empty() ? nullptr : Params.back();
6295 
6296   return false;
6297 }
6298 
6299 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6300 /// for validity.  Emit an error and return true on failure; return false
6301 /// on success.
6302 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6303   Expr *Fn = TheCall->getCallee();
6304 
6305   if (checkVAStartABI(*this, BuiltinID, Fn))
6306     return true;
6307 
6308   if (checkArgCount(*this, TheCall, 2))
6309     return true;
6310 
6311   // Type-check the first argument normally.
6312   if (checkBuiltinArgument(*this, TheCall, 0))
6313     return true;
6314 
6315   // Check that the current function is variadic, and get its last parameter.
6316   ParmVarDecl *LastParam;
6317   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6318     return true;
6319 
6320   // Verify that the second argument to the builtin is the last argument of the
6321   // current function or method.
6322   bool SecondArgIsLastNamedArgument = false;
6323   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6324 
6325   // These are valid if SecondArgIsLastNamedArgument is false after the next
6326   // block.
6327   QualType Type;
6328   SourceLocation ParamLoc;
6329   bool IsCRegister = false;
6330 
6331   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6332     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6333       SecondArgIsLastNamedArgument = PV == LastParam;
6334 
6335       Type = PV->getType();
6336       ParamLoc = PV->getLocation();
6337       IsCRegister =
6338           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6339     }
6340   }
6341 
6342   if (!SecondArgIsLastNamedArgument)
6343     Diag(TheCall->getArg(1)->getBeginLoc(),
6344          diag::warn_second_arg_of_va_start_not_last_named_param);
6345   else if (IsCRegister || Type->isReferenceType() ||
6346            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6347              // Promotable integers are UB, but enumerations need a bit of
6348              // extra checking to see what their promotable type actually is.
6349              if (!Type->isPromotableIntegerType())
6350                return false;
6351              if (!Type->isEnumeralType())
6352                return true;
6353              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6354              return !(ED &&
6355                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6356            }()) {
6357     unsigned Reason = 0;
6358     if (Type->isReferenceType())  Reason = 1;
6359     else if (IsCRegister)         Reason = 2;
6360     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6361     Diag(ParamLoc, diag::note_parameter_type) << Type;
6362   }
6363 
6364   TheCall->setType(Context.VoidTy);
6365   return false;
6366 }
6367 
6368 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6369   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6370   //                 const char *named_addr);
6371 
6372   Expr *Func = Call->getCallee();
6373 
6374   if (Call->getNumArgs() < 3)
6375     return Diag(Call->getEndLoc(),
6376                 diag::err_typecheck_call_too_few_args_at_least)
6377            << 0 /*function call*/ << 3 << Call->getNumArgs();
6378 
6379   // Type-check the first argument normally.
6380   if (checkBuiltinArgument(*this, Call, 0))
6381     return true;
6382 
6383   // Check that the current function is variadic.
6384   if (checkVAStartIsInVariadicFunction(*this, Func))
6385     return true;
6386 
6387   // __va_start on Windows does not validate the parameter qualifiers
6388 
6389   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6390   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6391 
6392   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6393   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6394 
6395   const QualType &ConstCharPtrTy =
6396       Context.getPointerType(Context.CharTy.withConst());
6397   if (!Arg1Ty->isPointerType() ||
6398       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6399     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6400         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6401         << 0                                      /* qualifier difference */
6402         << 3                                      /* parameter mismatch */
6403         << 2 << Arg1->getType() << ConstCharPtrTy;
6404 
6405   const QualType SizeTy = Context.getSizeType();
6406   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6407     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6408         << Arg2->getType() << SizeTy << 1 /* different class */
6409         << 0                              /* qualifier difference */
6410         << 3                              /* parameter mismatch */
6411         << 3 << Arg2->getType() << SizeTy;
6412 
6413   return false;
6414 }
6415 
6416 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6417 /// friends.  This is declared to take (...), so we have to check everything.
6418 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6419   if (checkArgCount(*this, TheCall, 2))
6420     return true;
6421 
6422   ExprResult OrigArg0 = TheCall->getArg(0);
6423   ExprResult OrigArg1 = TheCall->getArg(1);
6424 
6425   // Do standard promotions between the two arguments, returning their common
6426   // type.
6427   QualType Res = UsualArithmeticConversions(
6428       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6429   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6430     return true;
6431 
6432   // Make sure any conversions are pushed back into the call; this is
6433   // type safe since unordered compare builtins are declared as "_Bool
6434   // foo(...)".
6435   TheCall->setArg(0, OrigArg0.get());
6436   TheCall->setArg(1, OrigArg1.get());
6437 
6438   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6439     return false;
6440 
6441   // If the common type isn't a real floating type, then the arguments were
6442   // invalid for this operation.
6443   if (Res.isNull() || !Res->isRealFloatingType())
6444     return Diag(OrigArg0.get()->getBeginLoc(),
6445                 diag::err_typecheck_call_invalid_ordered_compare)
6446            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6447            << SourceRange(OrigArg0.get()->getBeginLoc(),
6448                           OrigArg1.get()->getEndLoc());
6449 
6450   return false;
6451 }
6452 
6453 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6454 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6455 /// to check everything. We expect the last argument to be a floating point
6456 /// value.
6457 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6458   if (checkArgCount(*this, TheCall, NumArgs))
6459     return true;
6460 
6461   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6462   // on all preceding parameters just being int.  Try all of those.
6463   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6464     Expr *Arg = TheCall->getArg(i);
6465 
6466     if (Arg->isTypeDependent())
6467       return false;
6468 
6469     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6470 
6471     if (Res.isInvalid())
6472       return true;
6473     TheCall->setArg(i, Res.get());
6474   }
6475 
6476   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6477 
6478   if (OrigArg->isTypeDependent())
6479     return false;
6480 
6481   // Usual Unary Conversions will convert half to float, which we want for
6482   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6483   // type how it is, but do normal L->Rvalue conversions.
6484   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6485     OrigArg = UsualUnaryConversions(OrigArg).get();
6486   else
6487     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6488   TheCall->setArg(NumArgs - 1, OrigArg);
6489 
6490   // This operation requires a non-_Complex floating-point number.
6491   if (!OrigArg->getType()->isRealFloatingType())
6492     return Diag(OrigArg->getBeginLoc(),
6493                 diag::err_typecheck_call_invalid_unary_fp)
6494            << OrigArg->getType() << OrigArg->getSourceRange();
6495 
6496   return false;
6497 }
6498 
6499 /// Perform semantic analysis for a call to __builtin_complex.
6500 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6501   if (checkArgCount(*this, TheCall, 2))
6502     return true;
6503 
6504   bool Dependent = false;
6505   for (unsigned I = 0; I != 2; ++I) {
6506     Expr *Arg = TheCall->getArg(I);
6507     QualType T = Arg->getType();
6508     if (T->isDependentType()) {
6509       Dependent = true;
6510       continue;
6511     }
6512 
6513     // Despite supporting _Complex int, GCC requires a real floating point type
6514     // for the operands of __builtin_complex.
6515     if (!T->isRealFloatingType()) {
6516       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6517              << Arg->getType() << Arg->getSourceRange();
6518     }
6519 
6520     ExprResult Converted = DefaultLvalueConversion(Arg);
6521     if (Converted.isInvalid())
6522       return true;
6523     TheCall->setArg(I, Converted.get());
6524   }
6525 
6526   if (Dependent) {
6527     TheCall->setType(Context.DependentTy);
6528     return false;
6529   }
6530 
6531   Expr *Real = TheCall->getArg(0);
6532   Expr *Imag = TheCall->getArg(1);
6533   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6534     return Diag(Real->getBeginLoc(),
6535                 diag::err_typecheck_call_different_arg_types)
6536            << Real->getType() << Imag->getType()
6537            << Real->getSourceRange() << Imag->getSourceRange();
6538   }
6539 
6540   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6541   // don't allow this builtin to form those types either.
6542   // FIXME: Should we allow these types?
6543   if (Real->getType()->isFloat16Type())
6544     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6545            << "_Float16";
6546   if (Real->getType()->isHalfType())
6547     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6548            << "half";
6549 
6550   TheCall->setType(Context.getComplexType(Real->getType()));
6551   return false;
6552 }
6553 
6554 // Customized Sema Checking for VSX builtins that have the following signature:
6555 // vector [...] builtinName(vector [...], vector [...], const int);
6556 // Which takes the same type of vectors (any legal vector type) for the first
6557 // two arguments and takes compile time constant for the third argument.
6558 // Example builtins are :
6559 // vector double vec_xxpermdi(vector double, vector double, int);
6560 // vector short vec_xxsldwi(vector short, vector short, int);
6561 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6562   unsigned ExpectedNumArgs = 3;
6563   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6564     return true;
6565 
6566   // Check the third argument is a compile time constant
6567   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6568     return Diag(TheCall->getBeginLoc(),
6569                 diag::err_vsx_builtin_nonconstant_argument)
6570            << 3 /* argument index */ << TheCall->getDirectCallee()
6571            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6572                           TheCall->getArg(2)->getEndLoc());
6573 
6574   QualType Arg1Ty = TheCall->getArg(0)->getType();
6575   QualType Arg2Ty = TheCall->getArg(1)->getType();
6576 
6577   // Check the type of argument 1 and argument 2 are vectors.
6578   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6579   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6580       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6581     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6582            << TheCall->getDirectCallee()
6583            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6584                           TheCall->getArg(1)->getEndLoc());
6585   }
6586 
6587   // Check the first two arguments are the same type.
6588   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6589     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6590            << TheCall->getDirectCallee()
6591            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6592                           TheCall->getArg(1)->getEndLoc());
6593   }
6594 
6595   // When default clang type checking is turned off and the customized type
6596   // checking is used, the returning type of the function must be explicitly
6597   // set. Otherwise it is _Bool by default.
6598   TheCall->setType(Arg1Ty);
6599 
6600   return false;
6601 }
6602 
6603 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6604 // This is declared to take (...), so we have to check everything.
6605 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6606   if (TheCall->getNumArgs() < 2)
6607     return ExprError(Diag(TheCall->getEndLoc(),
6608                           diag::err_typecheck_call_too_few_args_at_least)
6609                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6610                      << TheCall->getSourceRange());
6611 
6612   // Determine which of the following types of shufflevector we're checking:
6613   // 1) unary, vector mask: (lhs, mask)
6614   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6615   QualType resType = TheCall->getArg(0)->getType();
6616   unsigned numElements = 0;
6617 
6618   if (!TheCall->getArg(0)->isTypeDependent() &&
6619       !TheCall->getArg(1)->isTypeDependent()) {
6620     QualType LHSType = TheCall->getArg(0)->getType();
6621     QualType RHSType = TheCall->getArg(1)->getType();
6622 
6623     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6624       return ExprError(
6625           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6626           << TheCall->getDirectCallee()
6627           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6628                          TheCall->getArg(1)->getEndLoc()));
6629 
6630     numElements = LHSType->castAs<VectorType>()->getNumElements();
6631     unsigned numResElements = TheCall->getNumArgs() - 2;
6632 
6633     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6634     // with mask.  If so, verify that RHS is an integer vector type with the
6635     // same number of elts as lhs.
6636     if (TheCall->getNumArgs() == 2) {
6637       if (!RHSType->hasIntegerRepresentation() ||
6638           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6639         return ExprError(Diag(TheCall->getBeginLoc(),
6640                               diag::err_vec_builtin_incompatible_vector)
6641                          << TheCall->getDirectCallee()
6642                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6643                                         TheCall->getArg(1)->getEndLoc()));
6644     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6645       return ExprError(Diag(TheCall->getBeginLoc(),
6646                             diag::err_vec_builtin_incompatible_vector)
6647                        << TheCall->getDirectCallee()
6648                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6649                                       TheCall->getArg(1)->getEndLoc()));
6650     } else if (numElements != numResElements) {
6651       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6652       resType = Context.getVectorType(eltType, numResElements,
6653                                       VectorType::GenericVector);
6654     }
6655   }
6656 
6657   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6658     if (TheCall->getArg(i)->isTypeDependent() ||
6659         TheCall->getArg(i)->isValueDependent())
6660       continue;
6661 
6662     Optional<llvm::APSInt> Result;
6663     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6664       return ExprError(Diag(TheCall->getBeginLoc(),
6665                             diag::err_shufflevector_nonconstant_argument)
6666                        << TheCall->getArg(i)->getSourceRange());
6667 
6668     // Allow -1 which will be translated to undef in the IR.
6669     if (Result->isSigned() && Result->isAllOnesValue())
6670       continue;
6671 
6672     if (Result->getActiveBits() > 64 ||
6673         Result->getZExtValue() >= numElements * 2)
6674       return ExprError(Diag(TheCall->getBeginLoc(),
6675                             diag::err_shufflevector_argument_too_large)
6676                        << TheCall->getArg(i)->getSourceRange());
6677   }
6678 
6679   SmallVector<Expr*, 32> exprs;
6680 
6681   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6682     exprs.push_back(TheCall->getArg(i));
6683     TheCall->setArg(i, nullptr);
6684   }
6685 
6686   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6687                                          TheCall->getCallee()->getBeginLoc(),
6688                                          TheCall->getRParenLoc());
6689 }
6690 
6691 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6692 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6693                                        SourceLocation BuiltinLoc,
6694                                        SourceLocation RParenLoc) {
6695   ExprValueKind VK = VK_PRValue;
6696   ExprObjectKind OK = OK_Ordinary;
6697   QualType DstTy = TInfo->getType();
6698   QualType SrcTy = E->getType();
6699 
6700   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6701     return ExprError(Diag(BuiltinLoc,
6702                           diag::err_convertvector_non_vector)
6703                      << E->getSourceRange());
6704   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6705     return ExprError(Diag(BuiltinLoc,
6706                           diag::err_convertvector_non_vector_type));
6707 
6708   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6709     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6710     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6711     if (SrcElts != DstElts)
6712       return ExprError(Diag(BuiltinLoc,
6713                             diag::err_convertvector_incompatible_vector)
6714                        << E->getSourceRange());
6715   }
6716 
6717   return new (Context)
6718       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6719 }
6720 
6721 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6722 // This is declared to take (const void*, ...) and can take two
6723 // optional constant int args.
6724 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6725   unsigned NumArgs = TheCall->getNumArgs();
6726 
6727   if (NumArgs > 3)
6728     return Diag(TheCall->getEndLoc(),
6729                 diag::err_typecheck_call_too_many_args_at_most)
6730            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6731 
6732   // Argument 0 is checked for us and the remaining arguments must be
6733   // constant integers.
6734   for (unsigned i = 1; i != NumArgs; ++i)
6735     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6736       return true;
6737 
6738   return false;
6739 }
6740 
6741 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6742 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6743   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6744     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6745            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6746   if (checkArgCount(*this, TheCall, 1))
6747     return true;
6748   Expr *Arg = TheCall->getArg(0);
6749   if (Arg->isInstantiationDependent())
6750     return false;
6751 
6752   QualType ArgTy = Arg->getType();
6753   if (!ArgTy->hasFloatingRepresentation())
6754     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6755            << ArgTy;
6756   if (Arg->isLValue()) {
6757     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6758     TheCall->setArg(0, FirstArg.get());
6759   }
6760   TheCall->setType(TheCall->getArg(0)->getType());
6761   return false;
6762 }
6763 
6764 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6765 // __assume does not evaluate its arguments, and should warn if its argument
6766 // has side effects.
6767 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6768   Expr *Arg = TheCall->getArg(0);
6769   if (Arg->isInstantiationDependent()) return false;
6770 
6771   if (Arg->HasSideEffects(Context))
6772     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6773         << Arg->getSourceRange()
6774         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6775 
6776   return false;
6777 }
6778 
6779 /// Handle __builtin_alloca_with_align. This is declared
6780 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6781 /// than 8.
6782 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6783   // The alignment must be a constant integer.
6784   Expr *Arg = TheCall->getArg(1);
6785 
6786   // We can't check the value of a dependent argument.
6787   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6788     if (const auto *UE =
6789             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6790       if (UE->getKind() == UETT_AlignOf ||
6791           UE->getKind() == UETT_PreferredAlignOf)
6792         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6793             << Arg->getSourceRange();
6794 
6795     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6796 
6797     if (!Result.isPowerOf2())
6798       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6799              << Arg->getSourceRange();
6800 
6801     if (Result < Context.getCharWidth())
6802       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6803              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6804 
6805     if (Result > std::numeric_limits<int32_t>::max())
6806       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6807              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6808   }
6809 
6810   return false;
6811 }
6812 
6813 /// Handle __builtin_assume_aligned. This is declared
6814 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6815 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6816   unsigned NumArgs = TheCall->getNumArgs();
6817 
6818   if (NumArgs > 3)
6819     return Diag(TheCall->getEndLoc(),
6820                 diag::err_typecheck_call_too_many_args_at_most)
6821            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6822 
6823   // The alignment must be a constant integer.
6824   Expr *Arg = TheCall->getArg(1);
6825 
6826   // We can't check the value of a dependent argument.
6827   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6828     llvm::APSInt Result;
6829     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6830       return true;
6831 
6832     if (!Result.isPowerOf2())
6833       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6834              << Arg->getSourceRange();
6835 
6836     if (Result > Sema::MaximumAlignment)
6837       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6838           << Arg->getSourceRange() << Sema::MaximumAlignment;
6839   }
6840 
6841   if (NumArgs > 2) {
6842     ExprResult Arg(TheCall->getArg(2));
6843     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6844       Context.getSizeType(), false);
6845     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6846     if (Arg.isInvalid()) return true;
6847     TheCall->setArg(2, Arg.get());
6848   }
6849 
6850   return false;
6851 }
6852 
6853 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6854   unsigned BuiltinID =
6855       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6856   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6857 
6858   unsigned NumArgs = TheCall->getNumArgs();
6859   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6860   if (NumArgs < NumRequiredArgs) {
6861     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6862            << 0 /* function call */ << NumRequiredArgs << NumArgs
6863            << TheCall->getSourceRange();
6864   }
6865   if (NumArgs >= NumRequiredArgs + 0x100) {
6866     return Diag(TheCall->getEndLoc(),
6867                 diag::err_typecheck_call_too_many_args_at_most)
6868            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6869            << TheCall->getSourceRange();
6870   }
6871   unsigned i = 0;
6872 
6873   // For formatting call, check buffer arg.
6874   if (!IsSizeCall) {
6875     ExprResult Arg(TheCall->getArg(i));
6876     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6877         Context, Context.VoidPtrTy, false);
6878     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6879     if (Arg.isInvalid())
6880       return true;
6881     TheCall->setArg(i, Arg.get());
6882     i++;
6883   }
6884 
6885   // Check string literal arg.
6886   unsigned FormatIdx = i;
6887   {
6888     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6889     if (Arg.isInvalid())
6890       return true;
6891     TheCall->setArg(i, Arg.get());
6892     i++;
6893   }
6894 
6895   // Make sure variadic args are scalar.
6896   unsigned FirstDataArg = i;
6897   while (i < NumArgs) {
6898     ExprResult Arg = DefaultVariadicArgumentPromotion(
6899         TheCall->getArg(i), VariadicFunction, nullptr);
6900     if (Arg.isInvalid())
6901       return true;
6902     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6903     if (ArgSize.getQuantity() >= 0x100) {
6904       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6905              << i << (int)ArgSize.getQuantity() << 0xff
6906              << TheCall->getSourceRange();
6907     }
6908     TheCall->setArg(i, Arg.get());
6909     i++;
6910   }
6911 
6912   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6913   // call to avoid duplicate diagnostics.
6914   if (!IsSizeCall) {
6915     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6916     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6917     bool Success = CheckFormatArguments(
6918         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6919         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6920         CheckedVarArgs);
6921     if (!Success)
6922       return true;
6923   }
6924 
6925   if (IsSizeCall) {
6926     TheCall->setType(Context.getSizeType());
6927   } else {
6928     TheCall->setType(Context.VoidPtrTy);
6929   }
6930   return false;
6931 }
6932 
6933 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6934 /// TheCall is a constant expression.
6935 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6936                                   llvm::APSInt &Result) {
6937   Expr *Arg = TheCall->getArg(ArgNum);
6938   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6939   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6940 
6941   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6942 
6943   Optional<llvm::APSInt> R;
6944   if (!(R = Arg->getIntegerConstantExpr(Context)))
6945     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6946            << FDecl->getDeclName() << Arg->getSourceRange();
6947   Result = *R;
6948   return false;
6949 }
6950 
6951 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6952 /// TheCall is a constant expression in the range [Low, High].
6953 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6954                                        int Low, int High, bool RangeIsError) {
6955   if (isConstantEvaluated())
6956     return false;
6957   llvm::APSInt Result;
6958 
6959   // We can't check the value of a dependent argument.
6960   Expr *Arg = TheCall->getArg(ArgNum);
6961   if (Arg->isTypeDependent() || Arg->isValueDependent())
6962     return false;
6963 
6964   // Check constant-ness first.
6965   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6966     return true;
6967 
6968   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6969     if (RangeIsError)
6970       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6971              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6972     else
6973       // Defer the warning until we know if the code will be emitted so that
6974       // dead code can ignore this.
6975       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6976                           PDiag(diag::warn_argument_invalid_range)
6977                               << toString(Result, 10) << Low << High
6978                               << Arg->getSourceRange());
6979   }
6980 
6981   return false;
6982 }
6983 
6984 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6985 /// TheCall is a constant expression is a multiple of Num..
6986 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6987                                           unsigned Num) {
6988   llvm::APSInt Result;
6989 
6990   // We can't check the value of a dependent argument.
6991   Expr *Arg = TheCall->getArg(ArgNum);
6992   if (Arg->isTypeDependent() || Arg->isValueDependent())
6993     return false;
6994 
6995   // Check constant-ness first.
6996   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6997     return true;
6998 
6999   if (Result.getSExtValue() % Num != 0)
7000     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7001            << Num << Arg->getSourceRange();
7002 
7003   return false;
7004 }
7005 
7006 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7007 /// constant expression representing a power of 2.
7008 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7009   llvm::APSInt Result;
7010 
7011   // We can't check the value of a dependent argument.
7012   Expr *Arg = TheCall->getArg(ArgNum);
7013   if (Arg->isTypeDependent() || Arg->isValueDependent())
7014     return false;
7015 
7016   // Check constant-ness first.
7017   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7018     return true;
7019 
7020   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7021   // and only if x is a power of 2.
7022   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7023     return false;
7024 
7025   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7026          << Arg->getSourceRange();
7027 }
7028 
7029 static bool IsShiftedByte(llvm::APSInt Value) {
7030   if (Value.isNegative())
7031     return false;
7032 
7033   // Check if it's a shifted byte, by shifting it down
7034   while (true) {
7035     // If the value fits in the bottom byte, the check passes.
7036     if (Value < 0x100)
7037       return true;
7038 
7039     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7040     // fails.
7041     if ((Value & 0xFF) != 0)
7042       return false;
7043 
7044     // If the bottom 8 bits are all 0, but something above that is nonzero,
7045     // then shifting the value right by 8 bits won't affect whether it's a
7046     // shifted byte or not. So do that, and go round again.
7047     Value >>= 8;
7048   }
7049 }
7050 
7051 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7052 /// a constant expression representing an arbitrary byte value shifted left by
7053 /// a multiple of 8 bits.
7054 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7055                                              unsigned ArgBits) {
7056   llvm::APSInt Result;
7057 
7058   // We can't check the value of a dependent argument.
7059   Expr *Arg = TheCall->getArg(ArgNum);
7060   if (Arg->isTypeDependent() || Arg->isValueDependent())
7061     return false;
7062 
7063   // Check constant-ness first.
7064   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7065     return true;
7066 
7067   // Truncate to the given size.
7068   Result = Result.getLoBits(ArgBits);
7069   Result.setIsUnsigned(true);
7070 
7071   if (IsShiftedByte(Result))
7072     return false;
7073 
7074   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7075          << Arg->getSourceRange();
7076 }
7077 
7078 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7079 /// TheCall is a constant expression representing either a shifted byte value,
7080 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7081 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7082 /// Arm MVE intrinsics.
7083 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7084                                                    int ArgNum,
7085                                                    unsigned ArgBits) {
7086   llvm::APSInt Result;
7087 
7088   // We can't check the value of a dependent argument.
7089   Expr *Arg = TheCall->getArg(ArgNum);
7090   if (Arg->isTypeDependent() || Arg->isValueDependent())
7091     return false;
7092 
7093   // Check constant-ness first.
7094   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7095     return true;
7096 
7097   // Truncate to the given size.
7098   Result = Result.getLoBits(ArgBits);
7099   Result.setIsUnsigned(true);
7100 
7101   // Check to see if it's in either of the required forms.
7102   if (IsShiftedByte(Result) ||
7103       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7104     return false;
7105 
7106   return Diag(TheCall->getBeginLoc(),
7107               diag::err_argument_not_shifted_byte_or_xxff)
7108          << Arg->getSourceRange();
7109 }
7110 
7111 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7112 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7113   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7114     if (checkArgCount(*this, TheCall, 2))
7115       return true;
7116     Expr *Arg0 = TheCall->getArg(0);
7117     Expr *Arg1 = TheCall->getArg(1);
7118 
7119     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7120     if (FirstArg.isInvalid())
7121       return true;
7122     QualType FirstArgType = FirstArg.get()->getType();
7123     if (!FirstArgType->isAnyPointerType())
7124       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7125                << "first" << FirstArgType << Arg0->getSourceRange();
7126     TheCall->setArg(0, FirstArg.get());
7127 
7128     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7129     if (SecArg.isInvalid())
7130       return true;
7131     QualType SecArgType = SecArg.get()->getType();
7132     if (!SecArgType->isIntegerType())
7133       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7134                << "second" << SecArgType << Arg1->getSourceRange();
7135 
7136     // Derive the return type from the pointer argument.
7137     TheCall->setType(FirstArgType);
7138     return false;
7139   }
7140 
7141   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7142     if (checkArgCount(*this, TheCall, 2))
7143       return true;
7144 
7145     Expr *Arg0 = TheCall->getArg(0);
7146     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7147     if (FirstArg.isInvalid())
7148       return true;
7149     QualType FirstArgType = FirstArg.get()->getType();
7150     if (!FirstArgType->isAnyPointerType())
7151       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7152                << "first" << FirstArgType << Arg0->getSourceRange();
7153     TheCall->setArg(0, FirstArg.get());
7154 
7155     // Derive the return type from the pointer argument.
7156     TheCall->setType(FirstArgType);
7157 
7158     // Second arg must be an constant in range [0,15]
7159     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7160   }
7161 
7162   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7163     if (checkArgCount(*this, TheCall, 2))
7164       return true;
7165     Expr *Arg0 = TheCall->getArg(0);
7166     Expr *Arg1 = TheCall->getArg(1);
7167 
7168     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7169     if (FirstArg.isInvalid())
7170       return true;
7171     QualType FirstArgType = FirstArg.get()->getType();
7172     if (!FirstArgType->isAnyPointerType())
7173       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7174                << "first" << FirstArgType << Arg0->getSourceRange();
7175 
7176     QualType SecArgType = Arg1->getType();
7177     if (!SecArgType->isIntegerType())
7178       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7179                << "second" << SecArgType << Arg1->getSourceRange();
7180     TheCall->setType(Context.IntTy);
7181     return false;
7182   }
7183 
7184   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7185       BuiltinID == AArch64::BI__builtin_arm_stg) {
7186     if (checkArgCount(*this, TheCall, 1))
7187       return true;
7188     Expr *Arg0 = TheCall->getArg(0);
7189     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7190     if (FirstArg.isInvalid())
7191       return true;
7192 
7193     QualType FirstArgType = FirstArg.get()->getType();
7194     if (!FirstArgType->isAnyPointerType())
7195       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7196                << "first" << FirstArgType << Arg0->getSourceRange();
7197     TheCall->setArg(0, FirstArg.get());
7198 
7199     // Derive the return type from the pointer argument.
7200     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7201       TheCall->setType(FirstArgType);
7202     return false;
7203   }
7204 
7205   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7206     Expr *ArgA = TheCall->getArg(0);
7207     Expr *ArgB = TheCall->getArg(1);
7208 
7209     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7210     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7211 
7212     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7213       return true;
7214 
7215     QualType ArgTypeA = ArgExprA.get()->getType();
7216     QualType ArgTypeB = ArgExprB.get()->getType();
7217 
7218     auto isNull = [&] (Expr *E) -> bool {
7219       return E->isNullPointerConstant(
7220                         Context, Expr::NPC_ValueDependentIsNotNull); };
7221 
7222     // argument should be either a pointer or null
7223     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7224       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7225         << "first" << ArgTypeA << ArgA->getSourceRange();
7226 
7227     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7228       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7229         << "second" << ArgTypeB << ArgB->getSourceRange();
7230 
7231     // Ensure Pointee types are compatible
7232     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7233         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7234       QualType pointeeA = ArgTypeA->getPointeeType();
7235       QualType pointeeB = ArgTypeB->getPointeeType();
7236       if (!Context.typesAreCompatible(
7237              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7238              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7239         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7240           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7241           << ArgB->getSourceRange();
7242       }
7243     }
7244 
7245     // at least one argument should be pointer type
7246     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7247       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7248         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7249 
7250     if (isNull(ArgA)) // adopt type of the other pointer
7251       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7252 
7253     if (isNull(ArgB))
7254       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7255 
7256     TheCall->setArg(0, ArgExprA.get());
7257     TheCall->setArg(1, ArgExprB.get());
7258     TheCall->setType(Context.LongLongTy);
7259     return false;
7260   }
7261   assert(false && "Unhandled ARM MTE intrinsic");
7262   return true;
7263 }
7264 
7265 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7266 /// TheCall is an ARM/AArch64 special register string literal.
7267 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7268                                     int ArgNum, unsigned ExpectedFieldNum,
7269                                     bool AllowName) {
7270   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7271                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7272                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7273                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7274                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7275                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7276   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7277                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7278                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7279                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7280                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7281                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7282   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7283 
7284   // We can't check the value of a dependent argument.
7285   Expr *Arg = TheCall->getArg(ArgNum);
7286   if (Arg->isTypeDependent() || Arg->isValueDependent())
7287     return false;
7288 
7289   // Check if the argument is a string literal.
7290   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7291     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7292            << Arg->getSourceRange();
7293 
7294   // Check the type of special register given.
7295   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7296   SmallVector<StringRef, 6> Fields;
7297   Reg.split(Fields, ":");
7298 
7299   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7300     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7301            << Arg->getSourceRange();
7302 
7303   // If the string is the name of a register then we cannot check that it is
7304   // valid here but if the string is of one the forms described in ACLE then we
7305   // can check that the supplied fields are integers and within the valid
7306   // ranges.
7307   if (Fields.size() > 1) {
7308     bool FiveFields = Fields.size() == 5;
7309 
7310     bool ValidString = true;
7311     if (IsARMBuiltin) {
7312       ValidString &= Fields[0].startswith_insensitive("cp") ||
7313                      Fields[0].startswith_insensitive("p");
7314       if (ValidString)
7315         Fields[0] = Fields[0].drop_front(
7316             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7317 
7318       ValidString &= Fields[2].startswith_insensitive("c");
7319       if (ValidString)
7320         Fields[2] = Fields[2].drop_front(1);
7321 
7322       if (FiveFields) {
7323         ValidString &= Fields[3].startswith_insensitive("c");
7324         if (ValidString)
7325           Fields[3] = Fields[3].drop_front(1);
7326       }
7327     }
7328 
7329     SmallVector<int, 5> Ranges;
7330     if (FiveFields)
7331       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7332     else
7333       Ranges.append({15, 7, 15});
7334 
7335     for (unsigned i=0; i<Fields.size(); ++i) {
7336       int IntField;
7337       ValidString &= !Fields[i].getAsInteger(10, IntField);
7338       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7339     }
7340 
7341     if (!ValidString)
7342       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7343              << Arg->getSourceRange();
7344   } else if (IsAArch64Builtin && Fields.size() == 1) {
7345     // If the register name is one of those that appear in the condition below
7346     // and the special register builtin being used is one of the write builtins,
7347     // then we require that the argument provided for writing to the register
7348     // is an integer constant expression. This is because it will be lowered to
7349     // an MSR (immediate) instruction, so we need to know the immediate at
7350     // compile time.
7351     if (TheCall->getNumArgs() != 2)
7352       return false;
7353 
7354     std::string RegLower = Reg.lower();
7355     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7356         RegLower != "pan" && RegLower != "uao")
7357       return false;
7358 
7359     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7360   }
7361 
7362   return false;
7363 }
7364 
7365 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7366 /// Emit an error and return true on failure; return false on success.
7367 /// TypeStr is a string containing the type descriptor of the value returned by
7368 /// the builtin and the descriptors of the expected type of the arguments.
7369 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7370 
7371   assert((TypeStr[0] != '\0') &&
7372          "Invalid types in PPC MMA builtin declaration");
7373 
7374   unsigned Mask = 0;
7375   unsigned ArgNum = 0;
7376 
7377   // The first type in TypeStr is the type of the value returned by the
7378   // builtin. So we first read that type and change the type of TheCall.
7379   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7380   TheCall->setType(type);
7381 
7382   while (*TypeStr != '\0') {
7383     Mask = 0;
7384     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7385     if (ArgNum >= TheCall->getNumArgs()) {
7386       ArgNum++;
7387       break;
7388     }
7389 
7390     Expr *Arg = TheCall->getArg(ArgNum);
7391     QualType ArgType = Arg->getType();
7392 
7393     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7394         (!ExpectedType->isVoidPointerType() &&
7395            ArgType.getCanonicalType() != ExpectedType))
7396       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7397              << ArgType << ExpectedType << 1 << 0 << 0;
7398 
7399     // If the value of the Mask is not 0, we have a constraint in the size of
7400     // the integer argument so here we ensure the argument is a constant that
7401     // is in the valid range.
7402     if (Mask != 0 &&
7403         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7404       return true;
7405 
7406     ArgNum++;
7407   }
7408 
7409   // In case we exited early from the previous loop, there are other types to
7410   // read from TypeStr. So we need to read them all to ensure we have the right
7411   // number of arguments in TheCall and if it is not the case, to display a
7412   // better error message.
7413   while (*TypeStr != '\0') {
7414     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7415     ArgNum++;
7416   }
7417   if (checkArgCount(*this, TheCall, ArgNum))
7418     return true;
7419 
7420   return false;
7421 }
7422 
7423 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7424 /// This checks that the target supports __builtin_longjmp and
7425 /// that val is a constant 1.
7426 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7427   if (!Context.getTargetInfo().hasSjLjLowering())
7428     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7429            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7430 
7431   Expr *Arg = TheCall->getArg(1);
7432   llvm::APSInt Result;
7433 
7434   // TODO: This is less than ideal. Overload this to take a value.
7435   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7436     return true;
7437 
7438   if (Result != 1)
7439     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7440            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7441 
7442   return false;
7443 }
7444 
7445 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7446 /// This checks that the target supports __builtin_setjmp.
7447 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7448   if (!Context.getTargetInfo().hasSjLjLowering())
7449     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7450            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7451   return false;
7452 }
7453 
7454 namespace {
7455 
7456 class UncoveredArgHandler {
7457   enum { Unknown = -1, AllCovered = -2 };
7458 
7459   signed FirstUncoveredArg = Unknown;
7460   SmallVector<const Expr *, 4> DiagnosticExprs;
7461 
7462 public:
7463   UncoveredArgHandler() = default;
7464 
7465   bool hasUncoveredArg() const {
7466     return (FirstUncoveredArg >= 0);
7467   }
7468 
7469   unsigned getUncoveredArg() const {
7470     assert(hasUncoveredArg() && "no uncovered argument");
7471     return FirstUncoveredArg;
7472   }
7473 
7474   void setAllCovered() {
7475     // A string has been found with all arguments covered, so clear out
7476     // the diagnostics.
7477     DiagnosticExprs.clear();
7478     FirstUncoveredArg = AllCovered;
7479   }
7480 
7481   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7482     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7483 
7484     // Don't update if a previous string covers all arguments.
7485     if (FirstUncoveredArg == AllCovered)
7486       return;
7487 
7488     // UncoveredArgHandler tracks the highest uncovered argument index
7489     // and with it all the strings that match this index.
7490     if (NewFirstUncoveredArg == FirstUncoveredArg)
7491       DiagnosticExprs.push_back(StrExpr);
7492     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7493       DiagnosticExprs.clear();
7494       DiagnosticExprs.push_back(StrExpr);
7495       FirstUncoveredArg = NewFirstUncoveredArg;
7496     }
7497   }
7498 
7499   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7500 };
7501 
7502 enum StringLiteralCheckType {
7503   SLCT_NotALiteral,
7504   SLCT_UncheckedLiteral,
7505   SLCT_CheckedLiteral
7506 };
7507 
7508 } // namespace
7509 
7510 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7511                                      BinaryOperatorKind BinOpKind,
7512                                      bool AddendIsRight) {
7513   unsigned BitWidth = Offset.getBitWidth();
7514   unsigned AddendBitWidth = Addend.getBitWidth();
7515   // There might be negative interim results.
7516   if (Addend.isUnsigned()) {
7517     Addend = Addend.zext(++AddendBitWidth);
7518     Addend.setIsSigned(true);
7519   }
7520   // Adjust the bit width of the APSInts.
7521   if (AddendBitWidth > BitWidth) {
7522     Offset = Offset.sext(AddendBitWidth);
7523     BitWidth = AddendBitWidth;
7524   } else if (BitWidth > AddendBitWidth) {
7525     Addend = Addend.sext(BitWidth);
7526   }
7527 
7528   bool Ov = false;
7529   llvm::APSInt ResOffset = Offset;
7530   if (BinOpKind == BO_Add)
7531     ResOffset = Offset.sadd_ov(Addend, Ov);
7532   else {
7533     assert(AddendIsRight && BinOpKind == BO_Sub &&
7534            "operator must be add or sub with addend on the right");
7535     ResOffset = Offset.ssub_ov(Addend, Ov);
7536   }
7537 
7538   // We add an offset to a pointer here so we should support an offset as big as
7539   // possible.
7540   if (Ov) {
7541     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7542            "index (intermediate) result too big");
7543     Offset = Offset.sext(2 * BitWidth);
7544     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7545     return;
7546   }
7547 
7548   Offset = ResOffset;
7549 }
7550 
7551 namespace {
7552 
7553 // This is a wrapper class around StringLiteral to support offsetted string
7554 // literals as format strings. It takes the offset into account when returning
7555 // the string and its length or the source locations to display notes correctly.
7556 class FormatStringLiteral {
7557   const StringLiteral *FExpr;
7558   int64_t Offset;
7559 
7560  public:
7561   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7562       : FExpr(fexpr), Offset(Offset) {}
7563 
7564   StringRef getString() const {
7565     return FExpr->getString().drop_front(Offset);
7566   }
7567 
7568   unsigned getByteLength() const {
7569     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7570   }
7571 
7572   unsigned getLength() const { return FExpr->getLength() - Offset; }
7573   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7574 
7575   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7576 
7577   QualType getType() const { return FExpr->getType(); }
7578 
7579   bool isAscii() const { return FExpr->isAscii(); }
7580   bool isWide() const { return FExpr->isWide(); }
7581   bool isUTF8() const { return FExpr->isUTF8(); }
7582   bool isUTF16() const { return FExpr->isUTF16(); }
7583   bool isUTF32() const { return FExpr->isUTF32(); }
7584   bool isPascal() const { return FExpr->isPascal(); }
7585 
7586   SourceLocation getLocationOfByte(
7587       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7588       const TargetInfo &Target, unsigned *StartToken = nullptr,
7589       unsigned *StartTokenByteOffset = nullptr) const {
7590     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7591                                     StartToken, StartTokenByteOffset);
7592   }
7593 
7594   SourceLocation getBeginLoc() const LLVM_READONLY {
7595     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7596   }
7597 
7598   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7599 };
7600 
7601 }  // namespace
7602 
7603 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7604                               const Expr *OrigFormatExpr,
7605                               ArrayRef<const Expr *> Args,
7606                               bool HasVAListArg, unsigned format_idx,
7607                               unsigned firstDataArg,
7608                               Sema::FormatStringType Type,
7609                               bool inFunctionCall,
7610                               Sema::VariadicCallType CallType,
7611                               llvm::SmallBitVector &CheckedVarArgs,
7612                               UncoveredArgHandler &UncoveredArg,
7613                               bool IgnoreStringsWithoutSpecifiers);
7614 
7615 // Determine if an expression is a string literal or constant string.
7616 // If this function returns false on the arguments to a function expecting a
7617 // format string, we will usually need to emit a warning.
7618 // True string literals are then checked by CheckFormatString.
7619 static StringLiteralCheckType
7620 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7621                       bool HasVAListArg, unsigned format_idx,
7622                       unsigned firstDataArg, Sema::FormatStringType Type,
7623                       Sema::VariadicCallType CallType, bool InFunctionCall,
7624                       llvm::SmallBitVector &CheckedVarArgs,
7625                       UncoveredArgHandler &UncoveredArg,
7626                       llvm::APSInt Offset,
7627                       bool IgnoreStringsWithoutSpecifiers = false) {
7628   if (S.isConstantEvaluated())
7629     return SLCT_NotALiteral;
7630  tryAgain:
7631   assert(Offset.isSigned() && "invalid offset");
7632 
7633   if (E->isTypeDependent() || E->isValueDependent())
7634     return SLCT_NotALiteral;
7635 
7636   E = E->IgnoreParenCasts();
7637 
7638   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7639     // Technically -Wformat-nonliteral does not warn about this case.
7640     // The behavior of printf and friends in this case is implementation
7641     // dependent.  Ideally if the format string cannot be null then
7642     // it should have a 'nonnull' attribute in the function prototype.
7643     return SLCT_UncheckedLiteral;
7644 
7645   switch (E->getStmtClass()) {
7646   case Stmt::BinaryConditionalOperatorClass:
7647   case Stmt::ConditionalOperatorClass: {
7648     // The expression is a literal if both sub-expressions were, and it was
7649     // completely checked only if both sub-expressions were checked.
7650     const AbstractConditionalOperator *C =
7651         cast<AbstractConditionalOperator>(E);
7652 
7653     // Determine whether it is necessary to check both sub-expressions, for
7654     // example, because the condition expression is a constant that can be
7655     // evaluated at compile time.
7656     bool CheckLeft = true, CheckRight = true;
7657 
7658     bool Cond;
7659     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7660                                                  S.isConstantEvaluated())) {
7661       if (Cond)
7662         CheckRight = false;
7663       else
7664         CheckLeft = false;
7665     }
7666 
7667     // We need to maintain the offsets for the right and the left hand side
7668     // separately to check if every possible indexed expression is a valid
7669     // string literal. They might have different offsets for different string
7670     // literals in the end.
7671     StringLiteralCheckType Left;
7672     if (!CheckLeft)
7673       Left = SLCT_UncheckedLiteral;
7674     else {
7675       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7676                                    HasVAListArg, format_idx, firstDataArg,
7677                                    Type, CallType, InFunctionCall,
7678                                    CheckedVarArgs, UncoveredArg, Offset,
7679                                    IgnoreStringsWithoutSpecifiers);
7680       if (Left == SLCT_NotALiteral || !CheckRight) {
7681         return Left;
7682       }
7683     }
7684 
7685     StringLiteralCheckType Right = checkFormatStringExpr(
7686         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7687         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7688         IgnoreStringsWithoutSpecifiers);
7689 
7690     return (CheckLeft && Left < Right) ? Left : Right;
7691   }
7692 
7693   case Stmt::ImplicitCastExprClass:
7694     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7695     goto tryAgain;
7696 
7697   case Stmt::OpaqueValueExprClass:
7698     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7699       E = src;
7700       goto tryAgain;
7701     }
7702     return SLCT_NotALiteral;
7703 
7704   case Stmt::PredefinedExprClass:
7705     // While __func__, etc., are technically not string literals, they
7706     // cannot contain format specifiers and thus are not a security
7707     // liability.
7708     return SLCT_UncheckedLiteral;
7709 
7710   case Stmt::DeclRefExprClass: {
7711     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7712 
7713     // As an exception, do not flag errors for variables binding to
7714     // const string literals.
7715     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7716       bool isConstant = false;
7717       QualType T = DR->getType();
7718 
7719       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7720         isConstant = AT->getElementType().isConstant(S.Context);
7721       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7722         isConstant = T.isConstant(S.Context) &&
7723                      PT->getPointeeType().isConstant(S.Context);
7724       } else if (T->isObjCObjectPointerType()) {
7725         // In ObjC, there is usually no "const ObjectPointer" type,
7726         // so don't check if the pointee type is constant.
7727         isConstant = T.isConstant(S.Context);
7728       }
7729 
7730       if (isConstant) {
7731         if (const Expr *Init = VD->getAnyInitializer()) {
7732           // Look through initializers like const char c[] = { "foo" }
7733           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7734             if (InitList->isStringLiteralInit())
7735               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7736           }
7737           return checkFormatStringExpr(S, Init, Args,
7738                                        HasVAListArg, format_idx,
7739                                        firstDataArg, Type, CallType,
7740                                        /*InFunctionCall*/ false, CheckedVarArgs,
7741                                        UncoveredArg, Offset);
7742         }
7743       }
7744 
7745       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7746       // special check to see if the format string is a function parameter
7747       // of the function calling the printf function.  If the function
7748       // has an attribute indicating it is a printf-like function, then we
7749       // should suppress warnings concerning non-literals being used in a call
7750       // to a vprintf function.  For example:
7751       //
7752       // void
7753       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7754       //      va_list ap;
7755       //      va_start(ap, fmt);
7756       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7757       //      ...
7758       // }
7759       if (HasVAListArg) {
7760         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7761           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7762             int PVIndex = PV->getFunctionScopeIndex() + 1;
7763             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7764               // adjust for implicit parameter
7765               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7766                 if (MD->isInstance())
7767                   ++PVIndex;
7768               // We also check if the formats are compatible.
7769               // We can't pass a 'scanf' string to a 'printf' function.
7770               if (PVIndex == PVFormat->getFormatIdx() &&
7771                   Type == S.GetFormatStringType(PVFormat))
7772                 return SLCT_UncheckedLiteral;
7773             }
7774           }
7775         }
7776       }
7777     }
7778 
7779     return SLCT_NotALiteral;
7780   }
7781 
7782   case Stmt::CallExprClass:
7783   case Stmt::CXXMemberCallExprClass: {
7784     const CallExpr *CE = cast<CallExpr>(E);
7785     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7786       bool IsFirst = true;
7787       StringLiteralCheckType CommonResult;
7788       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7789         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7790         StringLiteralCheckType Result = checkFormatStringExpr(
7791             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7792             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7793             IgnoreStringsWithoutSpecifiers);
7794         if (IsFirst) {
7795           CommonResult = Result;
7796           IsFirst = false;
7797         }
7798       }
7799       if (!IsFirst)
7800         return CommonResult;
7801 
7802       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7803         unsigned BuiltinID = FD->getBuiltinID();
7804         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7805             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7806           const Expr *Arg = CE->getArg(0);
7807           return checkFormatStringExpr(S, Arg, Args,
7808                                        HasVAListArg, format_idx,
7809                                        firstDataArg, Type, CallType,
7810                                        InFunctionCall, CheckedVarArgs,
7811                                        UncoveredArg, Offset,
7812                                        IgnoreStringsWithoutSpecifiers);
7813         }
7814       }
7815     }
7816 
7817     return SLCT_NotALiteral;
7818   }
7819   case Stmt::ObjCMessageExprClass: {
7820     const auto *ME = cast<ObjCMessageExpr>(E);
7821     if (const auto *MD = ME->getMethodDecl()) {
7822       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7823         // As a special case heuristic, if we're using the method -[NSBundle
7824         // localizedStringForKey:value:table:], ignore any key strings that lack
7825         // format specifiers. The idea is that if the key doesn't have any
7826         // format specifiers then its probably just a key to map to the
7827         // localized strings. If it does have format specifiers though, then its
7828         // likely that the text of the key is the format string in the
7829         // programmer's language, and should be checked.
7830         const ObjCInterfaceDecl *IFace;
7831         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7832             IFace->getIdentifier()->isStr("NSBundle") &&
7833             MD->getSelector().isKeywordSelector(
7834                 {"localizedStringForKey", "value", "table"})) {
7835           IgnoreStringsWithoutSpecifiers = true;
7836         }
7837 
7838         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7839         return checkFormatStringExpr(
7840             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7841             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7842             IgnoreStringsWithoutSpecifiers);
7843       }
7844     }
7845 
7846     return SLCT_NotALiteral;
7847   }
7848   case Stmt::ObjCStringLiteralClass:
7849   case Stmt::StringLiteralClass: {
7850     const StringLiteral *StrE = nullptr;
7851 
7852     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7853       StrE = ObjCFExpr->getString();
7854     else
7855       StrE = cast<StringLiteral>(E);
7856 
7857     if (StrE) {
7858       if (Offset.isNegative() || Offset > StrE->getLength()) {
7859         // TODO: It would be better to have an explicit warning for out of
7860         // bounds literals.
7861         return SLCT_NotALiteral;
7862       }
7863       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7864       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7865                         firstDataArg, Type, InFunctionCall, CallType,
7866                         CheckedVarArgs, UncoveredArg,
7867                         IgnoreStringsWithoutSpecifiers);
7868       return SLCT_CheckedLiteral;
7869     }
7870 
7871     return SLCT_NotALiteral;
7872   }
7873   case Stmt::BinaryOperatorClass: {
7874     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7875 
7876     // A string literal + an int offset is still a string literal.
7877     if (BinOp->isAdditiveOp()) {
7878       Expr::EvalResult LResult, RResult;
7879 
7880       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7881           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7882       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7883           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7884 
7885       if (LIsInt != RIsInt) {
7886         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7887 
7888         if (LIsInt) {
7889           if (BinOpKind == BO_Add) {
7890             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7891             E = BinOp->getRHS();
7892             goto tryAgain;
7893           }
7894         } else {
7895           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7896           E = BinOp->getLHS();
7897           goto tryAgain;
7898         }
7899       }
7900     }
7901 
7902     return SLCT_NotALiteral;
7903   }
7904   case Stmt::UnaryOperatorClass: {
7905     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7906     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7907     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7908       Expr::EvalResult IndexResult;
7909       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7910                                        Expr::SE_NoSideEffects,
7911                                        S.isConstantEvaluated())) {
7912         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7913                    /*RHS is int*/ true);
7914         E = ASE->getBase();
7915         goto tryAgain;
7916       }
7917     }
7918 
7919     return SLCT_NotALiteral;
7920   }
7921 
7922   default:
7923     return SLCT_NotALiteral;
7924   }
7925 }
7926 
7927 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7928   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7929       .Case("scanf", FST_Scanf)
7930       .Cases("printf", "printf0", FST_Printf)
7931       .Cases("NSString", "CFString", FST_NSString)
7932       .Case("strftime", FST_Strftime)
7933       .Case("strfmon", FST_Strfmon)
7934       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7935       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7936       .Case("os_trace", FST_OSLog)
7937       .Case("os_log", FST_OSLog)
7938       .Default(FST_Unknown);
7939 }
7940 
7941 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7942 /// functions) for correct use of format strings.
7943 /// Returns true if a format string has been fully checked.
7944 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7945                                 ArrayRef<const Expr *> Args,
7946                                 bool IsCXXMember,
7947                                 VariadicCallType CallType,
7948                                 SourceLocation Loc, SourceRange Range,
7949                                 llvm::SmallBitVector &CheckedVarArgs) {
7950   FormatStringInfo FSI;
7951   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7952     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7953                                 FSI.FirstDataArg, GetFormatStringType(Format),
7954                                 CallType, Loc, Range, CheckedVarArgs);
7955   return false;
7956 }
7957 
7958 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7959                                 bool HasVAListArg, unsigned format_idx,
7960                                 unsigned firstDataArg, FormatStringType Type,
7961                                 VariadicCallType CallType,
7962                                 SourceLocation Loc, SourceRange Range,
7963                                 llvm::SmallBitVector &CheckedVarArgs) {
7964   // CHECK: printf/scanf-like function is called with no format string.
7965   if (format_idx >= Args.size()) {
7966     Diag(Loc, diag::warn_missing_format_string) << Range;
7967     return false;
7968   }
7969 
7970   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7971 
7972   // CHECK: format string is not a string literal.
7973   //
7974   // Dynamically generated format strings are difficult to
7975   // automatically vet at compile time.  Requiring that format strings
7976   // are string literals: (1) permits the checking of format strings by
7977   // the compiler and thereby (2) can practically remove the source of
7978   // many format string exploits.
7979 
7980   // Format string can be either ObjC string (e.g. @"%d") or
7981   // C string (e.g. "%d")
7982   // ObjC string uses the same format specifiers as C string, so we can use
7983   // the same format string checking logic for both ObjC and C strings.
7984   UncoveredArgHandler UncoveredArg;
7985   StringLiteralCheckType CT =
7986       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7987                             format_idx, firstDataArg, Type, CallType,
7988                             /*IsFunctionCall*/ true, CheckedVarArgs,
7989                             UncoveredArg,
7990                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7991 
7992   // Generate a diagnostic where an uncovered argument is detected.
7993   if (UncoveredArg.hasUncoveredArg()) {
7994     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7995     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7996     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7997   }
7998 
7999   if (CT != SLCT_NotALiteral)
8000     // Literal format string found, check done!
8001     return CT == SLCT_CheckedLiteral;
8002 
8003   // Strftime is particular as it always uses a single 'time' argument,
8004   // so it is safe to pass a non-literal string.
8005   if (Type == FST_Strftime)
8006     return false;
8007 
8008   // Do not emit diag when the string param is a macro expansion and the
8009   // format is either NSString or CFString. This is a hack to prevent
8010   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8011   // which are usually used in place of NS and CF string literals.
8012   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8013   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8014     return false;
8015 
8016   // If there are no arguments specified, warn with -Wformat-security, otherwise
8017   // warn only with -Wformat-nonliteral.
8018   if (Args.size() == firstDataArg) {
8019     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8020       << OrigFormatExpr->getSourceRange();
8021     switch (Type) {
8022     default:
8023       break;
8024     case FST_Kprintf:
8025     case FST_FreeBSDKPrintf:
8026     case FST_Printf:
8027       Diag(FormatLoc, diag::note_format_security_fixit)
8028         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8029       break;
8030     case FST_NSString:
8031       Diag(FormatLoc, diag::note_format_security_fixit)
8032         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8033       break;
8034     }
8035   } else {
8036     Diag(FormatLoc, diag::warn_format_nonliteral)
8037       << OrigFormatExpr->getSourceRange();
8038   }
8039   return false;
8040 }
8041 
8042 namespace {
8043 
8044 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8045 protected:
8046   Sema &S;
8047   const FormatStringLiteral *FExpr;
8048   const Expr *OrigFormatExpr;
8049   const Sema::FormatStringType FSType;
8050   const unsigned FirstDataArg;
8051   const unsigned NumDataArgs;
8052   const char *Beg; // Start of format string.
8053   const bool HasVAListArg;
8054   ArrayRef<const Expr *> Args;
8055   unsigned FormatIdx;
8056   llvm::SmallBitVector CoveredArgs;
8057   bool usesPositionalArgs = false;
8058   bool atFirstArg = true;
8059   bool inFunctionCall;
8060   Sema::VariadicCallType CallType;
8061   llvm::SmallBitVector &CheckedVarArgs;
8062   UncoveredArgHandler &UncoveredArg;
8063 
8064 public:
8065   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8066                      const Expr *origFormatExpr,
8067                      const Sema::FormatStringType type, unsigned firstDataArg,
8068                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8069                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8070                      bool inFunctionCall, Sema::VariadicCallType callType,
8071                      llvm::SmallBitVector &CheckedVarArgs,
8072                      UncoveredArgHandler &UncoveredArg)
8073       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8074         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8075         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8076         inFunctionCall(inFunctionCall), CallType(callType),
8077         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8078     CoveredArgs.resize(numDataArgs);
8079     CoveredArgs.reset();
8080   }
8081 
8082   void DoneProcessing();
8083 
8084   void HandleIncompleteSpecifier(const char *startSpecifier,
8085                                  unsigned specifierLen) override;
8086 
8087   void HandleInvalidLengthModifier(
8088                            const analyze_format_string::FormatSpecifier &FS,
8089                            const analyze_format_string::ConversionSpecifier &CS,
8090                            const char *startSpecifier, unsigned specifierLen,
8091                            unsigned DiagID);
8092 
8093   void HandleNonStandardLengthModifier(
8094                     const analyze_format_string::FormatSpecifier &FS,
8095                     const char *startSpecifier, unsigned specifierLen);
8096 
8097   void HandleNonStandardConversionSpecifier(
8098                     const analyze_format_string::ConversionSpecifier &CS,
8099                     const char *startSpecifier, unsigned specifierLen);
8100 
8101   void HandlePosition(const char *startPos, unsigned posLen) override;
8102 
8103   void HandleInvalidPosition(const char *startSpecifier,
8104                              unsigned specifierLen,
8105                              analyze_format_string::PositionContext p) override;
8106 
8107   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8108 
8109   void HandleNullChar(const char *nullCharacter) override;
8110 
8111   template <typename Range>
8112   static void
8113   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8114                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8115                        bool IsStringLocation, Range StringRange,
8116                        ArrayRef<FixItHint> Fixit = None);
8117 
8118 protected:
8119   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8120                                         const char *startSpec,
8121                                         unsigned specifierLen,
8122                                         const char *csStart, unsigned csLen);
8123 
8124   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8125                                          const char *startSpec,
8126                                          unsigned specifierLen);
8127 
8128   SourceRange getFormatStringRange();
8129   CharSourceRange getSpecifierRange(const char *startSpecifier,
8130                                     unsigned specifierLen);
8131   SourceLocation getLocationOfByte(const char *x);
8132 
8133   const Expr *getDataArg(unsigned i) const;
8134 
8135   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8136                     const analyze_format_string::ConversionSpecifier &CS,
8137                     const char *startSpecifier, unsigned specifierLen,
8138                     unsigned argIndex);
8139 
8140   template <typename Range>
8141   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8142                             bool IsStringLocation, Range StringRange,
8143                             ArrayRef<FixItHint> Fixit = None);
8144 };
8145 
8146 } // namespace
8147 
8148 SourceRange CheckFormatHandler::getFormatStringRange() {
8149   return OrigFormatExpr->getSourceRange();
8150 }
8151 
8152 CharSourceRange CheckFormatHandler::
8153 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8154   SourceLocation Start = getLocationOfByte(startSpecifier);
8155   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8156 
8157   // Advance the end SourceLocation by one due to half-open ranges.
8158   End = End.getLocWithOffset(1);
8159 
8160   return CharSourceRange::getCharRange(Start, End);
8161 }
8162 
8163 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8164   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8165                                   S.getLangOpts(), S.Context.getTargetInfo());
8166 }
8167 
8168 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8169                                                    unsigned specifierLen){
8170   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8171                        getLocationOfByte(startSpecifier),
8172                        /*IsStringLocation*/true,
8173                        getSpecifierRange(startSpecifier, specifierLen));
8174 }
8175 
8176 void CheckFormatHandler::HandleInvalidLengthModifier(
8177     const analyze_format_string::FormatSpecifier &FS,
8178     const analyze_format_string::ConversionSpecifier &CS,
8179     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8180   using namespace analyze_format_string;
8181 
8182   const LengthModifier &LM = FS.getLengthModifier();
8183   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8184 
8185   // See if we know how to fix this length modifier.
8186   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8187   if (FixedLM) {
8188     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8189                          getLocationOfByte(LM.getStart()),
8190                          /*IsStringLocation*/true,
8191                          getSpecifierRange(startSpecifier, specifierLen));
8192 
8193     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8194       << FixedLM->toString()
8195       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8196 
8197   } else {
8198     FixItHint Hint;
8199     if (DiagID == diag::warn_format_nonsensical_length)
8200       Hint = FixItHint::CreateRemoval(LMRange);
8201 
8202     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8203                          getLocationOfByte(LM.getStart()),
8204                          /*IsStringLocation*/true,
8205                          getSpecifierRange(startSpecifier, specifierLen),
8206                          Hint);
8207   }
8208 }
8209 
8210 void CheckFormatHandler::HandleNonStandardLengthModifier(
8211     const analyze_format_string::FormatSpecifier &FS,
8212     const char *startSpecifier, unsigned specifierLen) {
8213   using namespace analyze_format_string;
8214 
8215   const LengthModifier &LM = FS.getLengthModifier();
8216   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8217 
8218   // See if we know how to fix this length modifier.
8219   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8220   if (FixedLM) {
8221     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8222                            << LM.toString() << 0,
8223                          getLocationOfByte(LM.getStart()),
8224                          /*IsStringLocation*/true,
8225                          getSpecifierRange(startSpecifier, specifierLen));
8226 
8227     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8228       << FixedLM->toString()
8229       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8230 
8231   } else {
8232     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8233                            << LM.toString() << 0,
8234                          getLocationOfByte(LM.getStart()),
8235                          /*IsStringLocation*/true,
8236                          getSpecifierRange(startSpecifier, specifierLen));
8237   }
8238 }
8239 
8240 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8241     const analyze_format_string::ConversionSpecifier &CS,
8242     const char *startSpecifier, unsigned specifierLen) {
8243   using namespace analyze_format_string;
8244 
8245   // See if we know how to fix this conversion specifier.
8246   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8247   if (FixedCS) {
8248     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8249                           << CS.toString() << /*conversion specifier*/1,
8250                          getLocationOfByte(CS.getStart()),
8251                          /*IsStringLocation*/true,
8252                          getSpecifierRange(startSpecifier, specifierLen));
8253 
8254     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8255     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8256       << FixedCS->toString()
8257       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8258   } else {
8259     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8260                           << CS.toString() << /*conversion specifier*/1,
8261                          getLocationOfByte(CS.getStart()),
8262                          /*IsStringLocation*/true,
8263                          getSpecifierRange(startSpecifier, specifierLen));
8264   }
8265 }
8266 
8267 void CheckFormatHandler::HandlePosition(const char *startPos,
8268                                         unsigned posLen) {
8269   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8270                                getLocationOfByte(startPos),
8271                                /*IsStringLocation*/true,
8272                                getSpecifierRange(startPos, posLen));
8273 }
8274 
8275 void
8276 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8277                                      analyze_format_string::PositionContext p) {
8278   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8279                          << (unsigned) p,
8280                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8281                        getSpecifierRange(startPos, posLen));
8282 }
8283 
8284 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8285                                             unsigned posLen) {
8286   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8287                                getLocationOfByte(startPos),
8288                                /*IsStringLocation*/true,
8289                                getSpecifierRange(startPos, posLen));
8290 }
8291 
8292 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8293   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8294     // The presence of a null character is likely an error.
8295     EmitFormatDiagnostic(
8296       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8297       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8298       getFormatStringRange());
8299   }
8300 }
8301 
8302 // Note that this may return NULL if there was an error parsing or building
8303 // one of the argument expressions.
8304 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8305   return Args[FirstDataArg + i];
8306 }
8307 
8308 void CheckFormatHandler::DoneProcessing() {
8309   // Does the number of data arguments exceed the number of
8310   // format conversions in the format string?
8311   if (!HasVAListArg) {
8312       // Find any arguments that weren't covered.
8313     CoveredArgs.flip();
8314     signed notCoveredArg = CoveredArgs.find_first();
8315     if (notCoveredArg >= 0) {
8316       assert((unsigned)notCoveredArg < NumDataArgs);
8317       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8318     } else {
8319       UncoveredArg.setAllCovered();
8320     }
8321   }
8322 }
8323 
8324 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8325                                    const Expr *ArgExpr) {
8326   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8327          "Invalid state");
8328 
8329   if (!ArgExpr)
8330     return;
8331 
8332   SourceLocation Loc = ArgExpr->getBeginLoc();
8333 
8334   if (S.getSourceManager().isInSystemMacro(Loc))
8335     return;
8336 
8337   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8338   for (auto E : DiagnosticExprs)
8339     PDiag << E->getSourceRange();
8340 
8341   CheckFormatHandler::EmitFormatDiagnostic(
8342                                   S, IsFunctionCall, DiagnosticExprs[0],
8343                                   PDiag, Loc, /*IsStringLocation*/false,
8344                                   DiagnosticExprs[0]->getSourceRange());
8345 }
8346 
8347 bool
8348 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8349                                                      SourceLocation Loc,
8350                                                      const char *startSpec,
8351                                                      unsigned specifierLen,
8352                                                      const char *csStart,
8353                                                      unsigned csLen) {
8354   bool keepGoing = true;
8355   if (argIndex < NumDataArgs) {
8356     // Consider the argument coverered, even though the specifier doesn't
8357     // make sense.
8358     CoveredArgs.set(argIndex);
8359   }
8360   else {
8361     // If argIndex exceeds the number of data arguments we
8362     // don't issue a warning because that is just a cascade of warnings (and
8363     // they may have intended '%%' anyway). We don't want to continue processing
8364     // the format string after this point, however, as we will like just get
8365     // gibberish when trying to match arguments.
8366     keepGoing = false;
8367   }
8368 
8369   StringRef Specifier(csStart, csLen);
8370 
8371   // If the specifier in non-printable, it could be the first byte of a UTF-8
8372   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8373   // hex value.
8374   std::string CodePointStr;
8375   if (!llvm::sys::locale::isPrint(*csStart)) {
8376     llvm::UTF32 CodePoint;
8377     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8378     const llvm::UTF8 *E =
8379         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8380     llvm::ConversionResult Result =
8381         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8382 
8383     if (Result != llvm::conversionOK) {
8384       unsigned char FirstChar = *csStart;
8385       CodePoint = (llvm::UTF32)FirstChar;
8386     }
8387 
8388     llvm::raw_string_ostream OS(CodePointStr);
8389     if (CodePoint < 256)
8390       OS << "\\x" << llvm::format("%02x", CodePoint);
8391     else if (CodePoint <= 0xFFFF)
8392       OS << "\\u" << llvm::format("%04x", CodePoint);
8393     else
8394       OS << "\\U" << llvm::format("%08x", CodePoint);
8395     OS.flush();
8396     Specifier = CodePointStr;
8397   }
8398 
8399   EmitFormatDiagnostic(
8400       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8401       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8402 
8403   return keepGoing;
8404 }
8405 
8406 void
8407 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8408                                                       const char *startSpec,
8409                                                       unsigned specifierLen) {
8410   EmitFormatDiagnostic(
8411     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8412     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8413 }
8414 
8415 bool
8416 CheckFormatHandler::CheckNumArgs(
8417   const analyze_format_string::FormatSpecifier &FS,
8418   const analyze_format_string::ConversionSpecifier &CS,
8419   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8420 
8421   if (argIndex >= NumDataArgs) {
8422     PartialDiagnostic PDiag = FS.usesPositionalArg()
8423       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8424            << (argIndex+1) << NumDataArgs)
8425       : S.PDiag(diag::warn_printf_insufficient_data_args);
8426     EmitFormatDiagnostic(
8427       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8428       getSpecifierRange(startSpecifier, specifierLen));
8429 
8430     // Since more arguments than conversion tokens are given, by extension
8431     // all arguments are covered, so mark this as so.
8432     UncoveredArg.setAllCovered();
8433     return false;
8434   }
8435   return true;
8436 }
8437 
8438 template<typename Range>
8439 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8440                                               SourceLocation Loc,
8441                                               bool IsStringLocation,
8442                                               Range StringRange,
8443                                               ArrayRef<FixItHint> FixIt) {
8444   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8445                        Loc, IsStringLocation, StringRange, FixIt);
8446 }
8447 
8448 /// If the format string is not within the function call, emit a note
8449 /// so that the function call and string are in diagnostic messages.
8450 ///
8451 /// \param InFunctionCall if true, the format string is within the function
8452 /// call and only one diagnostic message will be produced.  Otherwise, an
8453 /// extra note will be emitted pointing to location of the format string.
8454 ///
8455 /// \param ArgumentExpr the expression that is passed as the format string
8456 /// argument in the function call.  Used for getting locations when two
8457 /// diagnostics are emitted.
8458 ///
8459 /// \param PDiag the callee should already have provided any strings for the
8460 /// diagnostic message.  This function only adds locations and fixits
8461 /// to diagnostics.
8462 ///
8463 /// \param Loc primary location for diagnostic.  If two diagnostics are
8464 /// required, one will be at Loc and a new SourceLocation will be created for
8465 /// the other one.
8466 ///
8467 /// \param IsStringLocation if true, Loc points to the format string should be
8468 /// used for the note.  Otherwise, Loc points to the argument list and will
8469 /// be used with PDiag.
8470 ///
8471 /// \param StringRange some or all of the string to highlight.  This is
8472 /// templated so it can accept either a CharSourceRange or a SourceRange.
8473 ///
8474 /// \param FixIt optional fix it hint for the format string.
8475 template <typename Range>
8476 void CheckFormatHandler::EmitFormatDiagnostic(
8477     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8478     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8479     Range StringRange, ArrayRef<FixItHint> FixIt) {
8480   if (InFunctionCall) {
8481     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8482     D << StringRange;
8483     D << FixIt;
8484   } else {
8485     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8486       << ArgumentExpr->getSourceRange();
8487 
8488     const Sema::SemaDiagnosticBuilder &Note =
8489       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8490              diag::note_format_string_defined);
8491 
8492     Note << StringRange;
8493     Note << FixIt;
8494   }
8495 }
8496 
8497 //===--- CHECK: Printf format string checking ------------------------------===//
8498 
8499 namespace {
8500 
8501 class CheckPrintfHandler : public CheckFormatHandler {
8502 public:
8503   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8504                      const Expr *origFormatExpr,
8505                      const Sema::FormatStringType type, unsigned firstDataArg,
8506                      unsigned numDataArgs, bool isObjC, const char *beg,
8507                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8508                      unsigned formatIdx, bool inFunctionCall,
8509                      Sema::VariadicCallType CallType,
8510                      llvm::SmallBitVector &CheckedVarArgs,
8511                      UncoveredArgHandler &UncoveredArg)
8512       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8513                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8514                            inFunctionCall, CallType, CheckedVarArgs,
8515                            UncoveredArg) {}
8516 
8517   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8518 
8519   /// Returns true if '%@' specifiers are allowed in the format string.
8520   bool allowsObjCArg() const {
8521     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8522            FSType == Sema::FST_OSTrace;
8523   }
8524 
8525   bool HandleInvalidPrintfConversionSpecifier(
8526                                       const analyze_printf::PrintfSpecifier &FS,
8527                                       const char *startSpecifier,
8528                                       unsigned specifierLen) override;
8529 
8530   void handleInvalidMaskType(StringRef MaskType) override;
8531 
8532   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8533                              const char *startSpecifier,
8534                              unsigned specifierLen) override;
8535   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8536                        const char *StartSpecifier,
8537                        unsigned SpecifierLen,
8538                        const Expr *E);
8539 
8540   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8541                     const char *startSpecifier, unsigned specifierLen);
8542   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8543                            const analyze_printf::OptionalAmount &Amt,
8544                            unsigned type,
8545                            const char *startSpecifier, unsigned specifierLen);
8546   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8547                   const analyze_printf::OptionalFlag &flag,
8548                   const char *startSpecifier, unsigned specifierLen);
8549   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8550                          const analyze_printf::OptionalFlag &ignoredFlag,
8551                          const analyze_printf::OptionalFlag &flag,
8552                          const char *startSpecifier, unsigned specifierLen);
8553   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8554                            const Expr *E);
8555 
8556   void HandleEmptyObjCModifierFlag(const char *startFlag,
8557                                    unsigned flagLen) override;
8558 
8559   void HandleInvalidObjCModifierFlag(const char *startFlag,
8560                                             unsigned flagLen) override;
8561 
8562   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8563                                            const char *flagsEnd,
8564                                            const char *conversionPosition)
8565                                              override;
8566 };
8567 
8568 } // namespace
8569 
8570 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8571                                       const analyze_printf::PrintfSpecifier &FS,
8572                                       const char *startSpecifier,
8573                                       unsigned specifierLen) {
8574   const analyze_printf::PrintfConversionSpecifier &CS =
8575     FS.getConversionSpecifier();
8576 
8577   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8578                                           getLocationOfByte(CS.getStart()),
8579                                           startSpecifier, specifierLen,
8580                                           CS.getStart(), CS.getLength());
8581 }
8582 
8583 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8584   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8585 }
8586 
8587 bool CheckPrintfHandler::HandleAmount(
8588                                const analyze_format_string::OptionalAmount &Amt,
8589                                unsigned k, const char *startSpecifier,
8590                                unsigned specifierLen) {
8591   if (Amt.hasDataArgument()) {
8592     if (!HasVAListArg) {
8593       unsigned argIndex = Amt.getArgIndex();
8594       if (argIndex >= NumDataArgs) {
8595         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8596                                << k,
8597                              getLocationOfByte(Amt.getStart()),
8598                              /*IsStringLocation*/true,
8599                              getSpecifierRange(startSpecifier, specifierLen));
8600         // Don't do any more checking.  We will just emit
8601         // spurious errors.
8602         return false;
8603       }
8604 
8605       // Type check the data argument.  It should be an 'int'.
8606       // Although not in conformance with C99, we also allow the argument to be
8607       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8608       // doesn't emit a warning for that case.
8609       CoveredArgs.set(argIndex);
8610       const Expr *Arg = getDataArg(argIndex);
8611       if (!Arg)
8612         return false;
8613 
8614       QualType T = Arg->getType();
8615 
8616       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8617       assert(AT.isValid());
8618 
8619       if (!AT.matchesType(S.Context, T)) {
8620         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8621                                << k << AT.getRepresentativeTypeName(S.Context)
8622                                << T << Arg->getSourceRange(),
8623                              getLocationOfByte(Amt.getStart()),
8624                              /*IsStringLocation*/true,
8625                              getSpecifierRange(startSpecifier, specifierLen));
8626         // Don't do any more checking.  We will just emit
8627         // spurious errors.
8628         return false;
8629       }
8630     }
8631   }
8632   return true;
8633 }
8634 
8635 void CheckPrintfHandler::HandleInvalidAmount(
8636                                       const analyze_printf::PrintfSpecifier &FS,
8637                                       const analyze_printf::OptionalAmount &Amt,
8638                                       unsigned type,
8639                                       const char *startSpecifier,
8640                                       unsigned specifierLen) {
8641   const analyze_printf::PrintfConversionSpecifier &CS =
8642     FS.getConversionSpecifier();
8643 
8644   FixItHint fixit =
8645     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8646       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8647                                  Amt.getConstantLength()))
8648       : FixItHint();
8649 
8650   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8651                          << type << CS.toString(),
8652                        getLocationOfByte(Amt.getStart()),
8653                        /*IsStringLocation*/true,
8654                        getSpecifierRange(startSpecifier, specifierLen),
8655                        fixit);
8656 }
8657 
8658 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8659                                     const analyze_printf::OptionalFlag &flag,
8660                                     const char *startSpecifier,
8661                                     unsigned specifierLen) {
8662   // Warn about pointless flag with a fixit removal.
8663   const analyze_printf::PrintfConversionSpecifier &CS =
8664     FS.getConversionSpecifier();
8665   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8666                          << flag.toString() << CS.toString(),
8667                        getLocationOfByte(flag.getPosition()),
8668                        /*IsStringLocation*/true,
8669                        getSpecifierRange(startSpecifier, specifierLen),
8670                        FixItHint::CreateRemoval(
8671                          getSpecifierRange(flag.getPosition(), 1)));
8672 }
8673 
8674 void CheckPrintfHandler::HandleIgnoredFlag(
8675                                 const analyze_printf::PrintfSpecifier &FS,
8676                                 const analyze_printf::OptionalFlag &ignoredFlag,
8677                                 const analyze_printf::OptionalFlag &flag,
8678                                 const char *startSpecifier,
8679                                 unsigned specifierLen) {
8680   // Warn about ignored flag with a fixit removal.
8681   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8682                          << ignoredFlag.toString() << flag.toString(),
8683                        getLocationOfByte(ignoredFlag.getPosition()),
8684                        /*IsStringLocation*/true,
8685                        getSpecifierRange(startSpecifier, specifierLen),
8686                        FixItHint::CreateRemoval(
8687                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8688 }
8689 
8690 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8691                                                      unsigned flagLen) {
8692   // Warn about an empty flag.
8693   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8694                        getLocationOfByte(startFlag),
8695                        /*IsStringLocation*/true,
8696                        getSpecifierRange(startFlag, flagLen));
8697 }
8698 
8699 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8700                                                        unsigned flagLen) {
8701   // Warn about an invalid flag.
8702   auto Range = getSpecifierRange(startFlag, flagLen);
8703   StringRef flag(startFlag, flagLen);
8704   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8705                       getLocationOfByte(startFlag),
8706                       /*IsStringLocation*/true,
8707                       Range, FixItHint::CreateRemoval(Range));
8708 }
8709 
8710 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8711     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8712     // Warn about using '[...]' without a '@' conversion.
8713     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8714     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8715     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8716                          getLocationOfByte(conversionPosition),
8717                          /*IsStringLocation*/true,
8718                          Range, FixItHint::CreateRemoval(Range));
8719 }
8720 
8721 // Determines if the specified is a C++ class or struct containing
8722 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8723 // "c_str()").
8724 template<typename MemberKind>
8725 static llvm::SmallPtrSet<MemberKind*, 1>
8726 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8727   const RecordType *RT = Ty->getAs<RecordType>();
8728   llvm::SmallPtrSet<MemberKind*, 1> Results;
8729 
8730   if (!RT)
8731     return Results;
8732   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8733   if (!RD || !RD->getDefinition())
8734     return Results;
8735 
8736   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8737                  Sema::LookupMemberName);
8738   R.suppressDiagnostics();
8739 
8740   // We just need to include all members of the right kind turned up by the
8741   // filter, at this point.
8742   if (S.LookupQualifiedName(R, RT->getDecl()))
8743     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8744       NamedDecl *decl = (*I)->getUnderlyingDecl();
8745       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8746         Results.insert(FK);
8747     }
8748   return Results;
8749 }
8750 
8751 /// Check if we could call '.c_str()' on an object.
8752 ///
8753 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8754 /// allow the call, or if it would be ambiguous).
8755 bool Sema::hasCStrMethod(const Expr *E) {
8756   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8757 
8758   MethodSet Results =
8759       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8760   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8761        MI != ME; ++MI)
8762     if ((*MI)->getMinRequiredArguments() == 0)
8763       return true;
8764   return false;
8765 }
8766 
8767 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8768 // better diagnostic if so. AT is assumed to be valid.
8769 // Returns true when a c_str() conversion method is found.
8770 bool CheckPrintfHandler::checkForCStrMembers(
8771     const analyze_printf::ArgType &AT, const Expr *E) {
8772   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8773 
8774   MethodSet Results =
8775       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8776 
8777   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8778        MI != ME; ++MI) {
8779     const CXXMethodDecl *Method = *MI;
8780     if (Method->getMinRequiredArguments() == 0 &&
8781         AT.matchesType(S.Context, Method->getReturnType())) {
8782       // FIXME: Suggest parens if the expression needs them.
8783       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8784       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8785           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8786       return true;
8787     }
8788   }
8789 
8790   return false;
8791 }
8792 
8793 bool
8794 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8795                                             &FS,
8796                                           const char *startSpecifier,
8797                                           unsigned specifierLen) {
8798   using namespace analyze_format_string;
8799   using namespace analyze_printf;
8800 
8801   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8802 
8803   if (FS.consumesDataArgument()) {
8804     if (atFirstArg) {
8805         atFirstArg = false;
8806         usesPositionalArgs = FS.usesPositionalArg();
8807     }
8808     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8809       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8810                                         startSpecifier, specifierLen);
8811       return false;
8812     }
8813   }
8814 
8815   // First check if the field width, precision, and conversion specifier
8816   // have matching data arguments.
8817   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8818                     startSpecifier, specifierLen)) {
8819     return false;
8820   }
8821 
8822   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8823                     startSpecifier, specifierLen)) {
8824     return false;
8825   }
8826 
8827   if (!CS.consumesDataArgument()) {
8828     // FIXME: Technically specifying a precision or field width here
8829     // makes no sense.  Worth issuing a warning at some point.
8830     return true;
8831   }
8832 
8833   // Consume the argument.
8834   unsigned argIndex = FS.getArgIndex();
8835   if (argIndex < NumDataArgs) {
8836     // The check to see if the argIndex is valid will come later.
8837     // We set the bit here because we may exit early from this
8838     // function if we encounter some other error.
8839     CoveredArgs.set(argIndex);
8840   }
8841 
8842   // FreeBSD kernel extensions.
8843   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8844       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8845     // We need at least two arguments.
8846     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8847       return false;
8848 
8849     // Claim the second argument.
8850     CoveredArgs.set(argIndex + 1);
8851 
8852     // Type check the first argument (int for %b, pointer for %D)
8853     const Expr *Ex = getDataArg(argIndex);
8854     const analyze_printf::ArgType &AT =
8855       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8856         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8857     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8858       EmitFormatDiagnostic(
8859           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8860               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8861               << false << Ex->getSourceRange(),
8862           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8863           getSpecifierRange(startSpecifier, specifierLen));
8864 
8865     // Type check the second argument (char * for both %b and %D)
8866     Ex = getDataArg(argIndex + 1);
8867     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8868     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8869       EmitFormatDiagnostic(
8870           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8871               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8872               << false << Ex->getSourceRange(),
8873           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8874           getSpecifierRange(startSpecifier, specifierLen));
8875 
8876      return true;
8877   }
8878 
8879   // Check for using an Objective-C specific conversion specifier
8880   // in a non-ObjC literal.
8881   if (!allowsObjCArg() && CS.isObjCArg()) {
8882     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8883                                                   specifierLen);
8884   }
8885 
8886   // %P can only be used with os_log.
8887   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8888     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8889                                                   specifierLen);
8890   }
8891 
8892   // %n is not allowed with os_log.
8893   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8894     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8895                          getLocationOfByte(CS.getStart()),
8896                          /*IsStringLocation*/ false,
8897                          getSpecifierRange(startSpecifier, specifierLen));
8898 
8899     return true;
8900   }
8901 
8902   // Only scalars are allowed for os_trace.
8903   if (FSType == Sema::FST_OSTrace &&
8904       (CS.getKind() == ConversionSpecifier::PArg ||
8905        CS.getKind() == ConversionSpecifier::sArg ||
8906        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8907     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8908                                                   specifierLen);
8909   }
8910 
8911   // Check for use of public/private annotation outside of os_log().
8912   if (FSType != Sema::FST_OSLog) {
8913     if (FS.isPublic().isSet()) {
8914       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8915                                << "public",
8916                            getLocationOfByte(FS.isPublic().getPosition()),
8917                            /*IsStringLocation*/ false,
8918                            getSpecifierRange(startSpecifier, specifierLen));
8919     }
8920     if (FS.isPrivate().isSet()) {
8921       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8922                                << "private",
8923                            getLocationOfByte(FS.isPrivate().getPosition()),
8924                            /*IsStringLocation*/ false,
8925                            getSpecifierRange(startSpecifier, specifierLen));
8926     }
8927   }
8928 
8929   // Check for invalid use of field width
8930   if (!FS.hasValidFieldWidth()) {
8931     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8932         startSpecifier, specifierLen);
8933   }
8934 
8935   // Check for invalid use of precision
8936   if (!FS.hasValidPrecision()) {
8937     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8938         startSpecifier, specifierLen);
8939   }
8940 
8941   // Precision is mandatory for %P specifier.
8942   if (CS.getKind() == ConversionSpecifier::PArg &&
8943       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8944     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8945                          getLocationOfByte(startSpecifier),
8946                          /*IsStringLocation*/ false,
8947                          getSpecifierRange(startSpecifier, specifierLen));
8948   }
8949 
8950   // Check each flag does not conflict with any other component.
8951   if (!FS.hasValidThousandsGroupingPrefix())
8952     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8953   if (!FS.hasValidLeadingZeros())
8954     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8955   if (!FS.hasValidPlusPrefix())
8956     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8957   if (!FS.hasValidSpacePrefix())
8958     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8959   if (!FS.hasValidAlternativeForm())
8960     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8961   if (!FS.hasValidLeftJustified())
8962     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8963 
8964   // Check that flags are not ignored by another flag
8965   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8966     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8967         startSpecifier, specifierLen);
8968   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8969     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8970             startSpecifier, specifierLen);
8971 
8972   // Check the length modifier is valid with the given conversion specifier.
8973   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8974                                  S.getLangOpts()))
8975     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8976                                 diag::warn_format_nonsensical_length);
8977   else if (!FS.hasStandardLengthModifier())
8978     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8979   else if (!FS.hasStandardLengthConversionCombination())
8980     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8981                                 diag::warn_format_non_standard_conversion_spec);
8982 
8983   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8984     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8985 
8986   // The remaining checks depend on the data arguments.
8987   if (HasVAListArg)
8988     return true;
8989 
8990   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8991     return false;
8992 
8993   const Expr *Arg = getDataArg(argIndex);
8994   if (!Arg)
8995     return true;
8996 
8997   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8998 }
8999 
9000 static bool requiresParensToAddCast(const Expr *E) {
9001   // FIXME: We should have a general way to reason about operator
9002   // precedence and whether parens are actually needed here.
9003   // Take care of a few common cases where they aren't.
9004   const Expr *Inside = E->IgnoreImpCasts();
9005   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9006     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9007 
9008   switch (Inside->getStmtClass()) {
9009   case Stmt::ArraySubscriptExprClass:
9010   case Stmt::CallExprClass:
9011   case Stmt::CharacterLiteralClass:
9012   case Stmt::CXXBoolLiteralExprClass:
9013   case Stmt::DeclRefExprClass:
9014   case Stmt::FloatingLiteralClass:
9015   case Stmt::IntegerLiteralClass:
9016   case Stmt::MemberExprClass:
9017   case Stmt::ObjCArrayLiteralClass:
9018   case Stmt::ObjCBoolLiteralExprClass:
9019   case Stmt::ObjCBoxedExprClass:
9020   case Stmt::ObjCDictionaryLiteralClass:
9021   case Stmt::ObjCEncodeExprClass:
9022   case Stmt::ObjCIvarRefExprClass:
9023   case Stmt::ObjCMessageExprClass:
9024   case Stmt::ObjCPropertyRefExprClass:
9025   case Stmt::ObjCStringLiteralClass:
9026   case Stmt::ObjCSubscriptRefExprClass:
9027   case Stmt::ParenExprClass:
9028   case Stmt::StringLiteralClass:
9029   case Stmt::UnaryOperatorClass:
9030     return false;
9031   default:
9032     return true;
9033   }
9034 }
9035 
9036 static std::pair<QualType, StringRef>
9037 shouldNotPrintDirectly(const ASTContext &Context,
9038                        QualType IntendedTy,
9039                        const Expr *E) {
9040   // Use a 'while' to peel off layers of typedefs.
9041   QualType TyTy = IntendedTy;
9042   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9043     StringRef Name = UserTy->getDecl()->getName();
9044     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9045       .Case("CFIndex", Context.getNSIntegerType())
9046       .Case("NSInteger", Context.getNSIntegerType())
9047       .Case("NSUInteger", Context.getNSUIntegerType())
9048       .Case("SInt32", Context.IntTy)
9049       .Case("UInt32", Context.UnsignedIntTy)
9050       .Default(QualType());
9051 
9052     if (!CastTy.isNull())
9053       return std::make_pair(CastTy, Name);
9054 
9055     TyTy = UserTy->desugar();
9056   }
9057 
9058   // Strip parens if necessary.
9059   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9060     return shouldNotPrintDirectly(Context,
9061                                   PE->getSubExpr()->getType(),
9062                                   PE->getSubExpr());
9063 
9064   // If this is a conditional expression, then its result type is constructed
9065   // via usual arithmetic conversions and thus there might be no necessary
9066   // typedef sugar there.  Recurse to operands to check for NSInteger &
9067   // Co. usage condition.
9068   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9069     QualType TrueTy, FalseTy;
9070     StringRef TrueName, FalseName;
9071 
9072     std::tie(TrueTy, TrueName) =
9073       shouldNotPrintDirectly(Context,
9074                              CO->getTrueExpr()->getType(),
9075                              CO->getTrueExpr());
9076     std::tie(FalseTy, FalseName) =
9077       shouldNotPrintDirectly(Context,
9078                              CO->getFalseExpr()->getType(),
9079                              CO->getFalseExpr());
9080 
9081     if (TrueTy == FalseTy)
9082       return std::make_pair(TrueTy, TrueName);
9083     else if (TrueTy.isNull())
9084       return std::make_pair(FalseTy, FalseName);
9085     else if (FalseTy.isNull())
9086       return std::make_pair(TrueTy, TrueName);
9087   }
9088 
9089   return std::make_pair(QualType(), StringRef());
9090 }
9091 
9092 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9093 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9094 /// type do not count.
9095 static bool
9096 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9097   QualType From = ICE->getSubExpr()->getType();
9098   QualType To = ICE->getType();
9099   // It's an integer promotion if the destination type is the promoted
9100   // source type.
9101   if (ICE->getCastKind() == CK_IntegralCast &&
9102       From->isPromotableIntegerType() &&
9103       S.Context.getPromotedIntegerType(From) == To)
9104     return true;
9105   // Look through vector types, since we do default argument promotion for
9106   // those in OpenCL.
9107   if (const auto *VecTy = From->getAs<ExtVectorType>())
9108     From = VecTy->getElementType();
9109   if (const auto *VecTy = To->getAs<ExtVectorType>())
9110     To = VecTy->getElementType();
9111   // It's a floating promotion if the source type is a lower rank.
9112   return ICE->getCastKind() == CK_FloatingCast &&
9113          S.Context.getFloatingTypeOrder(From, To) < 0;
9114 }
9115 
9116 bool
9117 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9118                                     const char *StartSpecifier,
9119                                     unsigned SpecifierLen,
9120                                     const Expr *E) {
9121   using namespace analyze_format_string;
9122   using namespace analyze_printf;
9123 
9124   // Now type check the data expression that matches the
9125   // format specifier.
9126   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9127   if (!AT.isValid())
9128     return true;
9129 
9130   QualType ExprTy = E->getType();
9131   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9132     ExprTy = TET->getUnderlyingExpr()->getType();
9133   }
9134 
9135   // Diagnose attempts to print a boolean value as a character. Unlike other
9136   // -Wformat diagnostics, this is fine from a type perspective, but it still
9137   // doesn't make sense.
9138   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9139       E->isKnownToHaveBooleanValue()) {
9140     const CharSourceRange &CSR =
9141         getSpecifierRange(StartSpecifier, SpecifierLen);
9142     SmallString<4> FSString;
9143     llvm::raw_svector_ostream os(FSString);
9144     FS.toString(os);
9145     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9146                              << FSString,
9147                          E->getExprLoc(), false, CSR);
9148     return true;
9149   }
9150 
9151   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9152   if (Match == analyze_printf::ArgType::Match)
9153     return true;
9154 
9155   // Look through argument promotions for our error message's reported type.
9156   // This includes the integral and floating promotions, but excludes array
9157   // and function pointer decay (seeing that an argument intended to be a
9158   // string has type 'char [6]' is probably more confusing than 'char *') and
9159   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9160   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9161     if (isArithmeticArgumentPromotion(S, ICE)) {
9162       E = ICE->getSubExpr();
9163       ExprTy = E->getType();
9164 
9165       // Check if we didn't match because of an implicit cast from a 'char'
9166       // or 'short' to an 'int'.  This is done because printf is a varargs
9167       // function.
9168       if (ICE->getType() == S.Context.IntTy ||
9169           ICE->getType() == S.Context.UnsignedIntTy) {
9170         // All further checking is done on the subexpression
9171         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9172             AT.matchesType(S.Context, ExprTy);
9173         if (ImplicitMatch == analyze_printf::ArgType::Match)
9174           return true;
9175         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9176             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9177           Match = ImplicitMatch;
9178       }
9179     }
9180   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9181     // Special case for 'a', which has type 'int' in C.
9182     // Note, however, that we do /not/ want to treat multibyte constants like
9183     // 'MooV' as characters! This form is deprecated but still exists. In
9184     // addition, don't treat expressions as of type 'char' if one byte length
9185     // modifier is provided.
9186     if (ExprTy == S.Context.IntTy &&
9187         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9188       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9189         ExprTy = S.Context.CharTy;
9190   }
9191 
9192   // Look through enums to their underlying type.
9193   bool IsEnum = false;
9194   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9195     ExprTy = EnumTy->getDecl()->getIntegerType();
9196     IsEnum = true;
9197   }
9198 
9199   // %C in an Objective-C context prints a unichar, not a wchar_t.
9200   // If the argument is an integer of some kind, believe the %C and suggest
9201   // a cast instead of changing the conversion specifier.
9202   QualType IntendedTy = ExprTy;
9203   if (isObjCContext() &&
9204       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9205     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9206         !ExprTy->isCharType()) {
9207       // 'unichar' is defined as a typedef of unsigned short, but we should
9208       // prefer using the typedef if it is visible.
9209       IntendedTy = S.Context.UnsignedShortTy;
9210 
9211       // While we are here, check if the value is an IntegerLiteral that happens
9212       // to be within the valid range.
9213       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9214         const llvm::APInt &V = IL->getValue();
9215         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9216           return true;
9217       }
9218 
9219       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9220                           Sema::LookupOrdinaryName);
9221       if (S.LookupName(Result, S.getCurScope())) {
9222         NamedDecl *ND = Result.getFoundDecl();
9223         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9224           if (TD->getUnderlyingType() == IntendedTy)
9225             IntendedTy = S.Context.getTypedefType(TD);
9226       }
9227     }
9228   }
9229 
9230   // Special-case some of Darwin's platform-independence types by suggesting
9231   // casts to primitive types that are known to be large enough.
9232   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9233   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9234     QualType CastTy;
9235     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9236     if (!CastTy.isNull()) {
9237       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9238       // (long in ASTContext). Only complain to pedants.
9239       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9240           (AT.isSizeT() || AT.isPtrdiffT()) &&
9241           AT.matchesType(S.Context, CastTy))
9242         Match = ArgType::NoMatchPedantic;
9243       IntendedTy = CastTy;
9244       ShouldNotPrintDirectly = true;
9245     }
9246   }
9247 
9248   // We may be able to offer a FixItHint if it is a supported type.
9249   PrintfSpecifier fixedFS = FS;
9250   bool Success =
9251       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9252 
9253   if (Success) {
9254     // Get the fix string from the fixed format specifier
9255     SmallString<16> buf;
9256     llvm::raw_svector_ostream os(buf);
9257     fixedFS.toString(os);
9258 
9259     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9260 
9261     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9262       unsigned Diag;
9263       switch (Match) {
9264       case ArgType::Match: llvm_unreachable("expected non-matching");
9265       case ArgType::NoMatchPedantic:
9266         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9267         break;
9268       case ArgType::NoMatchTypeConfusion:
9269         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9270         break;
9271       case ArgType::NoMatch:
9272         Diag = diag::warn_format_conversion_argument_type_mismatch;
9273         break;
9274       }
9275 
9276       // In this case, the specifier is wrong and should be changed to match
9277       // the argument.
9278       EmitFormatDiagnostic(S.PDiag(Diag)
9279                                << AT.getRepresentativeTypeName(S.Context)
9280                                << IntendedTy << IsEnum << E->getSourceRange(),
9281                            E->getBeginLoc(),
9282                            /*IsStringLocation*/ false, SpecRange,
9283                            FixItHint::CreateReplacement(SpecRange, os.str()));
9284     } else {
9285       // The canonical type for formatting this value is different from the
9286       // actual type of the expression. (This occurs, for example, with Darwin's
9287       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9288       // should be printed as 'long' for 64-bit compatibility.)
9289       // Rather than emitting a normal format/argument mismatch, we want to
9290       // add a cast to the recommended type (and correct the format string
9291       // if necessary).
9292       SmallString<16> CastBuf;
9293       llvm::raw_svector_ostream CastFix(CastBuf);
9294       CastFix << "(";
9295       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9296       CastFix << ")";
9297 
9298       SmallVector<FixItHint,4> Hints;
9299       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9300         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9301 
9302       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9303         // If there's already a cast present, just replace it.
9304         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9305         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9306 
9307       } else if (!requiresParensToAddCast(E)) {
9308         // If the expression has high enough precedence,
9309         // just write the C-style cast.
9310         Hints.push_back(
9311             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9312       } else {
9313         // Otherwise, add parens around the expression as well as the cast.
9314         CastFix << "(";
9315         Hints.push_back(
9316             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9317 
9318         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9319         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9320       }
9321 
9322       if (ShouldNotPrintDirectly) {
9323         // The expression has a type that should not be printed directly.
9324         // We extract the name from the typedef because we don't want to show
9325         // the underlying type in the diagnostic.
9326         StringRef Name;
9327         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9328           Name = TypedefTy->getDecl()->getName();
9329         else
9330           Name = CastTyName;
9331         unsigned Diag = Match == ArgType::NoMatchPedantic
9332                             ? diag::warn_format_argument_needs_cast_pedantic
9333                             : diag::warn_format_argument_needs_cast;
9334         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9335                                            << E->getSourceRange(),
9336                              E->getBeginLoc(), /*IsStringLocation=*/false,
9337                              SpecRange, Hints);
9338       } else {
9339         // In this case, the expression could be printed using a different
9340         // specifier, but we've decided that the specifier is probably correct
9341         // and we should cast instead. Just use the normal warning message.
9342         EmitFormatDiagnostic(
9343             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9344                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9345                 << E->getSourceRange(),
9346             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9347       }
9348     }
9349   } else {
9350     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9351                                                    SpecifierLen);
9352     // Since the warning for passing non-POD types to variadic functions
9353     // was deferred until now, we emit a warning for non-POD
9354     // arguments here.
9355     switch (S.isValidVarArgType(ExprTy)) {
9356     case Sema::VAK_Valid:
9357     case Sema::VAK_ValidInCXX11: {
9358       unsigned Diag;
9359       switch (Match) {
9360       case ArgType::Match: llvm_unreachable("expected non-matching");
9361       case ArgType::NoMatchPedantic:
9362         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9363         break;
9364       case ArgType::NoMatchTypeConfusion:
9365         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9366         break;
9367       case ArgType::NoMatch:
9368         Diag = diag::warn_format_conversion_argument_type_mismatch;
9369         break;
9370       }
9371 
9372       EmitFormatDiagnostic(
9373           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9374                         << IsEnum << CSR << E->getSourceRange(),
9375           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9376       break;
9377     }
9378     case Sema::VAK_Undefined:
9379     case Sema::VAK_MSVCUndefined:
9380       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9381                                << S.getLangOpts().CPlusPlus11 << ExprTy
9382                                << CallType
9383                                << AT.getRepresentativeTypeName(S.Context) << CSR
9384                                << E->getSourceRange(),
9385                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9386       checkForCStrMembers(AT, E);
9387       break;
9388 
9389     case Sema::VAK_Invalid:
9390       if (ExprTy->isObjCObjectType())
9391         EmitFormatDiagnostic(
9392             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9393                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9394                 << AT.getRepresentativeTypeName(S.Context) << CSR
9395                 << E->getSourceRange(),
9396             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9397       else
9398         // FIXME: If this is an initializer list, suggest removing the braces
9399         // or inserting a cast to the target type.
9400         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9401             << isa<InitListExpr>(E) << ExprTy << CallType
9402             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9403       break;
9404     }
9405 
9406     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9407            "format string specifier index out of range");
9408     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9409   }
9410 
9411   return true;
9412 }
9413 
9414 //===--- CHECK: Scanf format string checking ------------------------------===//
9415 
9416 namespace {
9417 
9418 class CheckScanfHandler : public CheckFormatHandler {
9419 public:
9420   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9421                     const Expr *origFormatExpr, Sema::FormatStringType type,
9422                     unsigned firstDataArg, unsigned numDataArgs,
9423                     const char *beg, bool hasVAListArg,
9424                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9425                     bool inFunctionCall, Sema::VariadicCallType CallType,
9426                     llvm::SmallBitVector &CheckedVarArgs,
9427                     UncoveredArgHandler &UncoveredArg)
9428       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9429                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9430                            inFunctionCall, CallType, CheckedVarArgs,
9431                            UncoveredArg) {}
9432 
9433   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9434                             const char *startSpecifier,
9435                             unsigned specifierLen) override;
9436 
9437   bool HandleInvalidScanfConversionSpecifier(
9438           const analyze_scanf::ScanfSpecifier &FS,
9439           const char *startSpecifier,
9440           unsigned specifierLen) override;
9441 
9442   void HandleIncompleteScanList(const char *start, const char *end) override;
9443 };
9444 
9445 } // namespace
9446 
9447 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9448                                                  const char *end) {
9449   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9450                        getLocationOfByte(end), /*IsStringLocation*/true,
9451                        getSpecifierRange(start, end - start));
9452 }
9453 
9454 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9455                                         const analyze_scanf::ScanfSpecifier &FS,
9456                                         const char *startSpecifier,
9457                                         unsigned specifierLen) {
9458   const analyze_scanf::ScanfConversionSpecifier &CS =
9459     FS.getConversionSpecifier();
9460 
9461   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9462                                           getLocationOfByte(CS.getStart()),
9463                                           startSpecifier, specifierLen,
9464                                           CS.getStart(), CS.getLength());
9465 }
9466 
9467 bool CheckScanfHandler::HandleScanfSpecifier(
9468                                        const analyze_scanf::ScanfSpecifier &FS,
9469                                        const char *startSpecifier,
9470                                        unsigned specifierLen) {
9471   using namespace analyze_scanf;
9472   using namespace analyze_format_string;
9473 
9474   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9475 
9476   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9477   // be used to decide if we are using positional arguments consistently.
9478   if (FS.consumesDataArgument()) {
9479     if (atFirstArg) {
9480       atFirstArg = false;
9481       usesPositionalArgs = FS.usesPositionalArg();
9482     }
9483     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9484       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9485                                         startSpecifier, specifierLen);
9486       return false;
9487     }
9488   }
9489 
9490   // Check if the field with is non-zero.
9491   const OptionalAmount &Amt = FS.getFieldWidth();
9492   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9493     if (Amt.getConstantAmount() == 0) {
9494       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9495                                                    Amt.getConstantLength());
9496       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9497                            getLocationOfByte(Amt.getStart()),
9498                            /*IsStringLocation*/true, R,
9499                            FixItHint::CreateRemoval(R));
9500     }
9501   }
9502 
9503   if (!FS.consumesDataArgument()) {
9504     // FIXME: Technically specifying a precision or field width here
9505     // makes no sense.  Worth issuing a warning at some point.
9506     return true;
9507   }
9508 
9509   // Consume the argument.
9510   unsigned argIndex = FS.getArgIndex();
9511   if (argIndex < NumDataArgs) {
9512       // The check to see if the argIndex is valid will come later.
9513       // We set the bit here because we may exit early from this
9514       // function if we encounter some other error.
9515     CoveredArgs.set(argIndex);
9516   }
9517 
9518   // Check the length modifier is valid with the given conversion specifier.
9519   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9520                                  S.getLangOpts()))
9521     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9522                                 diag::warn_format_nonsensical_length);
9523   else if (!FS.hasStandardLengthModifier())
9524     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9525   else if (!FS.hasStandardLengthConversionCombination())
9526     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9527                                 diag::warn_format_non_standard_conversion_spec);
9528 
9529   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9530     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9531 
9532   // The remaining checks depend on the data arguments.
9533   if (HasVAListArg)
9534     return true;
9535 
9536   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9537     return false;
9538 
9539   // Check that the argument type matches the format specifier.
9540   const Expr *Ex = getDataArg(argIndex);
9541   if (!Ex)
9542     return true;
9543 
9544   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9545 
9546   if (!AT.isValid()) {
9547     return true;
9548   }
9549 
9550   analyze_format_string::ArgType::MatchKind Match =
9551       AT.matchesType(S.Context, Ex->getType());
9552   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9553   if (Match == analyze_format_string::ArgType::Match)
9554     return true;
9555 
9556   ScanfSpecifier fixedFS = FS;
9557   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9558                                  S.getLangOpts(), S.Context);
9559 
9560   unsigned Diag =
9561       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9562                : diag::warn_format_conversion_argument_type_mismatch;
9563 
9564   if (Success) {
9565     // Get the fix string from the fixed format specifier.
9566     SmallString<128> buf;
9567     llvm::raw_svector_ostream os(buf);
9568     fixedFS.toString(os);
9569 
9570     EmitFormatDiagnostic(
9571         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9572                       << Ex->getType() << false << Ex->getSourceRange(),
9573         Ex->getBeginLoc(),
9574         /*IsStringLocation*/ false,
9575         getSpecifierRange(startSpecifier, specifierLen),
9576         FixItHint::CreateReplacement(
9577             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9578   } else {
9579     EmitFormatDiagnostic(S.PDiag(Diag)
9580                              << AT.getRepresentativeTypeName(S.Context)
9581                              << Ex->getType() << false << Ex->getSourceRange(),
9582                          Ex->getBeginLoc(),
9583                          /*IsStringLocation*/ false,
9584                          getSpecifierRange(startSpecifier, specifierLen));
9585   }
9586 
9587   return true;
9588 }
9589 
9590 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9591                               const Expr *OrigFormatExpr,
9592                               ArrayRef<const Expr *> Args,
9593                               bool HasVAListArg, unsigned format_idx,
9594                               unsigned firstDataArg,
9595                               Sema::FormatStringType Type,
9596                               bool inFunctionCall,
9597                               Sema::VariadicCallType CallType,
9598                               llvm::SmallBitVector &CheckedVarArgs,
9599                               UncoveredArgHandler &UncoveredArg,
9600                               bool IgnoreStringsWithoutSpecifiers) {
9601   // CHECK: is the format string a wide literal?
9602   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9603     CheckFormatHandler::EmitFormatDiagnostic(
9604         S, inFunctionCall, Args[format_idx],
9605         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9606         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9607     return;
9608   }
9609 
9610   // Str - The format string.  NOTE: this is NOT null-terminated!
9611   StringRef StrRef = FExpr->getString();
9612   const char *Str = StrRef.data();
9613   // Account for cases where the string literal is truncated in a declaration.
9614   const ConstantArrayType *T =
9615     S.Context.getAsConstantArrayType(FExpr->getType());
9616   assert(T && "String literal not of constant array type!");
9617   size_t TypeSize = T->getSize().getZExtValue();
9618   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9619   const unsigned numDataArgs = Args.size() - firstDataArg;
9620 
9621   if (IgnoreStringsWithoutSpecifiers &&
9622       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9623           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9624     return;
9625 
9626   // Emit a warning if the string literal is truncated and does not contain an
9627   // embedded null character.
9628   if (TypeSize <= StrRef.size() &&
9629       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9630     CheckFormatHandler::EmitFormatDiagnostic(
9631         S, inFunctionCall, Args[format_idx],
9632         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9633         FExpr->getBeginLoc(),
9634         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9635     return;
9636   }
9637 
9638   // CHECK: empty format string?
9639   if (StrLen == 0 && numDataArgs > 0) {
9640     CheckFormatHandler::EmitFormatDiagnostic(
9641         S, inFunctionCall, Args[format_idx],
9642         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9643         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9644     return;
9645   }
9646 
9647   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9648       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9649       Type == Sema::FST_OSTrace) {
9650     CheckPrintfHandler H(
9651         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9652         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9653         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9654         CheckedVarArgs, UncoveredArg);
9655 
9656     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9657                                                   S.getLangOpts(),
9658                                                   S.Context.getTargetInfo(),
9659                                             Type == Sema::FST_FreeBSDKPrintf))
9660       H.DoneProcessing();
9661   } else if (Type == Sema::FST_Scanf) {
9662     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9663                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9664                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9665 
9666     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9667                                                  S.getLangOpts(),
9668                                                  S.Context.getTargetInfo()))
9669       H.DoneProcessing();
9670   } // TODO: handle other formats
9671 }
9672 
9673 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9674   // Str - The format string.  NOTE: this is NOT null-terminated!
9675   StringRef StrRef = FExpr->getString();
9676   const char *Str = StrRef.data();
9677   // Account for cases where the string literal is truncated in a declaration.
9678   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9679   assert(T && "String literal not of constant array type!");
9680   size_t TypeSize = T->getSize().getZExtValue();
9681   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9682   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9683                                                          getLangOpts(),
9684                                                          Context.getTargetInfo());
9685 }
9686 
9687 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9688 
9689 // Returns the related absolute value function that is larger, of 0 if one
9690 // does not exist.
9691 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9692   switch (AbsFunction) {
9693   default:
9694     return 0;
9695 
9696   case Builtin::BI__builtin_abs:
9697     return Builtin::BI__builtin_labs;
9698   case Builtin::BI__builtin_labs:
9699     return Builtin::BI__builtin_llabs;
9700   case Builtin::BI__builtin_llabs:
9701     return 0;
9702 
9703   case Builtin::BI__builtin_fabsf:
9704     return Builtin::BI__builtin_fabs;
9705   case Builtin::BI__builtin_fabs:
9706     return Builtin::BI__builtin_fabsl;
9707   case Builtin::BI__builtin_fabsl:
9708     return 0;
9709 
9710   case Builtin::BI__builtin_cabsf:
9711     return Builtin::BI__builtin_cabs;
9712   case Builtin::BI__builtin_cabs:
9713     return Builtin::BI__builtin_cabsl;
9714   case Builtin::BI__builtin_cabsl:
9715     return 0;
9716 
9717   case Builtin::BIabs:
9718     return Builtin::BIlabs;
9719   case Builtin::BIlabs:
9720     return Builtin::BIllabs;
9721   case Builtin::BIllabs:
9722     return 0;
9723 
9724   case Builtin::BIfabsf:
9725     return Builtin::BIfabs;
9726   case Builtin::BIfabs:
9727     return Builtin::BIfabsl;
9728   case Builtin::BIfabsl:
9729     return 0;
9730 
9731   case Builtin::BIcabsf:
9732    return Builtin::BIcabs;
9733   case Builtin::BIcabs:
9734     return Builtin::BIcabsl;
9735   case Builtin::BIcabsl:
9736     return 0;
9737   }
9738 }
9739 
9740 // Returns the argument type of the absolute value function.
9741 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9742                                              unsigned AbsType) {
9743   if (AbsType == 0)
9744     return QualType();
9745 
9746   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9747   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9748   if (Error != ASTContext::GE_None)
9749     return QualType();
9750 
9751   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9752   if (!FT)
9753     return QualType();
9754 
9755   if (FT->getNumParams() != 1)
9756     return QualType();
9757 
9758   return FT->getParamType(0);
9759 }
9760 
9761 // Returns the best absolute value function, or zero, based on type and
9762 // current absolute value function.
9763 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9764                                    unsigned AbsFunctionKind) {
9765   unsigned BestKind = 0;
9766   uint64_t ArgSize = Context.getTypeSize(ArgType);
9767   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9768        Kind = getLargerAbsoluteValueFunction(Kind)) {
9769     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9770     if (Context.getTypeSize(ParamType) >= ArgSize) {
9771       if (BestKind == 0)
9772         BestKind = Kind;
9773       else if (Context.hasSameType(ParamType, ArgType)) {
9774         BestKind = Kind;
9775         break;
9776       }
9777     }
9778   }
9779   return BestKind;
9780 }
9781 
9782 enum AbsoluteValueKind {
9783   AVK_Integer,
9784   AVK_Floating,
9785   AVK_Complex
9786 };
9787 
9788 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9789   if (T->isIntegralOrEnumerationType())
9790     return AVK_Integer;
9791   if (T->isRealFloatingType())
9792     return AVK_Floating;
9793   if (T->isAnyComplexType())
9794     return AVK_Complex;
9795 
9796   llvm_unreachable("Type not integer, floating, or complex");
9797 }
9798 
9799 // Changes the absolute value function to a different type.  Preserves whether
9800 // the function is a builtin.
9801 static unsigned changeAbsFunction(unsigned AbsKind,
9802                                   AbsoluteValueKind ValueKind) {
9803   switch (ValueKind) {
9804   case AVK_Integer:
9805     switch (AbsKind) {
9806     default:
9807       return 0;
9808     case Builtin::BI__builtin_fabsf:
9809     case Builtin::BI__builtin_fabs:
9810     case Builtin::BI__builtin_fabsl:
9811     case Builtin::BI__builtin_cabsf:
9812     case Builtin::BI__builtin_cabs:
9813     case Builtin::BI__builtin_cabsl:
9814       return Builtin::BI__builtin_abs;
9815     case Builtin::BIfabsf:
9816     case Builtin::BIfabs:
9817     case Builtin::BIfabsl:
9818     case Builtin::BIcabsf:
9819     case Builtin::BIcabs:
9820     case Builtin::BIcabsl:
9821       return Builtin::BIabs;
9822     }
9823   case AVK_Floating:
9824     switch (AbsKind) {
9825     default:
9826       return 0;
9827     case Builtin::BI__builtin_abs:
9828     case Builtin::BI__builtin_labs:
9829     case Builtin::BI__builtin_llabs:
9830     case Builtin::BI__builtin_cabsf:
9831     case Builtin::BI__builtin_cabs:
9832     case Builtin::BI__builtin_cabsl:
9833       return Builtin::BI__builtin_fabsf;
9834     case Builtin::BIabs:
9835     case Builtin::BIlabs:
9836     case Builtin::BIllabs:
9837     case Builtin::BIcabsf:
9838     case Builtin::BIcabs:
9839     case Builtin::BIcabsl:
9840       return Builtin::BIfabsf;
9841     }
9842   case AVK_Complex:
9843     switch (AbsKind) {
9844     default:
9845       return 0;
9846     case Builtin::BI__builtin_abs:
9847     case Builtin::BI__builtin_labs:
9848     case Builtin::BI__builtin_llabs:
9849     case Builtin::BI__builtin_fabsf:
9850     case Builtin::BI__builtin_fabs:
9851     case Builtin::BI__builtin_fabsl:
9852       return Builtin::BI__builtin_cabsf;
9853     case Builtin::BIabs:
9854     case Builtin::BIlabs:
9855     case Builtin::BIllabs:
9856     case Builtin::BIfabsf:
9857     case Builtin::BIfabs:
9858     case Builtin::BIfabsl:
9859       return Builtin::BIcabsf;
9860     }
9861   }
9862   llvm_unreachable("Unable to convert function");
9863 }
9864 
9865 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9866   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9867   if (!FnInfo)
9868     return 0;
9869 
9870   switch (FDecl->getBuiltinID()) {
9871   default:
9872     return 0;
9873   case Builtin::BI__builtin_abs:
9874   case Builtin::BI__builtin_fabs:
9875   case Builtin::BI__builtin_fabsf:
9876   case Builtin::BI__builtin_fabsl:
9877   case Builtin::BI__builtin_labs:
9878   case Builtin::BI__builtin_llabs:
9879   case Builtin::BI__builtin_cabs:
9880   case Builtin::BI__builtin_cabsf:
9881   case Builtin::BI__builtin_cabsl:
9882   case Builtin::BIabs:
9883   case Builtin::BIlabs:
9884   case Builtin::BIllabs:
9885   case Builtin::BIfabs:
9886   case Builtin::BIfabsf:
9887   case Builtin::BIfabsl:
9888   case Builtin::BIcabs:
9889   case Builtin::BIcabsf:
9890   case Builtin::BIcabsl:
9891     return FDecl->getBuiltinID();
9892   }
9893   llvm_unreachable("Unknown Builtin type");
9894 }
9895 
9896 // If the replacement is valid, emit a note with replacement function.
9897 // Additionally, suggest including the proper header if not already included.
9898 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9899                             unsigned AbsKind, QualType ArgType) {
9900   bool EmitHeaderHint = true;
9901   const char *HeaderName = nullptr;
9902   const char *FunctionName = nullptr;
9903   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9904     FunctionName = "std::abs";
9905     if (ArgType->isIntegralOrEnumerationType()) {
9906       HeaderName = "cstdlib";
9907     } else if (ArgType->isRealFloatingType()) {
9908       HeaderName = "cmath";
9909     } else {
9910       llvm_unreachable("Invalid Type");
9911     }
9912 
9913     // Lookup all std::abs
9914     if (NamespaceDecl *Std = S.getStdNamespace()) {
9915       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9916       R.suppressDiagnostics();
9917       S.LookupQualifiedName(R, Std);
9918 
9919       for (const auto *I : R) {
9920         const FunctionDecl *FDecl = nullptr;
9921         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9922           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9923         } else {
9924           FDecl = dyn_cast<FunctionDecl>(I);
9925         }
9926         if (!FDecl)
9927           continue;
9928 
9929         // Found std::abs(), check that they are the right ones.
9930         if (FDecl->getNumParams() != 1)
9931           continue;
9932 
9933         // Check that the parameter type can handle the argument.
9934         QualType ParamType = FDecl->getParamDecl(0)->getType();
9935         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9936             S.Context.getTypeSize(ArgType) <=
9937                 S.Context.getTypeSize(ParamType)) {
9938           // Found a function, don't need the header hint.
9939           EmitHeaderHint = false;
9940           break;
9941         }
9942       }
9943     }
9944   } else {
9945     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9946     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9947 
9948     if (HeaderName) {
9949       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9950       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9951       R.suppressDiagnostics();
9952       S.LookupName(R, S.getCurScope());
9953 
9954       if (R.isSingleResult()) {
9955         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9956         if (FD && FD->getBuiltinID() == AbsKind) {
9957           EmitHeaderHint = false;
9958         } else {
9959           return;
9960         }
9961       } else if (!R.empty()) {
9962         return;
9963       }
9964     }
9965   }
9966 
9967   S.Diag(Loc, diag::note_replace_abs_function)
9968       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9969 
9970   if (!HeaderName)
9971     return;
9972 
9973   if (!EmitHeaderHint)
9974     return;
9975 
9976   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9977                                                     << FunctionName;
9978 }
9979 
9980 template <std::size_t StrLen>
9981 static bool IsStdFunction(const FunctionDecl *FDecl,
9982                           const char (&Str)[StrLen]) {
9983   if (!FDecl)
9984     return false;
9985   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9986     return false;
9987   if (!FDecl->isInStdNamespace())
9988     return false;
9989 
9990   return true;
9991 }
9992 
9993 // Warn when using the wrong abs() function.
9994 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9995                                       const FunctionDecl *FDecl) {
9996   if (Call->getNumArgs() != 1)
9997     return;
9998 
9999   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10000   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10001   if (AbsKind == 0 && !IsStdAbs)
10002     return;
10003 
10004   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10005   QualType ParamType = Call->getArg(0)->getType();
10006 
10007   // Unsigned types cannot be negative.  Suggest removing the absolute value
10008   // function call.
10009   if (ArgType->isUnsignedIntegerType()) {
10010     const char *FunctionName =
10011         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10012     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10013     Diag(Call->getExprLoc(), diag::note_remove_abs)
10014         << FunctionName
10015         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10016     return;
10017   }
10018 
10019   // Taking the absolute value of a pointer is very suspicious, they probably
10020   // wanted to index into an array, dereference a pointer, call a function, etc.
10021   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10022     unsigned DiagType = 0;
10023     if (ArgType->isFunctionType())
10024       DiagType = 1;
10025     else if (ArgType->isArrayType())
10026       DiagType = 2;
10027 
10028     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10029     return;
10030   }
10031 
10032   // std::abs has overloads which prevent most of the absolute value problems
10033   // from occurring.
10034   if (IsStdAbs)
10035     return;
10036 
10037   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10038   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10039 
10040   // The argument and parameter are the same kind.  Check if they are the right
10041   // size.
10042   if (ArgValueKind == ParamValueKind) {
10043     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10044       return;
10045 
10046     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10047     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10048         << FDecl << ArgType << ParamType;
10049 
10050     if (NewAbsKind == 0)
10051       return;
10052 
10053     emitReplacement(*this, Call->getExprLoc(),
10054                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10055     return;
10056   }
10057 
10058   // ArgValueKind != ParamValueKind
10059   // The wrong type of absolute value function was used.  Attempt to find the
10060   // proper one.
10061   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10062   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10063   if (NewAbsKind == 0)
10064     return;
10065 
10066   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10067       << FDecl << ParamValueKind << ArgValueKind;
10068 
10069   emitReplacement(*this, Call->getExprLoc(),
10070                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10071 }
10072 
10073 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10074 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10075                                 const FunctionDecl *FDecl) {
10076   if (!Call || !FDecl) return;
10077 
10078   // Ignore template specializations and macros.
10079   if (inTemplateInstantiation()) return;
10080   if (Call->getExprLoc().isMacroID()) return;
10081 
10082   // Only care about the one template argument, two function parameter std::max
10083   if (Call->getNumArgs() != 2) return;
10084   if (!IsStdFunction(FDecl, "max")) return;
10085   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10086   if (!ArgList) return;
10087   if (ArgList->size() != 1) return;
10088 
10089   // Check that template type argument is unsigned integer.
10090   const auto& TA = ArgList->get(0);
10091   if (TA.getKind() != TemplateArgument::Type) return;
10092   QualType ArgType = TA.getAsType();
10093   if (!ArgType->isUnsignedIntegerType()) return;
10094 
10095   // See if either argument is a literal zero.
10096   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10097     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10098     if (!MTE) return false;
10099     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10100     if (!Num) return false;
10101     if (Num->getValue() != 0) return false;
10102     return true;
10103   };
10104 
10105   const Expr *FirstArg = Call->getArg(0);
10106   const Expr *SecondArg = Call->getArg(1);
10107   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10108   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10109 
10110   // Only warn when exactly one argument is zero.
10111   if (IsFirstArgZero == IsSecondArgZero) return;
10112 
10113   SourceRange FirstRange = FirstArg->getSourceRange();
10114   SourceRange SecondRange = SecondArg->getSourceRange();
10115 
10116   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10117 
10118   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10119       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10120 
10121   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10122   SourceRange RemovalRange;
10123   if (IsFirstArgZero) {
10124     RemovalRange = SourceRange(FirstRange.getBegin(),
10125                                SecondRange.getBegin().getLocWithOffset(-1));
10126   } else {
10127     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10128                                SecondRange.getEnd());
10129   }
10130 
10131   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10132         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10133         << FixItHint::CreateRemoval(RemovalRange);
10134 }
10135 
10136 //===--- CHECK: Standard memory functions ---------------------------------===//
10137 
10138 /// Takes the expression passed to the size_t parameter of functions
10139 /// such as memcmp, strncat, etc and warns if it's a comparison.
10140 ///
10141 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10142 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10143                                            IdentifierInfo *FnName,
10144                                            SourceLocation FnLoc,
10145                                            SourceLocation RParenLoc) {
10146   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10147   if (!Size)
10148     return false;
10149 
10150   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10151   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10152     return false;
10153 
10154   SourceRange SizeRange = Size->getSourceRange();
10155   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10156       << SizeRange << FnName;
10157   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10158       << FnName
10159       << FixItHint::CreateInsertion(
10160              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10161       << FixItHint::CreateRemoval(RParenLoc);
10162   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10163       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10164       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10165                                     ")");
10166 
10167   return true;
10168 }
10169 
10170 /// Determine whether the given type is or contains a dynamic class type
10171 /// (e.g., whether it has a vtable).
10172 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10173                                                      bool &IsContained) {
10174   // Look through array types while ignoring qualifiers.
10175   const Type *Ty = T->getBaseElementTypeUnsafe();
10176   IsContained = false;
10177 
10178   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10179   RD = RD ? RD->getDefinition() : nullptr;
10180   if (!RD || RD->isInvalidDecl())
10181     return nullptr;
10182 
10183   if (RD->isDynamicClass())
10184     return RD;
10185 
10186   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10187   // It's impossible for a class to transitively contain itself by value, so
10188   // infinite recursion is impossible.
10189   for (auto *FD : RD->fields()) {
10190     bool SubContained;
10191     if (const CXXRecordDecl *ContainedRD =
10192             getContainedDynamicClass(FD->getType(), SubContained)) {
10193       IsContained = true;
10194       return ContainedRD;
10195     }
10196   }
10197 
10198   return nullptr;
10199 }
10200 
10201 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10202   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10203     if (Unary->getKind() == UETT_SizeOf)
10204       return Unary;
10205   return nullptr;
10206 }
10207 
10208 /// If E is a sizeof expression, returns its argument expression,
10209 /// otherwise returns NULL.
10210 static const Expr *getSizeOfExprArg(const Expr *E) {
10211   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10212     if (!SizeOf->isArgumentType())
10213       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10214   return nullptr;
10215 }
10216 
10217 /// If E is a sizeof expression, returns its argument type.
10218 static QualType getSizeOfArgType(const Expr *E) {
10219   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10220     return SizeOf->getTypeOfArgument();
10221   return QualType();
10222 }
10223 
10224 namespace {
10225 
10226 struct SearchNonTrivialToInitializeField
10227     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10228   using Super =
10229       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10230 
10231   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10232 
10233   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10234                      SourceLocation SL) {
10235     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10236       asDerived().visitArray(PDIK, AT, SL);
10237       return;
10238     }
10239 
10240     Super::visitWithKind(PDIK, FT, SL);
10241   }
10242 
10243   void visitARCStrong(QualType FT, SourceLocation SL) {
10244     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10245   }
10246   void visitARCWeak(QualType FT, SourceLocation SL) {
10247     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10248   }
10249   void visitStruct(QualType FT, SourceLocation SL) {
10250     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10251       visit(FD->getType(), FD->getLocation());
10252   }
10253   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10254                   const ArrayType *AT, SourceLocation SL) {
10255     visit(getContext().getBaseElementType(AT), SL);
10256   }
10257   void visitTrivial(QualType FT, SourceLocation SL) {}
10258 
10259   static void diag(QualType RT, const Expr *E, Sema &S) {
10260     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10261   }
10262 
10263   ASTContext &getContext() { return S.getASTContext(); }
10264 
10265   const Expr *E;
10266   Sema &S;
10267 };
10268 
10269 struct SearchNonTrivialToCopyField
10270     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10271   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10272 
10273   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10274 
10275   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10276                      SourceLocation SL) {
10277     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10278       asDerived().visitArray(PCK, AT, SL);
10279       return;
10280     }
10281 
10282     Super::visitWithKind(PCK, FT, SL);
10283   }
10284 
10285   void visitARCStrong(QualType FT, SourceLocation SL) {
10286     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10287   }
10288   void visitARCWeak(QualType FT, SourceLocation SL) {
10289     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10290   }
10291   void visitStruct(QualType FT, SourceLocation SL) {
10292     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10293       visit(FD->getType(), FD->getLocation());
10294   }
10295   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10296                   SourceLocation SL) {
10297     visit(getContext().getBaseElementType(AT), SL);
10298   }
10299   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10300                 SourceLocation SL) {}
10301   void visitTrivial(QualType FT, SourceLocation SL) {}
10302   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10303 
10304   static void diag(QualType RT, const Expr *E, Sema &S) {
10305     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10306   }
10307 
10308   ASTContext &getContext() { return S.getASTContext(); }
10309 
10310   const Expr *E;
10311   Sema &S;
10312 };
10313 
10314 }
10315 
10316 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10317 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10318   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10319 
10320   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10321     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10322       return false;
10323 
10324     return doesExprLikelyComputeSize(BO->getLHS()) ||
10325            doesExprLikelyComputeSize(BO->getRHS());
10326   }
10327 
10328   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10329 }
10330 
10331 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10332 ///
10333 /// \code
10334 ///   #define MACRO 0
10335 ///   foo(MACRO);
10336 ///   foo(0);
10337 /// \endcode
10338 ///
10339 /// This should return true for the first call to foo, but not for the second
10340 /// (regardless of whether foo is a macro or function).
10341 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10342                                         SourceLocation CallLoc,
10343                                         SourceLocation ArgLoc) {
10344   if (!CallLoc.isMacroID())
10345     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10346 
10347   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10348          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10349 }
10350 
10351 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10352 /// last two arguments transposed.
10353 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10354   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10355     return;
10356 
10357   const Expr *SizeArg =
10358     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10359 
10360   auto isLiteralZero = [](const Expr *E) {
10361     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10362   };
10363 
10364   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10365   SourceLocation CallLoc = Call->getRParenLoc();
10366   SourceManager &SM = S.getSourceManager();
10367   if (isLiteralZero(SizeArg) &&
10368       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10369 
10370     SourceLocation DiagLoc = SizeArg->getExprLoc();
10371 
10372     // Some platforms #define bzero to __builtin_memset. See if this is the
10373     // case, and if so, emit a better diagnostic.
10374     if (BId == Builtin::BIbzero ||
10375         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10376                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10377       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10378       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10379     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10380       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10381       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10382     }
10383     return;
10384   }
10385 
10386   // If the second argument to a memset is a sizeof expression and the third
10387   // isn't, this is also likely an error. This should catch
10388   // 'memset(buf, sizeof(buf), 0xff)'.
10389   if (BId == Builtin::BImemset &&
10390       doesExprLikelyComputeSize(Call->getArg(1)) &&
10391       !doesExprLikelyComputeSize(Call->getArg(2))) {
10392     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10393     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10394     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10395     return;
10396   }
10397 }
10398 
10399 /// Check for dangerous or invalid arguments to memset().
10400 ///
10401 /// This issues warnings on known problematic, dangerous or unspecified
10402 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10403 /// function calls.
10404 ///
10405 /// \param Call The call expression to diagnose.
10406 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10407                                    unsigned BId,
10408                                    IdentifierInfo *FnName) {
10409   assert(BId != 0);
10410 
10411   // It is possible to have a non-standard definition of memset.  Validate
10412   // we have enough arguments, and if not, abort further checking.
10413   unsigned ExpectedNumArgs =
10414       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10415   if (Call->getNumArgs() < ExpectedNumArgs)
10416     return;
10417 
10418   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10419                       BId == Builtin::BIstrndup ? 1 : 2);
10420   unsigned LenArg =
10421       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10422   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10423 
10424   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10425                                      Call->getBeginLoc(), Call->getRParenLoc()))
10426     return;
10427 
10428   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10429   CheckMemaccessSize(*this, BId, Call);
10430 
10431   // We have special checking when the length is a sizeof expression.
10432   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10433   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10434   llvm::FoldingSetNodeID SizeOfArgID;
10435 
10436   // Although widely used, 'bzero' is not a standard function. Be more strict
10437   // with the argument types before allowing diagnostics and only allow the
10438   // form bzero(ptr, sizeof(...)).
10439   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10440   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10441     return;
10442 
10443   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10444     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10445     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10446 
10447     QualType DestTy = Dest->getType();
10448     QualType PointeeTy;
10449     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10450       PointeeTy = DestPtrTy->getPointeeType();
10451 
10452       // Never warn about void type pointers. This can be used to suppress
10453       // false positives.
10454       if (PointeeTy->isVoidType())
10455         continue;
10456 
10457       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10458       // actually comparing the expressions for equality. Because computing the
10459       // expression IDs can be expensive, we only do this if the diagnostic is
10460       // enabled.
10461       if (SizeOfArg &&
10462           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10463                            SizeOfArg->getExprLoc())) {
10464         // We only compute IDs for expressions if the warning is enabled, and
10465         // cache the sizeof arg's ID.
10466         if (SizeOfArgID == llvm::FoldingSetNodeID())
10467           SizeOfArg->Profile(SizeOfArgID, Context, true);
10468         llvm::FoldingSetNodeID DestID;
10469         Dest->Profile(DestID, Context, true);
10470         if (DestID == SizeOfArgID) {
10471           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10472           //       over sizeof(src) as well.
10473           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10474           StringRef ReadableName = FnName->getName();
10475 
10476           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10477             if (UnaryOp->getOpcode() == UO_AddrOf)
10478               ActionIdx = 1; // If its an address-of operator, just remove it.
10479           if (!PointeeTy->isIncompleteType() &&
10480               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10481             ActionIdx = 2; // If the pointee's size is sizeof(char),
10482                            // suggest an explicit length.
10483 
10484           // If the function is defined as a builtin macro, do not show macro
10485           // expansion.
10486           SourceLocation SL = SizeOfArg->getExprLoc();
10487           SourceRange DSR = Dest->getSourceRange();
10488           SourceRange SSR = SizeOfArg->getSourceRange();
10489           SourceManager &SM = getSourceManager();
10490 
10491           if (SM.isMacroArgExpansion(SL)) {
10492             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10493             SL = SM.getSpellingLoc(SL);
10494             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10495                              SM.getSpellingLoc(DSR.getEnd()));
10496             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10497                              SM.getSpellingLoc(SSR.getEnd()));
10498           }
10499 
10500           DiagRuntimeBehavior(SL, SizeOfArg,
10501                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10502                                 << ReadableName
10503                                 << PointeeTy
10504                                 << DestTy
10505                                 << DSR
10506                                 << SSR);
10507           DiagRuntimeBehavior(SL, SizeOfArg,
10508                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10509                                 << ActionIdx
10510                                 << SSR);
10511 
10512           break;
10513         }
10514       }
10515 
10516       // Also check for cases where the sizeof argument is the exact same
10517       // type as the memory argument, and where it points to a user-defined
10518       // record type.
10519       if (SizeOfArgTy != QualType()) {
10520         if (PointeeTy->isRecordType() &&
10521             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10522           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10523                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10524                                 << FnName << SizeOfArgTy << ArgIdx
10525                                 << PointeeTy << Dest->getSourceRange()
10526                                 << LenExpr->getSourceRange());
10527           break;
10528         }
10529       }
10530     } else if (DestTy->isArrayType()) {
10531       PointeeTy = DestTy;
10532     }
10533 
10534     if (PointeeTy == QualType())
10535       continue;
10536 
10537     // Always complain about dynamic classes.
10538     bool IsContained;
10539     if (const CXXRecordDecl *ContainedRD =
10540             getContainedDynamicClass(PointeeTy, IsContained)) {
10541 
10542       unsigned OperationType = 0;
10543       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10544       // "overwritten" if we're warning about the destination for any call
10545       // but memcmp; otherwise a verb appropriate to the call.
10546       if (ArgIdx != 0 || IsCmp) {
10547         if (BId == Builtin::BImemcpy)
10548           OperationType = 1;
10549         else if(BId == Builtin::BImemmove)
10550           OperationType = 2;
10551         else if (IsCmp)
10552           OperationType = 3;
10553       }
10554 
10555       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10556                           PDiag(diag::warn_dyn_class_memaccess)
10557                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10558                               << IsContained << ContainedRD << OperationType
10559                               << Call->getCallee()->getSourceRange());
10560     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10561              BId != Builtin::BImemset)
10562       DiagRuntimeBehavior(
10563         Dest->getExprLoc(), Dest,
10564         PDiag(diag::warn_arc_object_memaccess)
10565           << ArgIdx << FnName << PointeeTy
10566           << Call->getCallee()->getSourceRange());
10567     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10568       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10569           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10570         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10571                             PDiag(diag::warn_cstruct_memaccess)
10572                                 << ArgIdx << FnName << PointeeTy << 0);
10573         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10574       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10575                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10576         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10577                             PDiag(diag::warn_cstruct_memaccess)
10578                                 << ArgIdx << FnName << PointeeTy << 1);
10579         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10580       } else {
10581         continue;
10582       }
10583     } else
10584       continue;
10585 
10586     DiagRuntimeBehavior(
10587       Dest->getExprLoc(), Dest,
10588       PDiag(diag::note_bad_memaccess_silence)
10589         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10590     break;
10591   }
10592 }
10593 
10594 // A little helper routine: ignore addition and subtraction of integer literals.
10595 // This intentionally does not ignore all integer constant expressions because
10596 // we don't want to remove sizeof().
10597 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10598   Ex = Ex->IgnoreParenCasts();
10599 
10600   while (true) {
10601     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10602     if (!BO || !BO->isAdditiveOp())
10603       break;
10604 
10605     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10606     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10607 
10608     if (isa<IntegerLiteral>(RHS))
10609       Ex = LHS;
10610     else if (isa<IntegerLiteral>(LHS))
10611       Ex = RHS;
10612     else
10613       break;
10614   }
10615 
10616   return Ex;
10617 }
10618 
10619 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10620                                                       ASTContext &Context) {
10621   // Only handle constant-sized or VLAs, but not flexible members.
10622   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10623     // Only issue the FIXIT for arrays of size > 1.
10624     if (CAT->getSize().getSExtValue() <= 1)
10625       return false;
10626   } else if (!Ty->isVariableArrayType()) {
10627     return false;
10628   }
10629   return true;
10630 }
10631 
10632 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10633 // be the size of the source, instead of the destination.
10634 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10635                                     IdentifierInfo *FnName) {
10636 
10637   // Don't crash if the user has the wrong number of arguments
10638   unsigned NumArgs = Call->getNumArgs();
10639   if ((NumArgs != 3) && (NumArgs != 4))
10640     return;
10641 
10642   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10643   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10644   const Expr *CompareWithSrc = nullptr;
10645 
10646   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10647                                      Call->getBeginLoc(), Call->getRParenLoc()))
10648     return;
10649 
10650   // Look for 'strlcpy(dst, x, sizeof(x))'
10651   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10652     CompareWithSrc = Ex;
10653   else {
10654     // Look for 'strlcpy(dst, x, strlen(x))'
10655     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10656       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10657           SizeCall->getNumArgs() == 1)
10658         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10659     }
10660   }
10661 
10662   if (!CompareWithSrc)
10663     return;
10664 
10665   // Determine if the argument to sizeof/strlen is equal to the source
10666   // argument.  In principle there's all kinds of things you could do
10667   // here, for instance creating an == expression and evaluating it with
10668   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10669   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10670   if (!SrcArgDRE)
10671     return;
10672 
10673   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10674   if (!CompareWithSrcDRE ||
10675       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10676     return;
10677 
10678   const Expr *OriginalSizeArg = Call->getArg(2);
10679   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10680       << OriginalSizeArg->getSourceRange() << FnName;
10681 
10682   // Output a FIXIT hint if the destination is an array (rather than a
10683   // pointer to an array).  This could be enhanced to handle some
10684   // pointers if we know the actual size, like if DstArg is 'array+2'
10685   // we could say 'sizeof(array)-2'.
10686   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10687   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10688     return;
10689 
10690   SmallString<128> sizeString;
10691   llvm::raw_svector_ostream OS(sizeString);
10692   OS << "sizeof(";
10693   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10694   OS << ")";
10695 
10696   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10697       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10698                                       OS.str());
10699 }
10700 
10701 /// Check if two expressions refer to the same declaration.
10702 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10703   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10704     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10705       return D1->getDecl() == D2->getDecl();
10706   return false;
10707 }
10708 
10709 static const Expr *getStrlenExprArg(const Expr *E) {
10710   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10711     const FunctionDecl *FD = CE->getDirectCallee();
10712     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10713       return nullptr;
10714     return CE->getArg(0)->IgnoreParenCasts();
10715   }
10716   return nullptr;
10717 }
10718 
10719 // Warn on anti-patterns as the 'size' argument to strncat.
10720 // The correct size argument should look like following:
10721 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10722 void Sema::CheckStrncatArguments(const CallExpr *CE,
10723                                  IdentifierInfo *FnName) {
10724   // Don't crash if the user has the wrong number of arguments.
10725   if (CE->getNumArgs() < 3)
10726     return;
10727   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10728   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10729   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10730 
10731   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10732                                      CE->getRParenLoc()))
10733     return;
10734 
10735   // Identify common expressions, which are wrongly used as the size argument
10736   // to strncat and may lead to buffer overflows.
10737   unsigned PatternType = 0;
10738   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10739     // - sizeof(dst)
10740     if (referToTheSameDecl(SizeOfArg, DstArg))
10741       PatternType = 1;
10742     // - sizeof(src)
10743     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10744       PatternType = 2;
10745   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10746     if (BE->getOpcode() == BO_Sub) {
10747       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10748       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10749       // - sizeof(dst) - strlen(dst)
10750       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10751           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10752         PatternType = 1;
10753       // - sizeof(src) - (anything)
10754       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10755         PatternType = 2;
10756     }
10757   }
10758 
10759   if (PatternType == 0)
10760     return;
10761 
10762   // Generate the diagnostic.
10763   SourceLocation SL = LenArg->getBeginLoc();
10764   SourceRange SR = LenArg->getSourceRange();
10765   SourceManager &SM = getSourceManager();
10766 
10767   // If the function is defined as a builtin macro, do not show macro expansion.
10768   if (SM.isMacroArgExpansion(SL)) {
10769     SL = SM.getSpellingLoc(SL);
10770     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10771                      SM.getSpellingLoc(SR.getEnd()));
10772   }
10773 
10774   // Check if the destination is an array (rather than a pointer to an array).
10775   QualType DstTy = DstArg->getType();
10776   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10777                                                                     Context);
10778   if (!isKnownSizeArray) {
10779     if (PatternType == 1)
10780       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10781     else
10782       Diag(SL, diag::warn_strncat_src_size) << SR;
10783     return;
10784   }
10785 
10786   if (PatternType == 1)
10787     Diag(SL, diag::warn_strncat_large_size) << SR;
10788   else
10789     Diag(SL, diag::warn_strncat_src_size) << SR;
10790 
10791   SmallString<128> sizeString;
10792   llvm::raw_svector_ostream OS(sizeString);
10793   OS << "sizeof(";
10794   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10795   OS << ") - ";
10796   OS << "strlen(";
10797   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10798   OS << ") - 1";
10799 
10800   Diag(SL, diag::note_strncat_wrong_size)
10801     << FixItHint::CreateReplacement(SR, OS.str());
10802 }
10803 
10804 namespace {
10805 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10806                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10807   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10808     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10809         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10810     return;
10811   }
10812 }
10813 
10814 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10815                                  const UnaryOperator *UnaryExpr) {
10816   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10817     const Decl *D = Lvalue->getDecl();
10818     if (isa<DeclaratorDecl>(D))
10819       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10820         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10821   }
10822 
10823   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10824     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10825                                       Lvalue->getMemberDecl());
10826 }
10827 
10828 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10829                             const UnaryOperator *UnaryExpr) {
10830   const auto *Lambda = dyn_cast<LambdaExpr>(
10831       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10832   if (!Lambda)
10833     return;
10834 
10835   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10836       << CalleeName << 2 /*object: lambda expression*/;
10837 }
10838 
10839 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10840                                   const DeclRefExpr *Lvalue) {
10841   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10842   if (Var == nullptr)
10843     return;
10844 
10845   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10846       << CalleeName << 0 /*object: */ << Var;
10847 }
10848 
10849 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10850                             const CastExpr *Cast) {
10851   SmallString<128> SizeString;
10852   llvm::raw_svector_ostream OS(SizeString);
10853 
10854   clang::CastKind Kind = Cast->getCastKind();
10855   if (Kind == clang::CK_BitCast &&
10856       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10857     return;
10858   if (Kind == clang::CK_IntegralToPointer &&
10859       !isa<IntegerLiteral>(
10860           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10861     return;
10862 
10863   switch (Cast->getCastKind()) {
10864   case clang::CK_BitCast:
10865   case clang::CK_IntegralToPointer:
10866   case clang::CK_FunctionToPointerDecay:
10867     OS << '\'';
10868     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10869     OS << '\'';
10870     break;
10871   default:
10872     return;
10873   }
10874 
10875   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10876       << CalleeName << 0 /*object: */ << OS.str();
10877 }
10878 } // namespace
10879 
10880 /// Alerts the user that they are attempting to free a non-malloc'd object.
10881 void Sema::CheckFreeArguments(const CallExpr *E) {
10882   const std::string CalleeName =
10883       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10884 
10885   { // Prefer something that doesn't involve a cast to make things simpler.
10886     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10887     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10888       switch (UnaryExpr->getOpcode()) {
10889       case UnaryOperator::Opcode::UO_AddrOf:
10890         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10891       case UnaryOperator::Opcode::UO_Plus:
10892         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10893       default:
10894         break;
10895       }
10896 
10897     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10898       if (Lvalue->getType()->isArrayType())
10899         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10900 
10901     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10902       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10903           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10904       return;
10905     }
10906 
10907     if (isa<BlockExpr>(Arg)) {
10908       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10909           << CalleeName << 1 /*object: block*/;
10910       return;
10911     }
10912   }
10913   // Maybe the cast was important, check after the other cases.
10914   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10915     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10916 }
10917 
10918 void
10919 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10920                          SourceLocation ReturnLoc,
10921                          bool isObjCMethod,
10922                          const AttrVec *Attrs,
10923                          const FunctionDecl *FD) {
10924   // Check if the return value is null but should not be.
10925   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10926        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10927       CheckNonNullExpr(*this, RetValExp))
10928     Diag(ReturnLoc, diag::warn_null_ret)
10929       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10930 
10931   // C++11 [basic.stc.dynamic.allocation]p4:
10932   //   If an allocation function declared with a non-throwing
10933   //   exception-specification fails to allocate storage, it shall return
10934   //   a null pointer. Any other allocation function that fails to allocate
10935   //   storage shall indicate failure only by throwing an exception [...]
10936   if (FD) {
10937     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10938     if (Op == OO_New || Op == OO_Array_New) {
10939       const FunctionProtoType *Proto
10940         = FD->getType()->castAs<FunctionProtoType>();
10941       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10942           CheckNonNullExpr(*this, RetValExp))
10943         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10944           << FD << getLangOpts().CPlusPlus11;
10945     }
10946   }
10947 
10948   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10949   // here prevent the user from using a PPC MMA type as trailing return type.
10950   if (Context.getTargetInfo().getTriple().isPPC64())
10951     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10952 }
10953 
10954 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10955 
10956 /// Check for comparisons of floating point operands using != and ==.
10957 /// Issue a warning if these are no self-comparisons, as they are not likely
10958 /// to do what the programmer intended.
10959 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10960   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10961   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10962 
10963   // Special case: check for x == x (which is OK).
10964   // Do not emit warnings for such cases.
10965   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10966     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10967       if (DRL->getDecl() == DRR->getDecl())
10968         return;
10969 
10970   // Special case: check for comparisons against literals that can be exactly
10971   //  represented by APFloat.  In such cases, do not emit a warning.  This
10972   //  is a heuristic: often comparison against such literals are used to
10973   //  detect if a value in a variable has not changed.  This clearly can
10974   //  lead to false negatives.
10975   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10976     if (FLL->isExact())
10977       return;
10978   } else
10979     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10980       if (FLR->isExact())
10981         return;
10982 
10983   // Check for comparisons with builtin types.
10984   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10985     if (CL->getBuiltinCallee())
10986       return;
10987 
10988   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10989     if (CR->getBuiltinCallee())
10990       return;
10991 
10992   // Emit the diagnostic.
10993   Diag(Loc, diag::warn_floatingpoint_eq)
10994     << LHS->getSourceRange() << RHS->getSourceRange();
10995 }
10996 
10997 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10998 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10999 
11000 namespace {
11001 
11002 /// Structure recording the 'active' range of an integer-valued
11003 /// expression.
11004 struct IntRange {
11005   /// The number of bits active in the int. Note that this includes exactly one
11006   /// sign bit if !NonNegative.
11007   unsigned Width;
11008 
11009   /// True if the int is known not to have negative values. If so, all leading
11010   /// bits before Width are known zero, otherwise they are known to be the
11011   /// same as the MSB within Width.
11012   bool NonNegative;
11013 
11014   IntRange(unsigned Width, bool NonNegative)
11015       : Width(Width), NonNegative(NonNegative) {}
11016 
11017   /// Number of bits excluding the sign bit.
11018   unsigned valueBits() const {
11019     return NonNegative ? Width : Width - 1;
11020   }
11021 
11022   /// Returns the range of the bool type.
11023   static IntRange forBoolType() {
11024     return IntRange(1, true);
11025   }
11026 
11027   /// Returns the range of an opaque value of the given integral type.
11028   static IntRange forValueOfType(ASTContext &C, QualType T) {
11029     return forValueOfCanonicalType(C,
11030                           T->getCanonicalTypeInternal().getTypePtr());
11031   }
11032 
11033   /// Returns the range of an opaque value of a canonical integral type.
11034   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11035     assert(T->isCanonicalUnqualified());
11036 
11037     if (const VectorType *VT = dyn_cast<VectorType>(T))
11038       T = VT->getElementType().getTypePtr();
11039     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11040       T = CT->getElementType().getTypePtr();
11041     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11042       T = AT->getValueType().getTypePtr();
11043 
11044     if (!C.getLangOpts().CPlusPlus) {
11045       // For enum types in C code, use the underlying datatype.
11046       if (const EnumType *ET = dyn_cast<EnumType>(T))
11047         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11048     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11049       // For enum types in C++, use the known bit width of the enumerators.
11050       EnumDecl *Enum = ET->getDecl();
11051       // In C++11, enums can have a fixed underlying type. Use this type to
11052       // compute the range.
11053       if (Enum->isFixed()) {
11054         return IntRange(C.getIntWidth(QualType(T, 0)),
11055                         !ET->isSignedIntegerOrEnumerationType());
11056       }
11057 
11058       unsigned NumPositive = Enum->getNumPositiveBits();
11059       unsigned NumNegative = Enum->getNumNegativeBits();
11060 
11061       if (NumNegative == 0)
11062         return IntRange(NumPositive, true/*NonNegative*/);
11063       else
11064         return IntRange(std::max(NumPositive + 1, NumNegative),
11065                         false/*NonNegative*/);
11066     }
11067 
11068     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11069       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11070 
11071     const BuiltinType *BT = cast<BuiltinType>(T);
11072     assert(BT->isInteger());
11073 
11074     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11075   }
11076 
11077   /// Returns the "target" range of a canonical integral type, i.e.
11078   /// the range of values expressible in the type.
11079   ///
11080   /// This matches forValueOfCanonicalType except that enums have the
11081   /// full range of their type, not the range of their enumerators.
11082   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11083     assert(T->isCanonicalUnqualified());
11084 
11085     if (const VectorType *VT = dyn_cast<VectorType>(T))
11086       T = VT->getElementType().getTypePtr();
11087     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11088       T = CT->getElementType().getTypePtr();
11089     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11090       T = AT->getValueType().getTypePtr();
11091     if (const EnumType *ET = dyn_cast<EnumType>(T))
11092       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11093 
11094     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11095       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11096 
11097     const BuiltinType *BT = cast<BuiltinType>(T);
11098     assert(BT->isInteger());
11099 
11100     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11101   }
11102 
11103   /// Returns the supremum of two ranges: i.e. their conservative merge.
11104   static IntRange join(IntRange L, IntRange R) {
11105     bool Unsigned = L.NonNegative && R.NonNegative;
11106     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11107                     L.NonNegative && R.NonNegative);
11108   }
11109 
11110   /// Return the range of a bitwise-AND of the two ranges.
11111   static IntRange bit_and(IntRange L, IntRange R) {
11112     unsigned Bits = std::max(L.Width, R.Width);
11113     bool NonNegative = false;
11114     if (L.NonNegative) {
11115       Bits = std::min(Bits, L.Width);
11116       NonNegative = true;
11117     }
11118     if (R.NonNegative) {
11119       Bits = std::min(Bits, R.Width);
11120       NonNegative = true;
11121     }
11122     return IntRange(Bits, NonNegative);
11123   }
11124 
11125   /// Return the range of a sum of the two ranges.
11126   static IntRange sum(IntRange L, IntRange R) {
11127     bool Unsigned = L.NonNegative && R.NonNegative;
11128     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11129                     Unsigned);
11130   }
11131 
11132   /// Return the range of a difference of the two ranges.
11133   static IntRange difference(IntRange L, IntRange R) {
11134     // We need a 1-bit-wider range if:
11135     //   1) LHS can be negative: least value can be reduced.
11136     //   2) RHS can be negative: greatest value can be increased.
11137     bool CanWiden = !L.NonNegative || !R.NonNegative;
11138     bool Unsigned = L.NonNegative && R.Width == 0;
11139     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11140                         !Unsigned,
11141                     Unsigned);
11142   }
11143 
11144   /// Return the range of a product of the two ranges.
11145   static IntRange product(IntRange L, IntRange R) {
11146     // If both LHS and RHS can be negative, we can form
11147     //   -2^L * -2^R = 2^(L + R)
11148     // which requires L + R + 1 value bits to represent.
11149     bool CanWiden = !L.NonNegative && !R.NonNegative;
11150     bool Unsigned = L.NonNegative && R.NonNegative;
11151     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11152                     Unsigned);
11153   }
11154 
11155   /// Return the range of a remainder operation between the two ranges.
11156   static IntRange rem(IntRange L, IntRange R) {
11157     // The result of a remainder can't be larger than the result of
11158     // either side. The sign of the result is the sign of the LHS.
11159     bool Unsigned = L.NonNegative;
11160     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11161                     Unsigned);
11162   }
11163 };
11164 
11165 } // namespace
11166 
11167 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11168                               unsigned MaxWidth) {
11169   if (value.isSigned() && value.isNegative())
11170     return IntRange(value.getMinSignedBits(), false);
11171 
11172   if (value.getBitWidth() > MaxWidth)
11173     value = value.trunc(MaxWidth);
11174 
11175   // isNonNegative() just checks the sign bit without considering
11176   // signedness.
11177   return IntRange(value.getActiveBits(), true);
11178 }
11179 
11180 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11181                               unsigned MaxWidth) {
11182   if (result.isInt())
11183     return GetValueRange(C, result.getInt(), MaxWidth);
11184 
11185   if (result.isVector()) {
11186     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11187     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11188       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11189       R = IntRange::join(R, El);
11190     }
11191     return R;
11192   }
11193 
11194   if (result.isComplexInt()) {
11195     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11196     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11197     return IntRange::join(R, I);
11198   }
11199 
11200   // This can happen with lossless casts to intptr_t of "based" lvalues.
11201   // Assume it might use arbitrary bits.
11202   // FIXME: The only reason we need to pass the type in here is to get
11203   // the sign right on this one case.  It would be nice if APValue
11204   // preserved this.
11205   assert(result.isLValue() || result.isAddrLabelDiff());
11206   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11207 }
11208 
11209 static QualType GetExprType(const Expr *E) {
11210   QualType Ty = E->getType();
11211   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11212     Ty = AtomicRHS->getValueType();
11213   return Ty;
11214 }
11215 
11216 /// Pseudo-evaluate the given integer expression, estimating the
11217 /// range of values it might take.
11218 ///
11219 /// \param MaxWidth The width to which the value will be truncated.
11220 /// \param Approximate If \c true, return a likely range for the result: in
11221 ///        particular, assume that aritmetic on narrower types doesn't leave
11222 ///        those types. If \c false, return a range including all possible
11223 ///        result values.
11224 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11225                              bool InConstantContext, bool Approximate) {
11226   E = E->IgnoreParens();
11227 
11228   // Try a full evaluation first.
11229   Expr::EvalResult result;
11230   if (E->EvaluateAsRValue(result, C, InConstantContext))
11231     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11232 
11233   // I think we only want to look through implicit casts here; if the
11234   // user has an explicit widening cast, we should treat the value as
11235   // being of the new, wider type.
11236   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11237     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11238       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11239                           Approximate);
11240 
11241     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11242 
11243     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11244                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11245 
11246     // Assume that non-integer casts can span the full range of the type.
11247     if (!isIntegerCast)
11248       return OutputTypeRange;
11249 
11250     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11251                                      std::min(MaxWidth, OutputTypeRange.Width),
11252                                      InConstantContext, Approximate);
11253 
11254     // Bail out if the subexpr's range is as wide as the cast type.
11255     if (SubRange.Width >= OutputTypeRange.Width)
11256       return OutputTypeRange;
11257 
11258     // Otherwise, we take the smaller width, and we're non-negative if
11259     // either the output type or the subexpr is.
11260     return IntRange(SubRange.Width,
11261                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11262   }
11263 
11264   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11265     // If we can fold the condition, just take that operand.
11266     bool CondResult;
11267     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11268       return GetExprRange(C,
11269                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11270                           MaxWidth, InConstantContext, Approximate);
11271 
11272     // Otherwise, conservatively merge.
11273     // GetExprRange requires an integer expression, but a throw expression
11274     // results in a void type.
11275     Expr *E = CO->getTrueExpr();
11276     IntRange L = E->getType()->isVoidType()
11277                      ? IntRange{0, true}
11278                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11279     E = CO->getFalseExpr();
11280     IntRange R = E->getType()->isVoidType()
11281                      ? IntRange{0, true}
11282                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11283     return IntRange::join(L, R);
11284   }
11285 
11286   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11287     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11288 
11289     switch (BO->getOpcode()) {
11290     case BO_Cmp:
11291       llvm_unreachable("builtin <=> should have class type");
11292 
11293     // Boolean-valued operations are single-bit and positive.
11294     case BO_LAnd:
11295     case BO_LOr:
11296     case BO_LT:
11297     case BO_GT:
11298     case BO_LE:
11299     case BO_GE:
11300     case BO_EQ:
11301     case BO_NE:
11302       return IntRange::forBoolType();
11303 
11304     // The type of the assignments is the type of the LHS, so the RHS
11305     // is not necessarily the same type.
11306     case BO_MulAssign:
11307     case BO_DivAssign:
11308     case BO_RemAssign:
11309     case BO_AddAssign:
11310     case BO_SubAssign:
11311     case BO_XorAssign:
11312     case BO_OrAssign:
11313       // TODO: bitfields?
11314       return IntRange::forValueOfType(C, GetExprType(E));
11315 
11316     // Simple assignments just pass through the RHS, which will have
11317     // been coerced to the LHS type.
11318     case BO_Assign:
11319       // TODO: bitfields?
11320       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11321                           Approximate);
11322 
11323     // Operations with opaque sources are black-listed.
11324     case BO_PtrMemD:
11325     case BO_PtrMemI:
11326       return IntRange::forValueOfType(C, GetExprType(E));
11327 
11328     // Bitwise-and uses the *infinum* of the two source ranges.
11329     case BO_And:
11330     case BO_AndAssign:
11331       Combine = IntRange::bit_and;
11332       break;
11333 
11334     // Left shift gets black-listed based on a judgement call.
11335     case BO_Shl:
11336       // ...except that we want to treat '1 << (blah)' as logically
11337       // positive.  It's an important idiom.
11338       if (IntegerLiteral *I
11339             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11340         if (I->getValue() == 1) {
11341           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11342           return IntRange(R.Width, /*NonNegative*/ true);
11343         }
11344       }
11345       LLVM_FALLTHROUGH;
11346 
11347     case BO_ShlAssign:
11348       return IntRange::forValueOfType(C, GetExprType(E));
11349 
11350     // Right shift by a constant can narrow its left argument.
11351     case BO_Shr:
11352     case BO_ShrAssign: {
11353       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11354                                 Approximate);
11355 
11356       // If the shift amount is a positive constant, drop the width by
11357       // that much.
11358       if (Optional<llvm::APSInt> shift =
11359               BO->getRHS()->getIntegerConstantExpr(C)) {
11360         if (shift->isNonNegative()) {
11361           unsigned zext = shift->getZExtValue();
11362           if (zext >= L.Width)
11363             L.Width = (L.NonNegative ? 0 : 1);
11364           else
11365             L.Width -= zext;
11366         }
11367       }
11368 
11369       return L;
11370     }
11371 
11372     // Comma acts as its right operand.
11373     case BO_Comma:
11374       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11375                           Approximate);
11376 
11377     case BO_Add:
11378       if (!Approximate)
11379         Combine = IntRange::sum;
11380       break;
11381 
11382     case BO_Sub:
11383       if (BO->getLHS()->getType()->isPointerType())
11384         return IntRange::forValueOfType(C, GetExprType(E));
11385       if (!Approximate)
11386         Combine = IntRange::difference;
11387       break;
11388 
11389     case BO_Mul:
11390       if (!Approximate)
11391         Combine = IntRange::product;
11392       break;
11393 
11394     // The width of a division result is mostly determined by the size
11395     // of the LHS.
11396     case BO_Div: {
11397       // Don't 'pre-truncate' the operands.
11398       unsigned opWidth = C.getIntWidth(GetExprType(E));
11399       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11400                                 Approximate);
11401 
11402       // If the divisor is constant, use that.
11403       if (Optional<llvm::APSInt> divisor =
11404               BO->getRHS()->getIntegerConstantExpr(C)) {
11405         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11406         if (log2 >= L.Width)
11407           L.Width = (L.NonNegative ? 0 : 1);
11408         else
11409           L.Width = std::min(L.Width - log2, MaxWidth);
11410         return L;
11411       }
11412 
11413       // Otherwise, just use the LHS's width.
11414       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11415       // could be -1.
11416       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11417                                 Approximate);
11418       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11419     }
11420 
11421     case BO_Rem:
11422       Combine = IntRange::rem;
11423       break;
11424 
11425     // The default behavior is okay for these.
11426     case BO_Xor:
11427     case BO_Or:
11428       break;
11429     }
11430 
11431     // Combine the two ranges, but limit the result to the type in which we
11432     // performed the computation.
11433     QualType T = GetExprType(E);
11434     unsigned opWidth = C.getIntWidth(T);
11435     IntRange L =
11436         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11437     IntRange R =
11438         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11439     IntRange C = Combine(L, R);
11440     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11441     C.Width = std::min(C.Width, MaxWidth);
11442     return C;
11443   }
11444 
11445   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11446     switch (UO->getOpcode()) {
11447     // Boolean-valued operations are white-listed.
11448     case UO_LNot:
11449       return IntRange::forBoolType();
11450 
11451     // Operations with opaque sources are black-listed.
11452     case UO_Deref:
11453     case UO_AddrOf: // should be impossible
11454       return IntRange::forValueOfType(C, GetExprType(E));
11455 
11456     default:
11457       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11458                           Approximate);
11459     }
11460   }
11461 
11462   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11463     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11464                         Approximate);
11465 
11466   if (const auto *BitField = E->getSourceBitField())
11467     return IntRange(BitField->getBitWidthValue(C),
11468                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11469 
11470   return IntRange::forValueOfType(C, GetExprType(E));
11471 }
11472 
11473 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11474                              bool InConstantContext, bool Approximate) {
11475   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11476                       Approximate);
11477 }
11478 
11479 /// Checks whether the given value, which currently has the given
11480 /// source semantics, has the same value when coerced through the
11481 /// target semantics.
11482 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11483                                  const llvm::fltSemantics &Src,
11484                                  const llvm::fltSemantics &Tgt) {
11485   llvm::APFloat truncated = value;
11486 
11487   bool ignored;
11488   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11489   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11490 
11491   return truncated.bitwiseIsEqual(value);
11492 }
11493 
11494 /// Checks whether the given value, which currently has the given
11495 /// source semantics, has the same value when coerced through the
11496 /// target semantics.
11497 ///
11498 /// The value might be a vector of floats (or a complex number).
11499 static bool IsSameFloatAfterCast(const APValue &value,
11500                                  const llvm::fltSemantics &Src,
11501                                  const llvm::fltSemantics &Tgt) {
11502   if (value.isFloat())
11503     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11504 
11505   if (value.isVector()) {
11506     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11507       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11508         return false;
11509     return true;
11510   }
11511 
11512   assert(value.isComplexFloat());
11513   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11514           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11515 }
11516 
11517 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11518                                        bool IsListInit = false);
11519 
11520 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11521   // Suppress cases where we are comparing against an enum constant.
11522   if (const DeclRefExpr *DR =
11523       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11524     if (isa<EnumConstantDecl>(DR->getDecl()))
11525       return true;
11526 
11527   // Suppress cases where the value is expanded from a macro, unless that macro
11528   // is how a language represents a boolean literal. This is the case in both C
11529   // and Objective-C.
11530   SourceLocation BeginLoc = E->getBeginLoc();
11531   if (BeginLoc.isMacroID()) {
11532     StringRef MacroName = Lexer::getImmediateMacroName(
11533         BeginLoc, S.getSourceManager(), S.getLangOpts());
11534     return MacroName != "YES" && MacroName != "NO" &&
11535            MacroName != "true" && MacroName != "false";
11536   }
11537 
11538   return false;
11539 }
11540 
11541 static bool isKnownToHaveUnsignedValue(Expr *E) {
11542   return E->getType()->isIntegerType() &&
11543          (!E->getType()->isSignedIntegerType() ||
11544           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11545 }
11546 
11547 namespace {
11548 /// The promoted range of values of a type. In general this has the
11549 /// following structure:
11550 ///
11551 ///     |-----------| . . . |-----------|
11552 ///     ^           ^       ^           ^
11553 ///    Min       HoleMin  HoleMax      Max
11554 ///
11555 /// ... where there is only a hole if a signed type is promoted to unsigned
11556 /// (in which case Min and Max are the smallest and largest representable
11557 /// values).
11558 struct PromotedRange {
11559   // Min, or HoleMax if there is a hole.
11560   llvm::APSInt PromotedMin;
11561   // Max, or HoleMin if there is a hole.
11562   llvm::APSInt PromotedMax;
11563 
11564   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11565     if (R.Width == 0)
11566       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11567     else if (R.Width >= BitWidth && !Unsigned) {
11568       // Promotion made the type *narrower*. This happens when promoting
11569       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11570       // Treat all values of 'signed int' as being in range for now.
11571       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11572       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11573     } else {
11574       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11575                         .extOrTrunc(BitWidth);
11576       PromotedMin.setIsUnsigned(Unsigned);
11577 
11578       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11579                         .extOrTrunc(BitWidth);
11580       PromotedMax.setIsUnsigned(Unsigned);
11581     }
11582   }
11583 
11584   // Determine whether this range is contiguous (has no hole).
11585   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11586 
11587   // Where a constant value is within the range.
11588   enum ComparisonResult {
11589     LT = 0x1,
11590     LE = 0x2,
11591     GT = 0x4,
11592     GE = 0x8,
11593     EQ = 0x10,
11594     NE = 0x20,
11595     InRangeFlag = 0x40,
11596 
11597     Less = LE | LT | NE,
11598     Min = LE | InRangeFlag,
11599     InRange = InRangeFlag,
11600     Max = GE | InRangeFlag,
11601     Greater = GE | GT | NE,
11602 
11603     OnlyValue = LE | GE | EQ | InRangeFlag,
11604     InHole = NE
11605   };
11606 
11607   ComparisonResult compare(const llvm::APSInt &Value) const {
11608     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11609            Value.isUnsigned() == PromotedMin.isUnsigned());
11610     if (!isContiguous()) {
11611       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11612       if (Value.isMinValue()) return Min;
11613       if (Value.isMaxValue()) return Max;
11614       if (Value >= PromotedMin) return InRange;
11615       if (Value <= PromotedMax) return InRange;
11616       return InHole;
11617     }
11618 
11619     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11620     case -1: return Less;
11621     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11622     case 1:
11623       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11624       case -1: return InRange;
11625       case 0: return Max;
11626       case 1: return Greater;
11627       }
11628     }
11629 
11630     llvm_unreachable("impossible compare result");
11631   }
11632 
11633   static llvm::Optional<StringRef>
11634   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11635     if (Op == BO_Cmp) {
11636       ComparisonResult LTFlag = LT, GTFlag = GT;
11637       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11638 
11639       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11640       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11641       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11642       return llvm::None;
11643     }
11644 
11645     ComparisonResult TrueFlag, FalseFlag;
11646     if (Op == BO_EQ) {
11647       TrueFlag = EQ;
11648       FalseFlag = NE;
11649     } else if (Op == BO_NE) {
11650       TrueFlag = NE;
11651       FalseFlag = EQ;
11652     } else {
11653       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11654         TrueFlag = LT;
11655         FalseFlag = GE;
11656       } else {
11657         TrueFlag = GT;
11658         FalseFlag = LE;
11659       }
11660       if (Op == BO_GE || Op == BO_LE)
11661         std::swap(TrueFlag, FalseFlag);
11662     }
11663     if (R & TrueFlag)
11664       return StringRef("true");
11665     if (R & FalseFlag)
11666       return StringRef("false");
11667     return llvm::None;
11668   }
11669 };
11670 }
11671 
11672 static bool HasEnumType(Expr *E) {
11673   // Strip off implicit integral promotions.
11674   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11675     if (ICE->getCastKind() != CK_IntegralCast &&
11676         ICE->getCastKind() != CK_NoOp)
11677       break;
11678     E = ICE->getSubExpr();
11679   }
11680 
11681   return E->getType()->isEnumeralType();
11682 }
11683 
11684 static int classifyConstantValue(Expr *Constant) {
11685   // The values of this enumeration are used in the diagnostics
11686   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11687   enum ConstantValueKind {
11688     Miscellaneous = 0,
11689     LiteralTrue,
11690     LiteralFalse
11691   };
11692   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11693     return BL->getValue() ? ConstantValueKind::LiteralTrue
11694                           : ConstantValueKind::LiteralFalse;
11695   return ConstantValueKind::Miscellaneous;
11696 }
11697 
11698 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11699                                         Expr *Constant, Expr *Other,
11700                                         const llvm::APSInt &Value,
11701                                         bool RhsConstant) {
11702   if (S.inTemplateInstantiation())
11703     return false;
11704 
11705   Expr *OriginalOther = Other;
11706 
11707   Constant = Constant->IgnoreParenImpCasts();
11708   Other = Other->IgnoreParenImpCasts();
11709 
11710   // Suppress warnings on tautological comparisons between values of the same
11711   // enumeration type. There are only two ways we could warn on this:
11712   //  - If the constant is outside the range of representable values of
11713   //    the enumeration. In such a case, we should warn about the cast
11714   //    to enumeration type, not about the comparison.
11715   //  - If the constant is the maximum / minimum in-range value. For an
11716   //    enumeratin type, such comparisons can be meaningful and useful.
11717   if (Constant->getType()->isEnumeralType() &&
11718       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11719     return false;
11720 
11721   IntRange OtherValueRange = GetExprRange(
11722       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11723 
11724   QualType OtherT = Other->getType();
11725   if (const auto *AT = OtherT->getAs<AtomicType>())
11726     OtherT = AT->getValueType();
11727   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11728 
11729   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11730   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11731   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11732                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11733                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11734 
11735   // Whether we're treating Other as being a bool because of the form of
11736   // expression despite it having another type (typically 'int' in C).
11737   bool OtherIsBooleanDespiteType =
11738       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11739   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11740     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11741 
11742   // Check if all values in the range of possible values of this expression
11743   // lead to the same comparison outcome.
11744   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11745                                         Value.isUnsigned());
11746   auto Cmp = OtherPromotedValueRange.compare(Value);
11747   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11748   if (!Result)
11749     return false;
11750 
11751   // Also consider the range determined by the type alone. This allows us to
11752   // classify the warning under the proper diagnostic group.
11753   bool TautologicalTypeCompare = false;
11754   {
11755     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11756                                          Value.isUnsigned());
11757     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11758     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11759                                                        RhsConstant)) {
11760       TautologicalTypeCompare = true;
11761       Cmp = TypeCmp;
11762       Result = TypeResult;
11763     }
11764   }
11765 
11766   // Don't warn if the non-constant operand actually always evaluates to the
11767   // same value.
11768   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11769     return false;
11770 
11771   // Suppress the diagnostic for an in-range comparison if the constant comes
11772   // from a macro or enumerator. We don't want to diagnose
11773   //
11774   //   some_long_value <= INT_MAX
11775   //
11776   // when sizeof(int) == sizeof(long).
11777   bool InRange = Cmp & PromotedRange::InRangeFlag;
11778   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11779     return false;
11780 
11781   // A comparison of an unsigned bit-field against 0 is really a type problem,
11782   // even though at the type level the bit-field might promote to 'signed int'.
11783   if (Other->refersToBitField() && InRange && Value == 0 &&
11784       Other->getType()->isUnsignedIntegerOrEnumerationType())
11785     TautologicalTypeCompare = true;
11786 
11787   // If this is a comparison to an enum constant, include that
11788   // constant in the diagnostic.
11789   const EnumConstantDecl *ED = nullptr;
11790   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11791     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11792 
11793   // Should be enough for uint128 (39 decimal digits)
11794   SmallString<64> PrettySourceValue;
11795   llvm::raw_svector_ostream OS(PrettySourceValue);
11796   if (ED) {
11797     OS << '\'' << *ED << "' (" << Value << ")";
11798   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11799                Constant->IgnoreParenImpCasts())) {
11800     OS << (BL->getValue() ? "YES" : "NO");
11801   } else {
11802     OS << Value;
11803   }
11804 
11805   if (!TautologicalTypeCompare) {
11806     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11807         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11808         << E->getOpcodeStr() << OS.str() << *Result
11809         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11810     return true;
11811   }
11812 
11813   if (IsObjCSignedCharBool) {
11814     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11815                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11816                               << OS.str() << *Result);
11817     return true;
11818   }
11819 
11820   // FIXME: We use a somewhat different formatting for the in-range cases and
11821   // cases involving boolean values for historical reasons. We should pick a
11822   // consistent way of presenting these diagnostics.
11823   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11824 
11825     S.DiagRuntimeBehavior(
11826         E->getOperatorLoc(), E,
11827         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11828                          : diag::warn_tautological_bool_compare)
11829             << OS.str() << classifyConstantValue(Constant) << OtherT
11830             << OtherIsBooleanDespiteType << *Result
11831             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11832   } else {
11833     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11834     unsigned Diag =
11835         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11836             ? (HasEnumType(OriginalOther)
11837                    ? diag::warn_unsigned_enum_always_true_comparison
11838                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11839                               : diag::warn_unsigned_always_true_comparison)
11840             : diag::warn_tautological_constant_compare;
11841 
11842     S.Diag(E->getOperatorLoc(), Diag)
11843         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11844         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11845   }
11846 
11847   return true;
11848 }
11849 
11850 /// Analyze the operands of the given comparison.  Implements the
11851 /// fallback case from AnalyzeComparison.
11852 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11853   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11854   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11855 }
11856 
11857 /// Implements -Wsign-compare.
11858 ///
11859 /// \param E the binary operator to check for warnings
11860 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11861   // The type the comparison is being performed in.
11862   QualType T = E->getLHS()->getType();
11863 
11864   // Only analyze comparison operators where both sides have been converted to
11865   // the same type.
11866   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11867     return AnalyzeImpConvsInComparison(S, E);
11868 
11869   // Don't analyze value-dependent comparisons directly.
11870   if (E->isValueDependent())
11871     return AnalyzeImpConvsInComparison(S, E);
11872 
11873   Expr *LHS = E->getLHS();
11874   Expr *RHS = E->getRHS();
11875 
11876   if (T->isIntegralType(S.Context)) {
11877     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11878     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11879 
11880     // We don't care about expressions whose result is a constant.
11881     if (RHSValue && LHSValue)
11882       return AnalyzeImpConvsInComparison(S, E);
11883 
11884     // We only care about expressions where just one side is literal
11885     if ((bool)RHSValue ^ (bool)LHSValue) {
11886       // Is the constant on the RHS or LHS?
11887       const bool RhsConstant = (bool)RHSValue;
11888       Expr *Const = RhsConstant ? RHS : LHS;
11889       Expr *Other = RhsConstant ? LHS : RHS;
11890       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11891 
11892       // Check whether an integer constant comparison results in a value
11893       // of 'true' or 'false'.
11894       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11895         return AnalyzeImpConvsInComparison(S, E);
11896     }
11897   }
11898 
11899   if (!T->hasUnsignedIntegerRepresentation()) {
11900     // We don't do anything special if this isn't an unsigned integral
11901     // comparison:  we're only interested in integral comparisons, and
11902     // signed comparisons only happen in cases we don't care to warn about.
11903     return AnalyzeImpConvsInComparison(S, E);
11904   }
11905 
11906   LHS = LHS->IgnoreParenImpCasts();
11907   RHS = RHS->IgnoreParenImpCasts();
11908 
11909   if (!S.getLangOpts().CPlusPlus) {
11910     // Avoid warning about comparison of integers with different signs when
11911     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11912     // the type of `E`.
11913     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11914       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11915     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11916       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11917   }
11918 
11919   // Check to see if one of the (unmodified) operands is of different
11920   // signedness.
11921   Expr *signedOperand, *unsignedOperand;
11922   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11923     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11924            "unsigned comparison between two signed integer expressions?");
11925     signedOperand = LHS;
11926     unsignedOperand = RHS;
11927   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11928     signedOperand = RHS;
11929     unsignedOperand = LHS;
11930   } else {
11931     return AnalyzeImpConvsInComparison(S, E);
11932   }
11933 
11934   // Otherwise, calculate the effective range of the signed operand.
11935   IntRange signedRange = GetExprRange(
11936       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11937 
11938   // Go ahead and analyze implicit conversions in the operands.  Note
11939   // that we skip the implicit conversions on both sides.
11940   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11941   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11942 
11943   // If the signed range is non-negative, -Wsign-compare won't fire.
11944   if (signedRange.NonNegative)
11945     return;
11946 
11947   // For (in)equality comparisons, if the unsigned operand is a
11948   // constant which cannot collide with a overflowed signed operand,
11949   // then reinterpreting the signed operand as unsigned will not
11950   // change the result of the comparison.
11951   if (E->isEqualityOp()) {
11952     unsigned comparisonWidth = S.Context.getIntWidth(T);
11953     IntRange unsignedRange =
11954         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11955                      /*Approximate*/ true);
11956 
11957     // We should never be unable to prove that the unsigned operand is
11958     // non-negative.
11959     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11960 
11961     if (unsignedRange.Width < comparisonWidth)
11962       return;
11963   }
11964 
11965   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11966                         S.PDiag(diag::warn_mixed_sign_comparison)
11967                             << LHS->getType() << RHS->getType()
11968                             << LHS->getSourceRange() << RHS->getSourceRange());
11969 }
11970 
11971 /// Analyzes an attempt to assign the given value to a bitfield.
11972 ///
11973 /// Returns true if there was something fishy about the attempt.
11974 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11975                                       SourceLocation InitLoc) {
11976   assert(Bitfield->isBitField());
11977   if (Bitfield->isInvalidDecl())
11978     return false;
11979 
11980   // White-list bool bitfields.
11981   QualType BitfieldType = Bitfield->getType();
11982   if (BitfieldType->isBooleanType())
11983      return false;
11984 
11985   if (BitfieldType->isEnumeralType()) {
11986     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11987     // If the underlying enum type was not explicitly specified as an unsigned
11988     // type and the enum contain only positive values, MSVC++ will cause an
11989     // inconsistency by storing this as a signed type.
11990     if (S.getLangOpts().CPlusPlus11 &&
11991         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11992         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11993         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11994       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11995           << BitfieldEnumDecl;
11996     }
11997   }
11998 
11999   if (Bitfield->getType()->isBooleanType())
12000     return false;
12001 
12002   // Ignore value- or type-dependent expressions.
12003   if (Bitfield->getBitWidth()->isValueDependent() ||
12004       Bitfield->getBitWidth()->isTypeDependent() ||
12005       Init->isValueDependent() ||
12006       Init->isTypeDependent())
12007     return false;
12008 
12009   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12010   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12011 
12012   Expr::EvalResult Result;
12013   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12014                                    Expr::SE_AllowSideEffects)) {
12015     // The RHS is not constant.  If the RHS has an enum type, make sure the
12016     // bitfield is wide enough to hold all the values of the enum without
12017     // truncation.
12018     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12019       EnumDecl *ED = EnumTy->getDecl();
12020       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12021 
12022       // Enum types are implicitly signed on Windows, so check if there are any
12023       // negative enumerators to see if the enum was intended to be signed or
12024       // not.
12025       bool SignedEnum = ED->getNumNegativeBits() > 0;
12026 
12027       // Check for surprising sign changes when assigning enum values to a
12028       // bitfield of different signedness.  If the bitfield is signed and we
12029       // have exactly the right number of bits to store this unsigned enum,
12030       // suggest changing the enum to an unsigned type. This typically happens
12031       // on Windows where unfixed enums always use an underlying type of 'int'.
12032       unsigned DiagID = 0;
12033       if (SignedEnum && !SignedBitfield) {
12034         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12035       } else if (SignedBitfield && !SignedEnum &&
12036                  ED->getNumPositiveBits() == FieldWidth) {
12037         DiagID = diag::warn_signed_bitfield_enum_conversion;
12038       }
12039 
12040       if (DiagID) {
12041         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12042         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12043         SourceRange TypeRange =
12044             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12045         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12046             << SignedEnum << TypeRange;
12047       }
12048 
12049       // Compute the required bitwidth. If the enum has negative values, we need
12050       // one more bit than the normal number of positive bits to represent the
12051       // sign bit.
12052       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12053                                                   ED->getNumNegativeBits())
12054                                        : ED->getNumPositiveBits();
12055 
12056       // Check the bitwidth.
12057       if (BitsNeeded > FieldWidth) {
12058         Expr *WidthExpr = Bitfield->getBitWidth();
12059         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12060             << Bitfield << ED;
12061         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12062             << BitsNeeded << ED << WidthExpr->getSourceRange();
12063       }
12064     }
12065 
12066     return false;
12067   }
12068 
12069   llvm::APSInt Value = Result.Val.getInt();
12070 
12071   unsigned OriginalWidth = Value.getBitWidth();
12072 
12073   if (!Value.isSigned() || Value.isNegative())
12074     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12075       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12076         OriginalWidth = Value.getMinSignedBits();
12077 
12078   if (OriginalWidth <= FieldWidth)
12079     return false;
12080 
12081   // Compute the value which the bitfield will contain.
12082   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12083   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12084 
12085   // Check whether the stored value is equal to the original value.
12086   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12087   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12088     return false;
12089 
12090   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12091   // therefore don't strictly fit into a signed bitfield of width 1.
12092   if (FieldWidth == 1 && Value == 1)
12093     return false;
12094 
12095   std::string PrettyValue = toString(Value, 10);
12096   std::string PrettyTrunc = toString(TruncatedValue, 10);
12097 
12098   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12099     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12100     << Init->getSourceRange();
12101 
12102   return true;
12103 }
12104 
12105 /// Analyze the given simple or compound assignment for warning-worthy
12106 /// operations.
12107 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12108   // Just recurse on the LHS.
12109   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12110 
12111   // We want to recurse on the RHS as normal unless we're assigning to
12112   // a bitfield.
12113   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12114     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12115                                   E->getOperatorLoc())) {
12116       // Recurse, ignoring any implicit conversions on the RHS.
12117       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12118                                         E->getOperatorLoc());
12119     }
12120   }
12121 
12122   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12123 
12124   // Diagnose implicitly sequentially-consistent atomic assignment.
12125   if (E->getLHS()->getType()->isAtomicType())
12126     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12127 }
12128 
12129 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12130 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12131                             SourceLocation CContext, unsigned diag,
12132                             bool pruneControlFlow = false) {
12133   if (pruneControlFlow) {
12134     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12135                           S.PDiag(diag)
12136                               << SourceType << T << E->getSourceRange()
12137                               << SourceRange(CContext));
12138     return;
12139   }
12140   S.Diag(E->getExprLoc(), diag)
12141     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12142 }
12143 
12144 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12145 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12146                             SourceLocation CContext,
12147                             unsigned diag, bool pruneControlFlow = false) {
12148   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12149 }
12150 
12151 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12152   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12153       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12154 }
12155 
12156 static void adornObjCBoolConversionDiagWithTernaryFixit(
12157     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12158   Expr *Ignored = SourceExpr->IgnoreImplicit();
12159   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12160     Ignored = OVE->getSourceExpr();
12161   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12162                      isa<BinaryOperator>(Ignored) ||
12163                      isa<CXXOperatorCallExpr>(Ignored);
12164   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12165   if (NeedsParens)
12166     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12167             << FixItHint::CreateInsertion(EndLoc, ")");
12168   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12169 }
12170 
12171 /// Diagnose an implicit cast from a floating point value to an integer value.
12172 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12173                                     SourceLocation CContext) {
12174   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12175   const bool PruneWarnings = S.inTemplateInstantiation();
12176 
12177   Expr *InnerE = E->IgnoreParenImpCasts();
12178   // We also want to warn on, e.g., "int i = -1.234"
12179   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12180     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12181       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12182 
12183   const bool IsLiteral =
12184       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12185 
12186   llvm::APFloat Value(0.0);
12187   bool IsConstant =
12188     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12189   if (!IsConstant) {
12190     if (isObjCSignedCharBool(S, T)) {
12191       return adornObjCBoolConversionDiagWithTernaryFixit(
12192           S, E,
12193           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12194               << E->getType());
12195     }
12196 
12197     return DiagnoseImpCast(S, E, T, CContext,
12198                            diag::warn_impcast_float_integer, PruneWarnings);
12199   }
12200 
12201   bool isExact = false;
12202 
12203   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12204                             T->hasUnsignedIntegerRepresentation());
12205   llvm::APFloat::opStatus Result = Value.convertToInteger(
12206       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12207 
12208   // FIXME: Force the precision of the source value down so we don't print
12209   // digits which are usually useless (we don't really care here if we
12210   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12211   // would automatically print the shortest representation, but it's a bit
12212   // tricky to implement.
12213   SmallString<16> PrettySourceValue;
12214   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12215   precision = (precision * 59 + 195) / 196;
12216   Value.toString(PrettySourceValue, precision);
12217 
12218   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12219     return adornObjCBoolConversionDiagWithTernaryFixit(
12220         S, E,
12221         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12222             << PrettySourceValue);
12223   }
12224 
12225   if (Result == llvm::APFloat::opOK && isExact) {
12226     if (IsLiteral) return;
12227     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12228                            PruneWarnings);
12229   }
12230 
12231   // Conversion of a floating-point value to a non-bool integer where the
12232   // integral part cannot be represented by the integer type is undefined.
12233   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12234     return DiagnoseImpCast(
12235         S, E, T, CContext,
12236         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12237                   : diag::warn_impcast_float_to_integer_out_of_range,
12238         PruneWarnings);
12239 
12240   unsigned DiagID = 0;
12241   if (IsLiteral) {
12242     // Warn on floating point literal to integer.
12243     DiagID = diag::warn_impcast_literal_float_to_integer;
12244   } else if (IntegerValue == 0) {
12245     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12246       return DiagnoseImpCast(S, E, T, CContext,
12247                              diag::warn_impcast_float_integer, PruneWarnings);
12248     }
12249     // Warn on non-zero to zero conversion.
12250     DiagID = diag::warn_impcast_float_to_integer_zero;
12251   } else {
12252     if (IntegerValue.isUnsigned()) {
12253       if (!IntegerValue.isMaxValue()) {
12254         return DiagnoseImpCast(S, E, T, CContext,
12255                                diag::warn_impcast_float_integer, PruneWarnings);
12256       }
12257     } else {  // IntegerValue.isSigned()
12258       if (!IntegerValue.isMaxSignedValue() &&
12259           !IntegerValue.isMinSignedValue()) {
12260         return DiagnoseImpCast(S, E, T, CContext,
12261                                diag::warn_impcast_float_integer, PruneWarnings);
12262       }
12263     }
12264     // Warn on evaluatable floating point expression to integer conversion.
12265     DiagID = diag::warn_impcast_float_to_integer;
12266   }
12267 
12268   SmallString<16> PrettyTargetValue;
12269   if (IsBool)
12270     PrettyTargetValue = Value.isZero() ? "false" : "true";
12271   else
12272     IntegerValue.toString(PrettyTargetValue);
12273 
12274   if (PruneWarnings) {
12275     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12276                           S.PDiag(DiagID)
12277                               << E->getType() << T.getUnqualifiedType()
12278                               << PrettySourceValue << PrettyTargetValue
12279                               << E->getSourceRange() << SourceRange(CContext));
12280   } else {
12281     S.Diag(E->getExprLoc(), DiagID)
12282         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12283         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12284   }
12285 }
12286 
12287 /// Analyze the given compound assignment for the possible losing of
12288 /// floating-point precision.
12289 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12290   assert(isa<CompoundAssignOperator>(E) &&
12291          "Must be compound assignment operation");
12292   // Recurse on the LHS and RHS in here
12293   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12294   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12295 
12296   if (E->getLHS()->getType()->isAtomicType())
12297     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12298 
12299   // Now check the outermost expression
12300   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12301   const auto *RBT = cast<CompoundAssignOperator>(E)
12302                         ->getComputationResultType()
12303                         ->getAs<BuiltinType>();
12304 
12305   // The below checks assume source is floating point.
12306   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12307 
12308   // If source is floating point but target is an integer.
12309   if (ResultBT->isInteger())
12310     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12311                            E->getExprLoc(), diag::warn_impcast_float_integer);
12312 
12313   if (!ResultBT->isFloatingPoint())
12314     return;
12315 
12316   // If both source and target are floating points, warn about losing precision.
12317   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12318       QualType(ResultBT, 0), QualType(RBT, 0));
12319   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12320     // warn about dropping FP rank.
12321     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12322                     diag::warn_impcast_float_result_precision);
12323 }
12324 
12325 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12326                                       IntRange Range) {
12327   if (!Range.Width) return "0";
12328 
12329   llvm::APSInt ValueInRange = Value;
12330   ValueInRange.setIsSigned(!Range.NonNegative);
12331   ValueInRange = ValueInRange.trunc(Range.Width);
12332   return toString(ValueInRange, 10);
12333 }
12334 
12335 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12336   if (!isa<ImplicitCastExpr>(Ex))
12337     return false;
12338 
12339   Expr *InnerE = Ex->IgnoreParenImpCasts();
12340   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12341   const Type *Source =
12342     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12343   if (Target->isDependentType())
12344     return false;
12345 
12346   const BuiltinType *FloatCandidateBT =
12347     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12348   const Type *BoolCandidateType = ToBool ? Target : Source;
12349 
12350   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12351           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12352 }
12353 
12354 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12355                                              SourceLocation CC) {
12356   unsigned NumArgs = TheCall->getNumArgs();
12357   for (unsigned i = 0; i < NumArgs; ++i) {
12358     Expr *CurrA = TheCall->getArg(i);
12359     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12360       continue;
12361 
12362     bool IsSwapped = ((i > 0) &&
12363         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12364     IsSwapped |= ((i < (NumArgs - 1)) &&
12365         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12366     if (IsSwapped) {
12367       // Warn on this floating-point to bool conversion.
12368       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12369                       CurrA->getType(), CC,
12370                       diag::warn_impcast_floating_point_to_bool);
12371     }
12372   }
12373 }
12374 
12375 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12376                                    SourceLocation CC) {
12377   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12378                         E->getExprLoc()))
12379     return;
12380 
12381   // Don't warn on functions which have return type nullptr_t.
12382   if (isa<CallExpr>(E))
12383     return;
12384 
12385   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12386   const Expr::NullPointerConstantKind NullKind =
12387       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12388   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12389     return;
12390 
12391   // Return if target type is a safe conversion.
12392   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12393       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12394     return;
12395 
12396   SourceLocation Loc = E->getSourceRange().getBegin();
12397 
12398   // Venture through the macro stacks to get to the source of macro arguments.
12399   // The new location is a better location than the complete location that was
12400   // passed in.
12401   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12402   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12403 
12404   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12405   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12406     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12407         Loc, S.SourceMgr, S.getLangOpts());
12408     if (MacroName == "NULL")
12409       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12410   }
12411 
12412   // Only warn if the null and context location are in the same macro expansion.
12413   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12414     return;
12415 
12416   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12417       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12418       << FixItHint::CreateReplacement(Loc,
12419                                       S.getFixItZeroLiteralForType(T, Loc));
12420 }
12421 
12422 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12423                                   ObjCArrayLiteral *ArrayLiteral);
12424 
12425 static void
12426 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12427                            ObjCDictionaryLiteral *DictionaryLiteral);
12428 
12429 /// Check a single element within a collection literal against the
12430 /// target element type.
12431 static void checkObjCCollectionLiteralElement(Sema &S,
12432                                               QualType TargetElementType,
12433                                               Expr *Element,
12434                                               unsigned ElementKind) {
12435   // Skip a bitcast to 'id' or qualified 'id'.
12436   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12437     if (ICE->getCastKind() == CK_BitCast &&
12438         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12439       Element = ICE->getSubExpr();
12440   }
12441 
12442   QualType ElementType = Element->getType();
12443   ExprResult ElementResult(Element);
12444   if (ElementType->getAs<ObjCObjectPointerType>() &&
12445       S.CheckSingleAssignmentConstraints(TargetElementType,
12446                                          ElementResult,
12447                                          false, false)
12448         != Sema::Compatible) {
12449     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12450         << ElementType << ElementKind << TargetElementType
12451         << Element->getSourceRange();
12452   }
12453 
12454   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12455     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12456   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12457     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12458 }
12459 
12460 /// Check an Objective-C array literal being converted to the given
12461 /// target type.
12462 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12463                                   ObjCArrayLiteral *ArrayLiteral) {
12464   if (!S.NSArrayDecl)
12465     return;
12466 
12467   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12468   if (!TargetObjCPtr)
12469     return;
12470 
12471   if (TargetObjCPtr->isUnspecialized() ||
12472       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12473         != S.NSArrayDecl->getCanonicalDecl())
12474     return;
12475 
12476   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12477   if (TypeArgs.size() != 1)
12478     return;
12479 
12480   QualType TargetElementType = TypeArgs[0];
12481   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12482     checkObjCCollectionLiteralElement(S, TargetElementType,
12483                                       ArrayLiteral->getElement(I),
12484                                       0);
12485   }
12486 }
12487 
12488 /// Check an Objective-C dictionary literal being converted to the given
12489 /// target type.
12490 static void
12491 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12492                            ObjCDictionaryLiteral *DictionaryLiteral) {
12493   if (!S.NSDictionaryDecl)
12494     return;
12495 
12496   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12497   if (!TargetObjCPtr)
12498     return;
12499 
12500   if (TargetObjCPtr->isUnspecialized() ||
12501       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12502         != S.NSDictionaryDecl->getCanonicalDecl())
12503     return;
12504 
12505   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12506   if (TypeArgs.size() != 2)
12507     return;
12508 
12509   QualType TargetKeyType = TypeArgs[0];
12510   QualType TargetObjectType = TypeArgs[1];
12511   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12512     auto Element = DictionaryLiteral->getKeyValueElement(I);
12513     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12514     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12515   }
12516 }
12517 
12518 // Helper function to filter out cases for constant width constant conversion.
12519 // Don't warn on char array initialization or for non-decimal values.
12520 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12521                                           SourceLocation CC) {
12522   // If initializing from a constant, and the constant starts with '0',
12523   // then it is a binary, octal, or hexadecimal.  Allow these constants
12524   // to fill all the bits, even if there is a sign change.
12525   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12526     const char FirstLiteralCharacter =
12527         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12528     if (FirstLiteralCharacter == '0')
12529       return false;
12530   }
12531 
12532   // If the CC location points to a '{', and the type is char, then assume
12533   // assume it is an array initialization.
12534   if (CC.isValid() && T->isCharType()) {
12535     const char FirstContextCharacter =
12536         S.getSourceManager().getCharacterData(CC)[0];
12537     if (FirstContextCharacter == '{')
12538       return false;
12539   }
12540 
12541   return true;
12542 }
12543 
12544 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12545   const auto *IL = dyn_cast<IntegerLiteral>(E);
12546   if (!IL) {
12547     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12548       if (UO->getOpcode() == UO_Minus)
12549         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12550     }
12551   }
12552 
12553   return IL;
12554 }
12555 
12556 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12557   E = E->IgnoreParenImpCasts();
12558   SourceLocation ExprLoc = E->getExprLoc();
12559 
12560   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12561     BinaryOperator::Opcode Opc = BO->getOpcode();
12562     Expr::EvalResult Result;
12563     // Do not diagnose unsigned shifts.
12564     if (Opc == BO_Shl) {
12565       const auto *LHS = getIntegerLiteral(BO->getLHS());
12566       const auto *RHS = getIntegerLiteral(BO->getRHS());
12567       if (LHS && LHS->getValue() == 0)
12568         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12569       else if (!E->isValueDependent() && LHS && RHS &&
12570                RHS->getValue().isNonNegative() &&
12571                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12572         S.Diag(ExprLoc, diag::warn_left_shift_always)
12573             << (Result.Val.getInt() != 0);
12574       else if (E->getType()->isSignedIntegerType())
12575         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12576     }
12577   }
12578 
12579   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12580     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12581     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12582     if (!LHS || !RHS)
12583       return;
12584     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12585         (RHS->getValue() == 0 || RHS->getValue() == 1))
12586       // Do not diagnose common idioms.
12587       return;
12588     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12589       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12590   }
12591 }
12592 
12593 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12594                                     SourceLocation CC,
12595                                     bool *ICContext = nullptr,
12596                                     bool IsListInit = false) {
12597   if (E->isTypeDependent() || E->isValueDependent()) return;
12598 
12599   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12600   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12601   if (Source == Target) return;
12602   if (Target->isDependentType()) return;
12603 
12604   // If the conversion context location is invalid don't complain. We also
12605   // don't want to emit a warning if the issue occurs from the expansion of
12606   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12607   // delay this check as long as possible. Once we detect we are in that
12608   // scenario, we just return.
12609   if (CC.isInvalid())
12610     return;
12611 
12612   if (Source->isAtomicType())
12613     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12614 
12615   // Diagnose implicit casts to bool.
12616   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12617     if (isa<StringLiteral>(E))
12618       // Warn on string literal to bool.  Checks for string literals in logical
12619       // and expressions, for instance, assert(0 && "error here"), are
12620       // prevented by a check in AnalyzeImplicitConversions().
12621       return DiagnoseImpCast(S, E, T, CC,
12622                              diag::warn_impcast_string_literal_to_bool);
12623     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12624         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12625       // This covers the literal expressions that evaluate to Objective-C
12626       // objects.
12627       return DiagnoseImpCast(S, E, T, CC,
12628                              diag::warn_impcast_objective_c_literal_to_bool);
12629     }
12630     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12631       // Warn on pointer to bool conversion that is always true.
12632       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12633                                      SourceRange(CC));
12634     }
12635   }
12636 
12637   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12638   // is a typedef for signed char (macOS), then that constant value has to be 1
12639   // or 0.
12640   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12641     Expr::EvalResult Result;
12642     if (E->EvaluateAsInt(Result, S.getASTContext(),
12643                          Expr::SE_AllowSideEffects)) {
12644       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12645         adornObjCBoolConversionDiagWithTernaryFixit(
12646             S, E,
12647             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12648                 << toString(Result.Val.getInt(), 10));
12649       }
12650       return;
12651     }
12652   }
12653 
12654   // Check implicit casts from Objective-C collection literals to specialized
12655   // collection types, e.g., NSArray<NSString *> *.
12656   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12657     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12658   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12659     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12660 
12661   // Strip vector types.
12662   if (isa<VectorType>(Source)) {
12663     if (Target->isVLSTBuiltinType() &&
12664         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12665                                          QualType(Source, 0)) ||
12666          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12667                                             QualType(Source, 0))))
12668       return;
12669 
12670     if (!isa<VectorType>(Target)) {
12671       if (S.SourceMgr.isInSystemMacro(CC))
12672         return;
12673       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12674     }
12675 
12676     // If the vector cast is cast between two vectors of the same size, it is
12677     // a bitcast, not a conversion.
12678     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12679       return;
12680 
12681     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12682     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12683   }
12684   if (auto VecTy = dyn_cast<VectorType>(Target))
12685     Target = VecTy->getElementType().getTypePtr();
12686 
12687   // Strip complex types.
12688   if (isa<ComplexType>(Source)) {
12689     if (!isa<ComplexType>(Target)) {
12690       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12691         return;
12692 
12693       return DiagnoseImpCast(S, E, T, CC,
12694                              S.getLangOpts().CPlusPlus
12695                                  ? diag::err_impcast_complex_scalar
12696                                  : diag::warn_impcast_complex_scalar);
12697     }
12698 
12699     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12700     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12701   }
12702 
12703   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12704   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12705 
12706   // If the source is floating point...
12707   if (SourceBT && SourceBT->isFloatingPoint()) {
12708     // ...and the target is floating point...
12709     if (TargetBT && TargetBT->isFloatingPoint()) {
12710       // ...then warn if we're dropping FP rank.
12711 
12712       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12713           QualType(SourceBT, 0), QualType(TargetBT, 0));
12714       if (Order > 0) {
12715         // Don't warn about float constants that are precisely
12716         // representable in the target type.
12717         Expr::EvalResult result;
12718         if (E->EvaluateAsRValue(result, S.Context)) {
12719           // Value might be a float, a float vector, or a float complex.
12720           if (IsSameFloatAfterCast(result.Val,
12721                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12722                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12723             return;
12724         }
12725 
12726         if (S.SourceMgr.isInSystemMacro(CC))
12727           return;
12728 
12729         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12730       }
12731       // ... or possibly if we're increasing rank, too
12732       else if (Order < 0) {
12733         if (S.SourceMgr.isInSystemMacro(CC))
12734           return;
12735 
12736         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12737       }
12738       return;
12739     }
12740 
12741     // If the target is integral, always warn.
12742     if (TargetBT && TargetBT->isInteger()) {
12743       if (S.SourceMgr.isInSystemMacro(CC))
12744         return;
12745 
12746       DiagnoseFloatingImpCast(S, E, T, CC);
12747     }
12748 
12749     // Detect the case where a call result is converted from floating-point to
12750     // to bool, and the final argument to the call is converted from bool, to
12751     // discover this typo:
12752     //
12753     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12754     //
12755     // FIXME: This is an incredibly special case; is there some more general
12756     // way to detect this class of misplaced-parentheses bug?
12757     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12758       // Check last argument of function call to see if it is an
12759       // implicit cast from a type matching the type the result
12760       // is being cast to.
12761       CallExpr *CEx = cast<CallExpr>(E);
12762       if (unsigned NumArgs = CEx->getNumArgs()) {
12763         Expr *LastA = CEx->getArg(NumArgs - 1);
12764         Expr *InnerE = LastA->IgnoreParenImpCasts();
12765         if (isa<ImplicitCastExpr>(LastA) &&
12766             InnerE->getType()->isBooleanType()) {
12767           // Warn on this floating-point to bool conversion
12768           DiagnoseImpCast(S, E, T, CC,
12769                           diag::warn_impcast_floating_point_to_bool);
12770         }
12771       }
12772     }
12773     return;
12774   }
12775 
12776   // Valid casts involving fixed point types should be accounted for here.
12777   if (Source->isFixedPointType()) {
12778     if (Target->isUnsaturatedFixedPointType()) {
12779       Expr::EvalResult Result;
12780       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12781                                   S.isConstantEvaluated())) {
12782         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12783         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12784         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12785         if (Value > MaxVal || Value < MinVal) {
12786           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12787                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12788                                     << Value.toString() << T
12789                                     << E->getSourceRange()
12790                                     << clang::SourceRange(CC));
12791           return;
12792         }
12793       }
12794     } else if (Target->isIntegerType()) {
12795       Expr::EvalResult Result;
12796       if (!S.isConstantEvaluated() &&
12797           E->EvaluateAsFixedPoint(Result, S.Context,
12798                                   Expr::SE_AllowSideEffects)) {
12799         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12800 
12801         bool Overflowed;
12802         llvm::APSInt IntResult = FXResult.convertToInt(
12803             S.Context.getIntWidth(T),
12804             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12805 
12806         if (Overflowed) {
12807           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12808                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12809                                     << FXResult.toString() << T
12810                                     << E->getSourceRange()
12811                                     << clang::SourceRange(CC));
12812           return;
12813         }
12814       }
12815     }
12816   } else if (Target->isUnsaturatedFixedPointType()) {
12817     if (Source->isIntegerType()) {
12818       Expr::EvalResult Result;
12819       if (!S.isConstantEvaluated() &&
12820           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12821         llvm::APSInt Value = Result.Val.getInt();
12822 
12823         bool Overflowed;
12824         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12825             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12826 
12827         if (Overflowed) {
12828           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12829                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12830                                     << toString(Value, /*Radix=*/10) << T
12831                                     << E->getSourceRange()
12832                                     << clang::SourceRange(CC));
12833           return;
12834         }
12835       }
12836     }
12837   }
12838 
12839   // If we are casting an integer type to a floating point type without
12840   // initialization-list syntax, we might lose accuracy if the floating
12841   // point type has a narrower significand than the integer type.
12842   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12843       TargetBT->isFloatingType() && !IsListInit) {
12844     // Determine the number of precision bits in the source integer type.
12845     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12846                                         /*Approximate*/ true);
12847     unsigned int SourcePrecision = SourceRange.Width;
12848 
12849     // Determine the number of precision bits in the
12850     // target floating point type.
12851     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12852         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12853 
12854     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12855         SourcePrecision > TargetPrecision) {
12856 
12857       if (Optional<llvm::APSInt> SourceInt =
12858               E->getIntegerConstantExpr(S.Context)) {
12859         // If the source integer is a constant, convert it to the target
12860         // floating point type. Issue a warning if the value changes
12861         // during the whole conversion.
12862         llvm::APFloat TargetFloatValue(
12863             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12864         llvm::APFloat::opStatus ConversionStatus =
12865             TargetFloatValue.convertFromAPInt(
12866                 *SourceInt, SourceBT->isSignedInteger(),
12867                 llvm::APFloat::rmNearestTiesToEven);
12868 
12869         if (ConversionStatus != llvm::APFloat::opOK) {
12870           SmallString<32> PrettySourceValue;
12871           SourceInt->toString(PrettySourceValue, 10);
12872           SmallString<32> PrettyTargetValue;
12873           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12874 
12875           S.DiagRuntimeBehavior(
12876               E->getExprLoc(), E,
12877               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12878                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12879                   << E->getSourceRange() << clang::SourceRange(CC));
12880         }
12881       } else {
12882         // Otherwise, the implicit conversion may lose precision.
12883         DiagnoseImpCast(S, E, T, CC,
12884                         diag::warn_impcast_integer_float_precision);
12885       }
12886     }
12887   }
12888 
12889   DiagnoseNullConversion(S, E, T, CC);
12890 
12891   S.DiscardMisalignedMemberAddress(Target, E);
12892 
12893   if (Target->isBooleanType())
12894     DiagnoseIntInBoolContext(S, E);
12895 
12896   if (!Source->isIntegerType() || !Target->isIntegerType())
12897     return;
12898 
12899   // TODO: remove this early return once the false positives for constant->bool
12900   // in templates, macros, etc, are reduced or removed.
12901   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12902     return;
12903 
12904   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12905       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12906     return adornObjCBoolConversionDiagWithTernaryFixit(
12907         S, E,
12908         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12909             << E->getType());
12910   }
12911 
12912   IntRange SourceTypeRange =
12913       IntRange::forTargetOfCanonicalType(S.Context, Source);
12914   IntRange LikelySourceRange =
12915       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12916   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12917 
12918   if (LikelySourceRange.Width > TargetRange.Width) {
12919     // If the source is a constant, use a default-on diagnostic.
12920     // TODO: this should happen for bitfield stores, too.
12921     Expr::EvalResult Result;
12922     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12923                          S.isConstantEvaluated())) {
12924       llvm::APSInt Value(32);
12925       Value = Result.Val.getInt();
12926 
12927       if (S.SourceMgr.isInSystemMacro(CC))
12928         return;
12929 
12930       std::string PrettySourceValue = toString(Value, 10);
12931       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12932 
12933       S.DiagRuntimeBehavior(
12934           E->getExprLoc(), E,
12935           S.PDiag(diag::warn_impcast_integer_precision_constant)
12936               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12937               << E->getSourceRange() << SourceRange(CC));
12938       return;
12939     }
12940 
12941     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12942     if (S.SourceMgr.isInSystemMacro(CC))
12943       return;
12944 
12945     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12946       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12947                              /* pruneControlFlow */ true);
12948     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12949   }
12950 
12951   if (TargetRange.Width > SourceTypeRange.Width) {
12952     if (auto *UO = dyn_cast<UnaryOperator>(E))
12953       if (UO->getOpcode() == UO_Minus)
12954         if (Source->isUnsignedIntegerType()) {
12955           if (Target->isUnsignedIntegerType())
12956             return DiagnoseImpCast(S, E, T, CC,
12957                                    diag::warn_impcast_high_order_zero_bits);
12958           if (Target->isSignedIntegerType())
12959             return DiagnoseImpCast(S, E, T, CC,
12960                                    diag::warn_impcast_nonnegative_result);
12961         }
12962   }
12963 
12964   if (TargetRange.Width == LikelySourceRange.Width &&
12965       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12966       Source->isSignedIntegerType()) {
12967     // Warn when doing a signed to signed conversion, warn if the positive
12968     // source value is exactly the width of the target type, which will
12969     // cause a negative value to be stored.
12970 
12971     Expr::EvalResult Result;
12972     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12973         !S.SourceMgr.isInSystemMacro(CC)) {
12974       llvm::APSInt Value = Result.Val.getInt();
12975       if (isSameWidthConstantConversion(S, E, T, CC)) {
12976         std::string PrettySourceValue = toString(Value, 10);
12977         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12978 
12979         S.DiagRuntimeBehavior(
12980             E->getExprLoc(), E,
12981             S.PDiag(diag::warn_impcast_integer_precision_constant)
12982                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12983                 << E->getSourceRange() << SourceRange(CC));
12984         return;
12985       }
12986     }
12987 
12988     // Fall through for non-constants to give a sign conversion warning.
12989   }
12990 
12991   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12992       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12993        LikelySourceRange.Width == TargetRange.Width)) {
12994     if (S.SourceMgr.isInSystemMacro(CC))
12995       return;
12996 
12997     unsigned DiagID = diag::warn_impcast_integer_sign;
12998 
12999     // Traditionally, gcc has warned about this under -Wsign-compare.
13000     // We also want to warn about it in -Wconversion.
13001     // So if -Wconversion is off, use a completely identical diagnostic
13002     // in the sign-compare group.
13003     // The conditional-checking code will
13004     if (ICContext) {
13005       DiagID = diag::warn_impcast_integer_sign_conditional;
13006       *ICContext = true;
13007     }
13008 
13009     return DiagnoseImpCast(S, E, T, CC, DiagID);
13010   }
13011 
13012   // Diagnose conversions between different enumeration types.
13013   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13014   // type, to give us better diagnostics.
13015   QualType SourceType = E->getType();
13016   if (!S.getLangOpts().CPlusPlus) {
13017     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13018       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13019         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13020         SourceType = S.Context.getTypeDeclType(Enum);
13021         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13022       }
13023   }
13024 
13025   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13026     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13027       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13028           TargetEnum->getDecl()->hasNameForLinkage() &&
13029           SourceEnum != TargetEnum) {
13030         if (S.SourceMgr.isInSystemMacro(CC))
13031           return;
13032 
13033         return DiagnoseImpCast(S, E, SourceType, T, CC,
13034                                diag::warn_impcast_different_enum_types);
13035       }
13036 }
13037 
13038 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13039                                      SourceLocation CC, QualType T);
13040 
13041 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13042                                     SourceLocation CC, bool &ICContext) {
13043   E = E->IgnoreParenImpCasts();
13044 
13045   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13046     return CheckConditionalOperator(S, CO, CC, T);
13047 
13048   AnalyzeImplicitConversions(S, E, CC);
13049   if (E->getType() != T)
13050     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13051 }
13052 
13053 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13054                                      SourceLocation CC, QualType T) {
13055   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13056 
13057   Expr *TrueExpr = E->getTrueExpr();
13058   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13059     TrueExpr = BCO->getCommon();
13060 
13061   bool Suspicious = false;
13062   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13063   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13064 
13065   if (T->isBooleanType())
13066     DiagnoseIntInBoolContext(S, E);
13067 
13068   // If -Wconversion would have warned about either of the candidates
13069   // for a signedness conversion to the context type...
13070   if (!Suspicious) return;
13071 
13072   // ...but it's currently ignored...
13073   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13074     return;
13075 
13076   // ...then check whether it would have warned about either of the
13077   // candidates for a signedness conversion to the condition type.
13078   if (E->getType() == T) return;
13079 
13080   Suspicious = false;
13081   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13082                           E->getType(), CC, &Suspicious);
13083   if (!Suspicious)
13084     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13085                             E->getType(), CC, &Suspicious);
13086 }
13087 
13088 /// Check conversion of given expression to boolean.
13089 /// Input argument E is a logical expression.
13090 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13091   if (S.getLangOpts().Bool)
13092     return;
13093   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13094     return;
13095   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13096 }
13097 
13098 namespace {
13099 struct AnalyzeImplicitConversionsWorkItem {
13100   Expr *E;
13101   SourceLocation CC;
13102   bool IsListInit;
13103 };
13104 }
13105 
13106 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13107 /// that should be visited are added to WorkList.
13108 static void AnalyzeImplicitConversions(
13109     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13110     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13111   Expr *OrigE = Item.E;
13112   SourceLocation CC = Item.CC;
13113 
13114   QualType T = OrigE->getType();
13115   Expr *E = OrigE->IgnoreParenImpCasts();
13116 
13117   // Propagate whether we are in a C++ list initialization expression.
13118   // If so, we do not issue warnings for implicit int-float conversion
13119   // precision loss, because C++11 narrowing already handles it.
13120   bool IsListInit = Item.IsListInit ||
13121                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13122 
13123   if (E->isTypeDependent() || E->isValueDependent())
13124     return;
13125 
13126   Expr *SourceExpr = E;
13127   // Examine, but don't traverse into the source expression of an
13128   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13129   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13130   // evaluate it in the context of checking the specific conversion to T though.
13131   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13132     if (auto *Src = OVE->getSourceExpr())
13133       SourceExpr = Src;
13134 
13135   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13136     if (UO->getOpcode() == UO_Not &&
13137         UO->getSubExpr()->isKnownToHaveBooleanValue())
13138       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13139           << OrigE->getSourceRange() << T->isBooleanType()
13140           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13141 
13142   // For conditional operators, we analyze the arguments as if they
13143   // were being fed directly into the output.
13144   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13145     CheckConditionalOperator(S, CO, CC, T);
13146     return;
13147   }
13148 
13149   // Check implicit argument conversions for function calls.
13150   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13151     CheckImplicitArgumentConversions(S, Call, CC);
13152 
13153   // Go ahead and check any implicit conversions we might have skipped.
13154   // The non-canonical typecheck is just an optimization;
13155   // CheckImplicitConversion will filter out dead implicit conversions.
13156   if (SourceExpr->getType() != T)
13157     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13158 
13159   // Now continue drilling into this expression.
13160 
13161   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13162     // The bound subexpressions in a PseudoObjectExpr are not reachable
13163     // as transitive children.
13164     // FIXME: Use a more uniform representation for this.
13165     for (auto *SE : POE->semantics())
13166       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13167         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13168   }
13169 
13170   // Skip past explicit casts.
13171   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13172     E = CE->getSubExpr()->IgnoreParenImpCasts();
13173     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13174       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13175     WorkList.push_back({E, CC, IsListInit});
13176     return;
13177   }
13178 
13179   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13180     // Do a somewhat different check with comparison operators.
13181     if (BO->isComparisonOp())
13182       return AnalyzeComparison(S, BO);
13183 
13184     // And with simple assignments.
13185     if (BO->getOpcode() == BO_Assign)
13186       return AnalyzeAssignment(S, BO);
13187     // And with compound assignments.
13188     if (BO->isAssignmentOp())
13189       return AnalyzeCompoundAssignment(S, BO);
13190   }
13191 
13192   // These break the otherwise-useful invariant below.  Fortunately,
13193   // we don't really need to recurse into them, because any internal
13194   // expressions should have been analyzed already when they were
13195   // built into statements.
13196   if (isa<StmtExpr>(E)) return;
13197 
13198   // Don't descend into unevaluated contexts.
13199   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13200 
13201   // Now just recurse over the expression's children.
13202   CC = E->getExprLoc();
13203   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13204   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13205   for (Stmt *SubStmt : E->children()) {
13206     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13207     if (!ChildExpr)
13208       continue;
13209 
13210     if (IsLogicalAndOperator &&
13211         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13212       // Ignore checking string literals that are in logical and operators.
13213       // This is a common pattern for asserts.
13214       continue;
13215     WorkList.push_back({ChildExpr, CC, IsListInit});
13216   }
13217 
13218   if (BO && BO->isLogicalOp()) {
13219     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13220     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13221       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13222 
13223     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13224     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13225       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13226   }
13227 
13228   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13229     if (U->getOpcode() == UO_LNot) {
13230       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13231     } else if (U->getOpcode() != UO_AddrOf) {
13232       if (U->getSubExpr()->getType()->isAtomicType())
13233         S.Diag(U->getSubExpr()->getBeginLoc(),
13234                diag::warn_atomic_implicit_seq_cst);
13235     }
13236   }
13237 }
13238 
13239 /// AnalyzeImplicitConversions - Find and report any interesting
13240 /// implicit conversions in the given expression.  There are a couple
13241 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13242 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13243                                        bool IsListInit/*= false*/) {
13244   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13245   WorkList.push_back({OrigE, CC, IsListInit});
13246   while (!WorkList.empty())
13247     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13248 }
13249 
13250 /// Diagnose integer type and any valid implicit conversion to it.
13251 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13252   // Taking into account implicit conversions,
13253   // allow any integer.
13254   if (!E->getType()->isIntegerType()) {
13255     S.Diag(E->getBeginLoc(),
13256            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13257     return true;
13258   }
13259   // Potentially emit standard warnings for implicit conversions if enabled
13260   // using -Wconversion.
13261   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13262   return false;
13263 }
13264 
13265 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13266 // Returns true when emitting a warning about taking the address of a reference.
13267 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13268                               const PartialDiagnostic &PD) {
13269   E = E->IgnoreParenImpCasts();
13270 
13271   const FunctionDecl *FD = nullptr;
13272 
13273   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13274     if (!DRE->getDecl()->getType()->isReferenceType())
13275       return false;
13276   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13277     if (!M->getMemberDecl()->getType()->isReferenceType())
13278       return false;
13279   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13280     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13281       return false;
13282     FD = Call->getDirectCallee();
13283   } else {
13284     return false;
13285   }
13286 
13287   SemaRef.Diag(E->getExprLoc(), PD);
13288 
13289   // If possible, point to location of function.
13290   if (FD) {
13291     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13292   }
13293 
13294   return true;
13295 }
13296 
13297 // Returns true if the SourceLocation is expanded from any macro body.
13298 // Returns false if the SourceLocation is invalid, is from not in a macro
13299 // expansion, or is from expanded from a top-level macro argument.
13300 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13301   if (Loc.isInvalid())
13302     return false;
13303 
13304   while (Loc.isMacroID()) {
13305     if (SM.isMacroBodyExpansion(Loc))
13306       return true;
13307     Loc = SM.getImmediateMacroCallerLoc(Loc);
13308   }
13309 
13310   return false;
13311 }
13312 
13313 /// Diagnose pointers that are always non-null.
13314 /// \param E the expression containing the pointer
13315 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13316 /// compared to a null pointer
13317 /// \param IsEqual True when the comparison is equal to a null pointer
13318 /// \param Range Extra SourceRange to highlight in the diagnostic
13319 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13320                                         Expr::NullPointerConstantKind NullKind,
13321                                         bool IsEqual, SourceRange Range) {
13322   if (!E)
13323     return;
13324 
13325   // Don't warn inside macros.
13326   if (E->getExprLoc().isMacroID()) {
13327     const SourceManager &SM = getSourceManager();
13328     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13329         IsInAnyMacroBody(SM, Range.getBegin()))
13330       return;
13331   }
13332   E = E->IgnoreImpCasts();
13333 
13334   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13335 
13336   if (isa<CXXThisExpr>(E)) {
13337     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13338                                 : diag::warn_this_bool_conversion;
13339     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13340     return;
13341   }
13342 
13343   bool IsAddressOf = false;
13344 
13345   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13346     if (UO->getOpcode() != UO_AddrOf)
13347       return;
13348     IsAddressOf = true;
13349     E = UO->getSubExpr();
13350   }
13351 
13352   if (IsAddressOf) {
13353     unsigned DiagID = IsCompare
13354                           ? diag::warn_address_of_reference_null_compare
13355                           : diag::warn_address_of_reference_bool_conversion;
13356     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13357                                          << IsEqual;
13358     if (CheckForReference(*this, E, PD)) {
13359       return;
13360     }
13361   }
13362 
13363   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13364     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13365     std::string Str;
13366     llvm::raw_string_ostream S(Str);
13367     E->printPretty(S, nullptr, getPrintingPolicy());
13368     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13369                                 : diag::warn_cast_nonnull_to_bool;
13370     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13371       << E->getSourceRange() << Range << IsEqual;
13372     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13373   };
13374 
13375   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13376   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13377     if (auto *Callee = Call->getDirectCallee()) {
13378       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13379         ComplainAboutNonnullParamOrCall(A);
13380         return;
13381       }
13382     }
13383   }
13384 
13385   // Expect to find a single Decl.  Skip anything more complicated.
13386   ValueDecl *D = nullptr;
13387   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13388     D = R->getDecl();
13389   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13390     D = M->getMemberDecl();
13391   }
13392 
13393   // Weak Decls can be null.
13394   if (!D || D->isWeak())
13395     return;
13396 
13397   // Check for parameter decl with nonnull attribute
13398   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13399     if (getCurFunction() &&
13400         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13401       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13402         ComplainAboutNonnullParamOrCall(A);
13403         return;
13404       }
13405 
13406       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13407         // Skip function template not specialized yet.
13408         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13409           return;
13410         auto ParamIter = llvm::find(FD->parameters(), PV);
13411         assert(ParamIter != FD->param_end());
13412         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13413 
13414         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13415           if (!NonNull->args_size()) {
13416               ComplainAboutNonnullParamOrCall(NonNull);
13417               return;
13418           }
13419 
13420           for (const ParamIdx &ArgNo : NonNull->args()) {
13421             if (ArgNo.getASTIndex() == ParamNo) {
13422               ComplainAboutNonnullParamOrCall(NonNull);
13423               return;
13424             }
13425           }
13426         }
13427       }
13428     }
13429   }
13430 
13431   QualType T = D->getType();
13432   const bool IsArray = T->isArrayType();
13433   const bool IsFunction = T->isFunctionType();
13434 
13435   // Address of function is used to silence the function warning.
13436   if (IsAddressOf && IsFunction) {
13437     return;
13438   }
13439 
13440   // Found nothing.
13441   if (!IsAddressOf && !IsFunction && !IsArray)
13442     return;
13443 
13444   // Pretty print the expression for the diagnostic.
13445   std::string Str;
13446   llvm::raw_string_ostream S(Str);
13447   E->printPretty(S, nullptr, getPrintingPolicy());
13448 
13449   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13450                               : diag::warn_impcast_pointer_to_bool;
13451   enum {
13452     AddressOf,
13453     FunctionPointer,
13454     ArrayPointer
13455   } DiagType;
13456   if (IsAddressOf)
13457     DiagType = AddressOf;
13458   else if (IsFunction)
13459     DiagType = FunctionPointer;
13460   else if (IsArray)
13461     DiagType = ArrayPointer;
13462   else
13463     llvm_unreachable("Could not determine diagnostic.");
13464   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13465                                 << Range << IsEqual;
13466 
13467   if (!IsFunction)
13468     return;
13469 
13470   // Suggest '&' to silence the function warning.
13471   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13472       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13473 
13474   // Check to see if '()' fixit should be emitted.
13475   QualType ReturnType;
13476   UnresolvedSet<4> NonTemplateOverloads;
13477   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13478   if (ReturnType.isNull())
13479     return;
13480 
13481   if (IsCompare) {
13482     // There are two cases here.  If there is null constant, the only suggest
13483     // for a pointer return type.  If the null is 0, then suggest if the return
13484     // type is a pointer or an integer type.
13485     if (!ReturnType->isPointerType()) {
13486       if (NullKind == Expr::NPCK_ZeroExpression ||
13487           NullKind == Expr::NPCK_ZeroLiteral) {
13488         if (!ReturnType->isIntegerType())
13489           return;
13490       } else {
13491         return;
13492       }
13493     }
13494   } else { // !IsCompare
13495     // For function to bool, only suggest if the function pointer has bool
13496     // return type.
13497     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13498       return;
13499   }
13500   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13501       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13502 }
13503 
13504 /// Diagnoses "dangerous" implicit conversions within the given
13505 /// expression (which is a full expression).  Implements -Wconversion
13506 /// and -Wsign-compare.
13507 ///
13508 /// \param CC the "context" location of the implicit conversion, i.e.
13509 ///   the most location of the syntactic entity requiring the implicit
13510 ///   conversion
13511 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13512   // Don't diagnose in unevaluated contexts.
13513   if (isUnevaluatedContext())
13514     return;
13515 
13516   // Don't diagnose for value- or type-dependent expressions.
13517   if (E->isTypeDependent() || E->isValueDependent())
13518     return;
13519 
13520   // Check for array bounds violations in cases where the check isn't triggered
13521   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13522   // ArraySubscriptExpr is on the RHS of a variable initialization.
13523   CheckArrayAccess(E);
13524 
13525   // This is not the right CC for (e.g.) a variable initialization.
13526   AnalyzeImplicitConversions(*this, E, CC);
13527 }
13528 
13529 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13530 /// Input argument E is a logical expression.
13531 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13532   ::CheckBoolLikeConversion(*this, E, CC);
13533 }
13534 
13535 /// Diagnose when expression is an integer constant expression and its evaluation
13536 /// results in integer overflow
13537 void Sema::CheckForIntOverflow (Expr *E) {
13538   // Use a work list to deal with nested struct initializers.
13539   SmallVector<Expr *, 2> Exprs(1, E);
13540 
13541   do {
13542     Expr *OriginalE = Exprs.pop_back_val();
13543     Expr *E = OriginalE->IgnoreParenCasts();
13544 
13545     if (isa<BinaryOperator>(E)) {
13546       E->EvaluateForOverflow(Context);
13547       continue;
13548     }
13549 
13550     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13551       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13552     else if (isa<ObjCBoxedExpr>(OriginalE))
13553       E->EvaluateForOverflow(Context);
13554     else if (auto Call = dyn_cast<CallExpr>(E))
13555       Exprs.append(Call->arg_begin(), Call->arg_end());
13556     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13557       Exprs.append(Message->arg_begin(), Message->arg_end());
13558   } while (!Exprs.empty());
13559 }
13560 
13561 namespace {
13562 
13563 /// Visitor for expressions which looks for unsequenced operations on the
13564 /// same object.
13565 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13566   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13567 
13568   /// A tree of sequenced regions within an expression. Two regions are
13569   /// unsequenced if one is an ancestor or a descendent of the other. When we
13570   /// finish processing an expression with sequencing, such as a comma
13571   /// expression, we fold its tree nodes into its parent, since they are
13572   /// unsequenced with respect to nodes we will visit later.
13573   class SequenceTree {
13574     struct Value {
13575       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13576       unsigned Parent : 31;
13577       unsigned Merged : 1;
13578     };
13579     SmallVector<Value, 8> Values;
13580 
13581   public:
13582     /// A region within an expression which may be sequenced with respect
13583     /// to some other region.
13584     class Seq {
13585       friend class SequenceTree;
13586 
13587       unsigned Index;
13588 
13589       explicit Seq(unsigned N) : Index(N) {}
13590 
13591     public:
13592       Seq() : Index(0) {}
13593     };
13594 
13595     SequenceTree() { Values.push_back(Value(0)); }
13596     Seq root() const { return Seq(0); }
13597 
13598     /// Create a new sequence of operations, which is an unsequenced
13599     /// subset of \p Parent. This sequence of operations is sequenced with
13600     /// respect to other children of \p Parent.
13601     Seq allocate(Seq Parent) {
13602       Values.push_back(Value(Parent.Index));
13603       return Seq(Values.size() - 1);
13604     }
13605 
13606     /// Merge a sequence of operations into its parent.
13607     void merge(Seq S) {
13608       Values[S.Index].Merged = true;
13609     }
13610 
13611     /// Determine whether two operations are unsequenced. This operation
13612     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13613     /// should have been merged into its parent as appropriate.
13614     bool isUnsequenced(Seq Cur, Seq Old) {
13615       unsigned C = representative(Cur.Index);
13616       unsigned Target = representative(Old.Index);
13617       while (C >= Target) {
13618         if (C == Target)
13619           return true;
13620         C = Values[C].Parent;
13621       }
13622       return false;
13623     }
13624 
13625   private:
13626     /// Pick a representative for a sequence.
13627     unsigned representative(unsigned K) {
13628       if (Values[K].Merged)
13629         // Perform path compression as we go.
13630         return Values[K].Parent = representative(Values[K].Parent);
13631       return K;
13632     }
13633   };
13634 
13635   /// An object for which we can track unsequenced uses.
13636   using Object = const NamedDecl *;
13637 
13638   /// Different flavors of object usage which we track. We only track the
13639   /// least-sequenced usage of each kind.
13640   enum UsageKind {
13641     /// A read of an object. Multiple unsequenced reads are OK.
13642     UK_Use,
13643 
13644     /// A modification of an object which is sequenced before the value
13645     /// computation of the expression, such as ++n in C++.
13646     UK_ModAsValue,
13647 
13648     /// A modification of an object which is not sequenced before the value
13649     /// computation of the expression, such as n++.
13650     UK_ModAsSideEffect,
13651 
13652     UK_Count = UK_ModAsSideEffect + 1
13653   };
13654 
13655   /// Bundle together a sequencing region and the expression corresponding
13656   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13657   struct Usage {
13658     const Expr *UsageExpr;
13659     SequenceTree::Seq Seq;
13660 
13661     Usage() : UsageExpr(nullptr), Seq() {}
13662   };
13663 
13664   struct UsageInfo {
13665     Usage Uses[UK_Count];
13666 
13667     /// Have we issued a diagnostic for this object already?
13668     bool Diagnosed;
13669 
13670     UsageInfo() : Uses(), Diagnosed(false) {}
13671   };
13672   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13673 
13674   Sema &SemaRef;
13675 
13676   /// Sequenced regions within the expression.
13677   SequenceTree Tree;
13678 
13679   /// Declaration modifications and references which we have seen.
13680   UsageInfoMap UsageMap;
13681 
13682   /// The region we are currently within.
13683   SequenceTree::Seq Region;
13684 
13685   /// Filled in with declarations which were modified as a side-effect
13686   /// (that is, post-increment operations).
13687   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13688 
13689   /// Expressions to check later. We defer checking these to reduce
13690   /// stack usage.
13691   SmallVectorImpl<const Expr *> &WorkList;
13692 
13693   /// RAII object wrapping the visitation of a sequenced subexpression of an
13694   /// expression. At the end of this process, the side-effects of the evaluation
13695   /// become sequenced with respect to the value computation of the result, so
13696   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13697   /// UK_ModAsValue.
13698   struct SequencedSubexpression {
13699     SequencedSubexpression(SequenceChecker &Self)
13700       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13701       Self.ModAsSideEffect = &ModAsSideEffect;
13702     }
13703 
13704     ~SequencedSubexpression() {
13705       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13706         // Add a new usage with usage kind UK_ModAsValue, and then restore
13707         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13708         // the previous one was empty).
13709         UsageInfo &UI = Self.UsageMap[M.first];
13710         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13711         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13712         SideEffectUsage = M.second;
13713       }
13714       Self.ModAsSideEffect = OldModAsSideEffect;
13715     }
13716 
13717     SequenceChecker &Self;
13718     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13719     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13720   };
13721 
13722   /// RAII object wrapping the visitation of a subexpression which we might
13723   /// choose to evaluate as a constant. If any subexpression is evaluated and
13724   /// found to be non-constant, this allows us to suppress the evaluation of
13725   /// the outer expression.
13726   class EvaluationTracker {
13727   public:
13728     EvaluationTracker(SequenceChecker &Self)
13729         : Self(Self), Prev(Self.EvalTracker) {
13730       Self.EvalTracker = this;
13731     }
13732 
13733     ~EvaluationTracker() {
13734       Self.EvalTracker = Prev;
13735       if (Prev)
13736         Prev->EvalOK &= EvalOK;
13737     }
13738 
13739     bool evaluate(const Expr *E, bool &Result) {
13740       if (!EvalOK || E->isValueDependent())
13741         return false;
13742       EvalOK = E->EvaluateAsBooleanCondition(
13743           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13744       return EvalOK;
13745     }
13746 
13747   private:
13748     SequenceChecker &Self;
13749     EvaluationTracker *Prev;
13750     bool EvalOK = true;
13751   } *EvalTracker = nullptr;
13752 
13753   /// Find the object which is produced by the specified expression,
13754   /// if any.
13755   Object getObject(const Expr *E, bool Mod) const {
13756     E = E->IgnoreParenCasts();
13757     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13758       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13759         return getObject(UO->getSubExpr(), Mod);
13760     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13761       if (BO->getOpcode() == BO_Comma)
13762         return getObject(BO->getRHS(), Mod);
13763       if (Mod && BO->isAssignmentOp())
13764         return getObject(BO->getLHS(), Mod);
13765     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13766       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13767       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13768         return ME->getMemberDecl();
13769     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13770       // FIXME: If this is a reference, map through to its value.
13771       return DRE->getDecl();
13772     return nullptr;
13773   }
13774 
13775   /// Note that an object \p O was modified or used by an expression
13776   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13777   /// the object \p O as obtained via the \p UsageMap.
13778   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13779     // Get the old usage for the given object and usage kind.
13780     Usage &U = UI.Uses[UK];
13781     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13782       // If we have a modification as side effect and are in a sequenced
13783       // subexpression, save the old Usage so that we can restore it later
13784       // in SequencedSubexpression::~SequencedSubexpression.
13785       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13786         ModAsSideEffect->push_back(std::make_pair(O, U));
13787       // Then record the new usage with the current sequencing region.
13788       U.UsageExpr = UsageExpr;
13789       U.Seq = Region;
13790     }
13791   }
13792 
13793   /// Check whether a modification or use of an object \p O in an expression
13794   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13795   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13796   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13797   /// usage and false we are checking for a mod-use unsequenced usage.
13798   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13799                   UsageKind OtherKind, bool IsModMod) {
13800     if (UI.Diagnosed)
13801       return;
13802 
13803     const Usage &U = UI.Uses[OtherKind];
13804     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13805       return;
13806 
13807     const Expr *Mod = U.UsageExpr;
13808     const Expr *ModOrUse = UsageExpr;
13809     if (OtherKind == UK_Use)
13810       std::swap(Mod, ModOrUse);
13811 
13812     SemaRef.DiagRuntimeBehavior(
13813         Mod->getExprLoc(), {Mod, ModOrUse},
13814         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13815                                : diag::warn_unsequenced_mod_use)
13816             << O << SourceRange(ModOrUse->getExprLoc()));
13817     UI.Diagnosed = true;
13818   }
13819 
13820   // A note on note{Pre, Post}{Use, Mod}:
13821   //
13822   // (It helps to follow the algorithm with an expression such as
13823   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13824   //  operations before C++17 and both are well-defined in C++17).
13825   //
13826   // When visiting a node which uses/modify an object we first call notePreUse
13827   // or notePreMod before visiting its sub-expression(s). At this point the
13828   // children of the current node have not yet been visited and so the eventual
13829   // uses/modifications resulting from the children of the current node have not
13830   // been recorded yet.
13831   //
13832   // We then visit the children of the current node. After that notePostUse or
13833   // notePostMod is called. These will 1) detect an unsequenced modification
13834   // as side effect (as in "k++ + k") and 2) add a new usage with the
13835   // appropriate usage kind.
13836   //
13837   // We also have to be careful that some operation sequences modification as
13838   // side effect as well (for example: || or ,). To account for this we wrap
13839   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13840   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13841   // which record usages which are modifications as side effect, and then
13842   // downgrade them (or more accurately restore the previous usage which was a
13843   // modification as side effect) when exiting the scope of the sequenced
13844   // subexpression.
13845 
13846   void notePreUse(Object O, const Expr *UseExpr) {
13847     UsageInfo &UI = UsageMap[O];
13848     // Uses conflict with other modifications.
13849     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13850   }
13851 
13852   void notePostUse(Object O, const Expr *UseExpr) {
13853     UsageInfo &UI = UsageMap[O];
13854     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13855                /*IsModMod=*/false);
13856     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13857   }
13858 
13859   void notePreMod(Object O, const Expr *ModExpr) {
13860     UsageInfo &UI = UsageMap[O];
13861     // Modifications conflict with other modifications and with uses.
13862     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13863     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13864   }
13865 
13866   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13867     UsageInfo &UI = UsageMap[O];
13868     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13869                /*IsModMod=*/true);
13870     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13871   }
13872 
13873 public:
13874   SequenceChecker(Sema &S, const Expr *E,
13875                   SmallVectorImpl<const Expr *> &WorkList)
13876       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13877     Visit(E);
13878     // Silence a -Wunused-private-field since WorkList is now unused.
13879     // TODO: Evaluate if it can be used, and if not remove it.
13880     (void)this->WorkList;
13881   }
13882 
13883   void VisitStmt(const Stmt *S) {
13884     // Skip all statements which aren't expressions for now.
13885   }
13886 
13887   void VisitExpr(const Expr *E) {
13888     // By default, just recurse to evaluated subexpressions.
13889     Base::VisitStmt(E);
13890   }
13891 
13892   void VisitCastExpr(const CastExpr *E) {
13893     Object O = Object();
13894     if (E->getCastKind() == CK_LValueToRValue)
13895       O = getObject(E->getSubExpr(), false);
13896 
13897     if (O)
13898       notePreUse(O, E);
13899     VisitExpr(E);
13900     if (O)
13901       notePostUse(O, E);
13902   }
13903 
13904   void VisitSequencedExpressions(const Expr *SequencedBefore,
13905                                  const Expr *SequencedAfter) {
13906     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13907     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13908     SequenceTree::Seq OldRegion = Region;
13909 
13910     {
13911       SequencedSubexpression SeqBefore(*this);
13912       Region = BeforeRegion;
13913       Visit(SequencedBefore);
13914     }
13915 
13916     Region = AfterRegion;
13917     Visit(SequencedAfter);
13918 
13919     Region = OldRegion;
13920 
13921     Tree.merge(BeforeRegion);
13922     Tree.merge(AfterRegion);
13923   }
13924 
13925   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13926     // C++17 [expr.sub]p1:
13927     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13928     //   expression E1 is sequenced before the expression E2.
13929     if (SemaRef.getLangOpts().CPlusPlus17)
13930       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13931     else {
13932       Visit(ASE->getLHS());
13933       Visit(ASE->getRHS());
13934     }
13935   }
13936 
13937   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13938   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13939   void VisitBinPtrMem(const BinaryOperator *BO) {
13940     // C++17 [expr.mptr.oper]p4:
13941     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13942     //  the expression E1 is sequenced before the expression E2.
13943     if (SemaRef.getLangOpts().CPlusPlus17)
13944       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13945     else {
13946       Visit(BO->getLHS());
13947       Visit(BO->getRHS());
13948     }
13949   }
13950 
13951   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13952   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13953   void VisitBinShlShr(const BinaryOperator *BO) {
13954     // C++17 [expr.shift]p4:
13955     //  The expression E1 is sequenced before the expression E2.
13956     if (SemaRef.getLangOpts().CPlusPlus17)
13957       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13958     else {
13959       Visit(BO->getLHS());
13960       Visit(BO->getRHS());
13961     }
13962   }
13963 
13964   void VisitBinComma(const BinaryOperator *BO) {
13965     // C++11 [expr.comma]p1:
13966     //   Every value computation and side effect associated with the left
13967     //   expression is sequenced before every value computation and side
13968     //   effect associated with the right expression.
13969     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13970   }
13971 
13972   void VisitBinAssign(const BinaryOperator *BO) {
13973     SequenceTree::Seq RHSRegion;
13974     SequenceTree::Seq LHSRegion;
13975     if (SemaRef.getLangOpts().CPlusPlus17) {
13976       RHSRegion = Tree.allocate(Region);
13977       LHSRegion = Tree.allocate(Region);
13978     } else {
13979       RHSRegion = Region;
13980       LHSRegion = Region;
13981     }
13982     SequenceTree::Seq OldRegion = Region;
13983 
13984     // C++11 [expr.ass]p1:
13985     //  [...] the assignment is sequenced after the value computation
13986     //  of the right and left operands, [...]
13987     //
13988     // so check it before inspecting the operands and update the
13989     // map afterwards.
13990     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13991     if (O)
13992       notePreMod(O, BO);
13993 
13994     if (SemaRef.getLangOpts().CPlusPlus17) {
13995       // C++17 [expr.ass]p1:
13996       //  [...] The right operand is sequenced before the left operand. [...]
13997       {
13998         SequencedSubexpression SeqBefore(*this);
13999         Region = RHSRegion;
14000         Visit(BO->getRHS());
14001       }
14002 
14003       Region = LHSRegion;
14004       Visit(BO->getLHS());
14005 
14006       if (O && isa<CompoundAssignOperator>(BO))
14007         notePostUse(O, BO);
14008 
14009     } else {
14010       // C++11 does not specify any sequencing between the LHS and RHS.
14011       Region = LHSRegion;
14012       Visit(BO->getLHS());
14013 
14014       if (O && isa<CompoundAssignOperator>(BO))
14015         notePostUse(O, BO);
14016 
14017       Region = RHSRegion;
14018       Visit(BO->getRHS());
14019     }
14020 
14021     // C++11 [expr.ass]p1:
14022     //  the assignment is sequenced [...] before the value computation of the
14023     //  assignment expression.
14024     // C11 6.5.16/3 has no such rule.
14025     Region = OldRegion;
14026     if (O)
14027       notePostMod(O, BO,
14028                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14029                                                   : UK_ModAsSideEffect);
14030     if (SemaRef.getLangOpts().CPlusPlus17) {
14031       Tree.merge(RHSRegion);
14032       Tree.merge(LHSRegion);
14033     }
14034   }
14035 
14036   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14037     VisitBinAssign(CAO);
14038   }
14039 
14040   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14041   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14042   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14043     Object O = getObject(UO->getSubExpr(), true);
14044     if (!O)
14045       return VisitExpr(UO);
14046 
14047     notePreMod(O, UO);
14048     Visit(UO->getSubExpr());
14049     // C++11 [expr.pre.incr]p1:
14050     //   the expression ++x is equivalent to x+=1
14051     notePostMod(O, UO,
14052                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14053                                                 : UK_ModAsSideEffect);
14054   }
14055 
14056   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14057   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14058   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14059     Object O = getObject(UO->getSubExpr(), true);
14060     if (!O)
14061       return VisitExpr(UO);
14062 
14063     notePreMod(O, UO);
14064     Visit(UO->getSubExpr());
14065     notePostMod(O, UO, UK_ModAsSideEffect);
14066   }
14067 
14068   void VisitBinLOr(const BinaryOperator *BO) {
14069     // C++11 [expr.log.or]p2:
14070     //  If the second expression is evaluated, every value computation and
14071     //  side effect associated with the first expression is sequenced before
14072     //  every value computation and side effect associated with the
14073     //  second expression.
14074     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14075     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14076     SequenceTree::Seq OldRegion = Region;
14077 
14078     EvaluationTracker Eval(*this);
14079     {
14080       SequencedSubexpression Sequenced(*this);
14081       Region = LHSRegion;
14082       Visit(BO->getLHS());
14083     }
14084 
14085     // C++11 [expr.log.or]p1:
14086     //  [...] the second operand is not evaluated if the first operand
14087     //  evaluates to true.
14088     bool EvalResult = false;
14089     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14090     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14091     if (ShouldVisitRHS) {
14092       Region = RHSRegion;
14093       Visit(BO->getRHS());
14094     }
14095 
14096     Region = OldRegion;
14097     Tree.merge(LHSRegion);
14098     Tree.merge(RHSRegion);
14099   }
14100 
14101   void VisitBinLAnd(const BinaryOperator *BO) {
14102     // C++11 [expr.log.and]p2:
14103     //  If the second expression is evaluated, every value computation and
14104     //  side effect associated with the first expression is sequenced before
14105     //  every value computation and side effect associated with the
14106     //  second expression.
14107     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14108     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14109     SequenceTree::Seq OldRegion = Region;
14110 
14111     EvaluationTracker Eval(*this);
14112     {
14113       SequencedSubexpression Sequenced(*this);
14114       Region = LHSRegion;
14115       Visit(BO->getLHS());
14116     }
14117 
14118     // C++11 [expr.log.and]p1:
14119     //  [...] the second operand is not evaluated if the first operand is false.
14120     bool EvalResult = false;
14121     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14122     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14123     if (ShouldVisitRHS) {
14124       Region = RHSRegion;
14125       Visit(BO->getRHS());
14126     }
14127 
14128     Region = OldRegion;
14129     Tree.merge(LHSRegion);
14130     Tree.merge(RHSRegion);
14131   }
14132 
14133   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14134     // C++11 [expr.cond]p1:
14135     //  [...] Every value computation and side effect associated with the first
14136     //  expression is sequenced before every value computation and side effect
14137     //  associated with the second or third expression.
14138     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14139 
14140     // No sequencing is specified between the true and false expression.
14141     // However since exactly one of both is going to be evaluated we can
14142     // consider them to be sequenced. This is needed to avoid warning on
14143     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14144     // both the true and false expressions because we can't evaluate x.
14145     // This will still allow us to detect an expression like (pre C++17)
14146     // "(x ? y += 1 : y += 2) = y".
14147     //
14148     // We don't wrap the visitation of the true and false expression with
14149     // SequencedSubexpression because we don't want to downgrade modifications
14150     // as side effect in the true and false expressions after the visition
14151     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14152     // not warn between the two "y++", but we should warn between the "y++"
14153     // and the "y".
14154     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14155     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14156     SequenceTree::Seq OldRegion = Region;
14157 
14158     EvaluationTracker Eval(*this);
14159     {
14160       SequencedSubexpression Sequenced(*this);
14161       Region = ConditionRegion;
14162       Visit(CO->getCond());
14163     }
14164 
14165     // C++11 [expr.cond]p1:
14166     // [...] The first expression is contextually converted to bool (Clause 4).
14167     // It is evaluated and if it is true, the result of the conditional
14168     // expression is the value of the second expression, otherwise that of the
14169     // third expression. Only one of the second and third expressions is
14170     // evaluated. [...]
14171     bool EvalResult = false;
14172     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14173     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14174     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14175     if (ShouldVisitTrueExpr) {
14176       Region = TrueRegion;
14177       Visit(CO->getTrueExpr());
14178     }
14179     if (ShouldVisitFalseExpr) {
14180       Region = FalseRegion;
14181       Visit(CO->getFalseExpr());
14182     }
14183 
14184     Region = OldRegion;
14185     Tree.merge(ConditionRegion);
14186     Tree.merge(TrueRegion);
14187     Tree.merge(FalseRegion);
14188   }
14189 
14190   void VisitCallExpr(const CallExpr *CE) {
14191     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14192 
14193     if (CE->isUnevaluatedBuiltinCall(Context))
14194       return;
14195 
14196     // C++11 [intro.execution]p15:
14197     //   When calling a function [...], every value computation and side effect
14198     //   associated with any argument expression, or with the postfix expression
14199     //   designating the called function, is sequenced before execution of every
14200     //   expression or statement in the body of the function [and thus before
14201     //   the value computation of its result].
14202     SequencedSubexpression Sequenced(*this);
14203     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14204       // C++17 [expr.call]p5
14205       //   The postfix-expression is sequenced before each expression in the
14206       //   expression-list and any default argument. [...]
14207       SequenceTree::Seq CalleeRegion;
14208       SequenceTree::Seq OtherRegion;
14209       if (SemaRef.getLangOpts().CPlusPlus17) {
14210         CalleeRegion = Tree.allocate(Region);
14211         OtherRegion = Tree.allocate(Region);
14212       } else {
14213         CalleeRegion = Region;
14214         OtherRegion = Region;
14215       }
14216       SequenceTree::Seq OldRegion = Region;
14217 
14218       // Visit the callee expression first.
14219       Region = CalleeRegion;
14220       if (SemaRef.getLangOpts().CPlusPlus17) {
14221         SequencedSubexpression Sequenced(*this);
14222         Visit(CE->getCallee());
14223       } else {
14224         Visit(CE->getCallee());
14225       }
14226 
14227       // Then visit the argument expressions.
14228       Region = OtherRegion;
14229       for (const Expr *Argument : CE->arguments())
14230         Visit(Argument);
14231 
14232       Region = OldRegion;
14233       if (SemaRef.getLangOpts().CPlusPlus17) {
14234         Tree.merge(CalleeRegion);
14235         Tree.merge(OtherRegion);
14236       }
14237     });
14238   }
14239 
14240   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14241     // C++17 [over.match.oper]p2:
14242     //   [...] the operator notation is first transformed to the equivalent
14243     //   function-call notation as summarized in Table 12 (where @ denotes one
14244     //   of the operators covered in the specified subclause). However, the
14245     //   operands are sequenced in the order prescribed for the built-in
14246     //   operator (Clause 8).
14247     //
14248     // From the above only overloaded binary operators and overloaded call
14249     // operators have sequencing rules in C++17 that we need to handle
14250     // separately.
14251     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14252         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14253       return VisitCallExpr(CXXOCE);
14254 
14255     enum {
14256       NoSequencing,
14257       LHSBeforeRHS,
14258       RHSBeforeLHS,
14259       LHSBeforeRest
14260     } SequencingKind;
14261     switch (CXXOCE->getOperator()) {
14262     case OO_Equal:
14263     case OO_PlusEqual:
14264     case OO_MinusEqual:
14265     case OO_StarEqual:
14266     case OO_SlashEqual:
14267     case OO_PercentEqual:
14268     case OO_CaretEqual:
14269     case OO_AmpEqual:
14270     case OO_PipeEqual:
14271     case OO_LessLessEqual:
14272     case OO_GreaterGreaterEqual:
14273       SequencingKind = RHSBeforeLHS;
14274       break;
14275 
14276     case OO_LessLess:
14277     case OO_GreaterGreater:
14278     case OO_AmpAmp:
14279     case OO_PipePipe:
14280     case OO_Comma:
14281     case OO_ArrowStar:
14282     case OO_Subscript:
14283       SequencingKind = LHSBeforeRHS;
14284       break;
14285 
14286     case OO_Call:
14287       SequencingKind = LHSBeforeRest;
14288       break;
14289 
14290     default:
14291       SequencingKind = NoSequencing;
14292       break;
14293     }
14294 
14295     if (SequencingKind == NoSequencing)
14296       return VisitCallExpr(CXXOCE);
14297 
14298     // This is a call, so all subexpressions are sequenced before the result.
14299     SequencedSubexpression Sequenced(*this);
14300 
14301     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14302       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14303              "Should only get there with C++17 and above!");
14304       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14305              "Should only get there with an overloaded binary operator"
14306              " or an overloaded call operator!");
14307 
14308       if (SequencingKind == LHSBeforeRest) {
14309         assert(CXXOCE->getOperator() == OO_Call &&
14310                "We should only have an overloaded call operator here!");
14311 
14312         // This is very similar to VisitCallExpr, except that we only have the
14313         // C++17 case. The postfix-expression is the first argument of the
14314         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14315         // are in the following arguments.
14316         //
14317         // Note that we intentionally do not visit the callee expression since
14318         // it is just a decayed reference to a function.
14319         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14320         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14321         SequenceTree::Seq OldRegion = Region;
14322 
14323         assert(CXXOCE->getNumArgs() >= 1 &&
14324                "An overloaded call operator must have at least one argument"
14325                " for the postfix-expression!");
14326         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14327         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14328                                           CXXOCE->getNumArgs() - 1);
14329 
14330         // Visit the postfix-expression first.
14331         {
14332           Region = PostfixExprRegion;
14333           SequencedSubexpression Sequenced(*this);
14334           Visit(PostfixExpr);
14335         }
14336 
14337         // Then visit the argument expressions.
14338         Region = ArgsRegion;
14339         for (const Expr *Arg : Args)
14340           Visit(Arg);
14341 
14342         Region = OldRegion;
14343         Tree.merge(PostfixExprRegion);
14344         Tree.merge(ArgsRegion);
14345       } else {
14346         assert(CXXOCE->getNumArgs() == 2 &&
14347                "Should only have two arguments here!");
14348         assert((SequencingKind == LHSBeforeRHS ||
14349                 SequencingKind == RHSBeforeLHS) &&
14350                "Unexpected sequencing kind!");
14351 
14352         // We do not visit the callee expression since it is just a decayed
14353         // reference to a function.
14354         const Expr *E1 = CXXOCE->getArg(0);
14355         const Expr *E2 = CXXOCE->getArg(1);
14356         if (SequencingKind == RHSBeforeLHS)
14357           std::swap(E1, E2);
14358 
14359         return VisitSequencedExpressions(E1, E2);
14360       }
14361     });
14362   }
14363 
14364   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14365     // This is a call, so all subexpressions are sequenced before the result.
14366     SequencedSubexpression Sequenced(*this);
14367 
14368     if (!CCE->isListInitialization())
14369       return VisitExpr(CCE);
14370 
14371     // In C++11, list initializations are sequenced.
14372     SmallVector<SequenceTree::Seq, 32> Elts;
14373     SequenceTree::Seq Parent = Region;
14374     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14375                                               E = CCE->arg_end();
14376          I != E; ++I) {
14377       Region = Tree.allocate(Parent);
14378       Elts.push_back(Region);
14379       Visit(*I);
14380     }
14381 
14382     // Forget that the initializers are sequenced.
14383     Region = Parent;
14384     for (unsigned I = 0; I < Elts.size(); ++I)
14385       Tree.merge(Elts[I]);
14386   }
14387 
14388   void VisitInitListExpr(const InitListExpr *ILE) {
14389     if (!SemaRef.getLangOpts().CPlusPlus11)
14390       return VisitExpr(ILE);
14391 
14392     // In C++11, list initializations are sequenced.
14393     SmallVector<SequenceTree::Seq, 32> Elts;
14394     SequenceTree::Seq Parent = Region;
14395     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14396       const Expr *E = ILE->getInit(I);
14397       if (!E)
14398         continue;
14399       Region = Tree.allocate(Parent);
14400       Elts.push_back(Region);
14401       Visit(E);
14402     }
14403 
14404     // Forget that the initializers are sequenced.
14405     Region = Parent;
14406     for (unsigned I = 0; I < Elts.size(); ++I)
14407       Tree.merge(Elts[I]);
14408   }
14409 };
14410 
14411 } // namespace
14412 
14413 void Sema::CheckUnsequencedOperations(const Expr *E) {
14414   SmallVector<const Expr *, 8> WorkList;
14415   WorkList.push_back(E);
14416   while (!WorkList.empty()) {
14417     const Expr *Item = WorkList.pop_back_val();
14418     SequenceChecker(*this, Item, WorkList);
14419   }
14420 }
14421 
14422 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14423                               bool IsConstexpr) {
14424   llvm::SaveAndRestore<bool> ConstantContext(
14425       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14426   CheckImplicitConversions(E, CheckLoc);
14427   if (!E->isInstantiationDependent())
14428     CheckUnsequencedOperations(E);
14429   if (!IsConstexpr && !E->isValueDependent())
14430     CheckForIntOverflow(E);
14431   DiagnoseMisalignedMembers();
14432 }
14433 
14434 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14435                                        FieldDecl *BitField,
14436                                        Expr *Init) {
14437   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14438 }
14439 
14440 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14441                                          SourceLocation Loc) {
14442   if (!PType->isVariablyModifiedType())
14443     return;
14444   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14445     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14446     return;
14447   }
14448   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14449     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14450     return;
14451   }
14452   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14453     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14454     return;
14455   }
14456 
14457   const ArrayType *AT = S.Context.getAsArrayType(PType);
14458   if (!AT)
14459     return;
14460 
14461   if (AT->getSizeModifier() != ArrayType::Star) {
14462     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14463     return;
14464   }
14465 
14466   S.Diag(Loc, diag::err_array_star_in_function_definition);
14467 }
14468 
14469 /// CheckParmsForFunctionDef - Check that the parameters of the given
14470 /// function are appropriate for the definition of a function. This
14471 /// takes care of any checks that cannot be performed on the
14472 /// declaration itself, e.g., that the types of each of the function
14473 /// parameters are complete.
14474 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14475                                     bool CheckParameterNames) {
14476   bool HasInvalidParm = false;
14477   for (ParmVarDecl *Param : Parameters) {
14478     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14479     // function declarator that is part of a function definition of
14480     // that function shall not have incomplete type.
14481     //
14482     // This is also C++ [dcl.fct]p6.
14483     if (!Param->isInvalidDecl() &&
14484         RequireCompleteType(Param->getLocation(), Param->getType(),
14485                             diag::err_typecheck_decl_incomplete_type)) {
14486       Param->setInvalidDecl();
14487       HasInvalidParm = true;
14488     }
14489 
14490     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14491     // declaration of each parameter shall include an identifier.
14492     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14493         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14494       // Diagnose this as an extension in C17 and earlier.
14495       if (!getLangOpts().C2x)
14496         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14497     }
14498 
14499     // C99 6.7.5.3p12:
14500     //   If the function declarator is not part of a definition of that
14501     //   function, parameters may have incomplete type and may use the [*]
14502     //   notation in their sequences of declarator specifiers to specify
14503     //   variable length array types.
14504     QualType PType = Param->getOriginalType();
14505     // FIXME: This diagnostic should point the '[*]' if source-location
14506     // information is added for it.
14507     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14508 
14509     // If the parameter is a c++ class type and it has to be destructed in the
14510     // callee function, declare the destructor so that it can be called by the
14511     // callee function. Do not perform any direct access check on the dtor here.
14512     if (!Param->isInvalidDecl()) {
14513       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14514         if (!ClassDecl->isInvalidDecl() &&
14515             !ClassDecl->hasIrrelevantDestructor() &&
14516             !ClassDecl->isDependentContext() &&
14517             ClassDecl->isParamDestroyedInCallee()) {
14518           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14519           MarkFunctionReferenced(Param->getLocation(), Destructor);
14520           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14521         }
14522       }
14523     }
14524 
14525     // Parameters with the pass_object_size attribute only need to be marked
14526     // constant at function definitions. Because we lack information about
14527     // whether we're on a declaration or definition when we're instantiating the
14528     // attribute, we need to check for constness here.
14529     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14530       if (!Param->getType().isConstQualified())
14531         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14532             << Attr->getSpelling() << 1;
14533 
14534     // Check for parameter names shadowing fields from the class.
14535     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14536       // The owning context for the parameter should be the function, but we
14537       // want to see if this function's declaration context is a record.
14538       DeclContext *DC = Param->getDeclContext();
14539       if (DC && DC->isFunctionOrMethod()) {
14540         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14541           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14542                                      RD, /*DeclIsField*/ false);
14543       }
14544     }
14545   }
14546 
14547   return HasInvalidParm;
14548 }
14549 
14550 Optional<std::pair<CharUnits, CharUnits>>
14551 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14552 
14553 /// Compute the alignment and offset of the base class object given the
14554 /// derived-to-base cast expression and the alignment and offset of the derived
14555 /// class object.
14556 static std::pair<CharUnits, CharUnits>
14557 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14558                                    CharUnits BaseAlignment, CharUnits Offset,
14559                                    ASTContext &Ctx) {
14560   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14561        ++PathI) {
14562     const CXXBaseSpecifier *Base = *PathI;
14563     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14564     if (Base->isVirtual()) {
14565       // The complete object may have a lower alignment than the non-virtual
14566       // alignment of the base, in which case the base may be misaligned. Choose
14567       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14568       // conservative lower bound of the complete object alignment.
14569       CharUnits NonVirtualAlignment =
14570           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14571       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14572       Offset = CharUnits::Zero();
14573     } else {
14574       const ASTRecordLayout &RL =
14575           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14576       Offset += RL.getBaseClassOffset(BaseDecl);
14577     }
14578     DerivedType = Base->getType();
14579   }
14580 
14581   return std::make_pair(BaseAlignment, Offset);
14582 }
14583 
14584 /// Compute the alignment and offset of a binary additive operator.
14585 static Optional<std::pair<CharUnits, CharUnits>>
14586 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14587                                      bool IsSub, ASTContext &Ctx) {
14588   QualType PointeeType = PtrE->getType()->getPointeeType();
14589 
14590   if (!PointeeType->isConstantSizeType())
14591     return llvm::None;
14592 
14593   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14594 
14595   if (!P)
14596     return llvm::None;
14597 
14598   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14599   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14600     CharUnits Offset = EltSize * IdxRes->getExtValue();
14601     if (IsSub)
14602       Offset = -Offset;
14603     return std::make_pair(P->first, P->second + Offset);
14604   }
14605 
14606   // If the integer expression isn't a constant expression, compute the lower
14607   // bound of the alignment using the alignment and offset of the pointer
14608   // expression and the element size.
14609   return std::make_pair(
14610       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14611       CharUnits::Zero());
14612 }
14613 
14614 /// This helper function takes an lvalue expression and returns the alignment of
14615 /// a VarDecl and a constant offset from the VarDecl.
14616 Optional<std::pair<CharUnits, CharUnits>>
14617 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14618   E = E->IgnoreParens();
14619   switch (E->getStmtClass()) {
14620   default:
14621     break;
14622   case Stmt::CStyleCastExprClass:
14623   case Stmt::CXXStaticCastExprClass:
14624   case Stmt::ImplicitCastExprClass: {
14625     auto *CE = cast<CastExpr>(E);
14626     const Expr *From = CE->getSubExpr();
14627     switch (CE->getCastKind()) {
14628     default:
14629       break;
14630     case CK_NoOp:
14631       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14632     case CK_UncheckedDerivedToBase:
14633     case CK_DerivedToBase: {
14634       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14635       if (!P)
14636         break;
14637       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14638                                                 P->second, Ctx);
14639     }
14640     }
14641     break;
14642   }
14643   case Stmt::ArraySubscriptExprClass: {
14644     auto *ASE = cast<ArraySubscriptExpr>(E);
14645     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14646                                                 false, Ctx);
14647   }
14648   case Stmt::DeclRefExprClass: {
14649     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14650       // FIXME: If VD is captured by copy or is an escaping __block variable,
14651       // use the alignment of VD's type.
14652       if (!VD->getType()->isReferenceType())
14653         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14654       if (VD->hasInit())
14655         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14656     }
14657     break;
14658   }
14659   case Stmt::MemberExprClass: {
14660     auto *ME = cast<MemberExpr>(E);
14661     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14662     if (!FD || FD->getType()->isReferenceType() ||
14663         FD->getParent()->isInvalidDecl())
14664       break;
14665     Optional<std::pair<CharUnits, CharUnits>> P;
14666     if (ME->isArrow())
14667       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14668     else
14669       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14670     if (!P)
14671       break;
14672     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14673     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14674     return std::make_pair(P->first,
14675                           P->second + CharUnits::fromQuantity(Offset));
14676   }
14677   case Stmt::UnaryOperatorClass: {
14678     auto *UO = cast<UnaryOperator>(E);
14679     switch (UO->getOpcode()) {
14680     default:
14681       break;
14682     case UO_Deref:
14683       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14684     }
14685     break;
14686   }
14687   case Stmt::BinaryOperatorClass: {
14688     auto *BO = cast<BinaryOperator>(E);
14689     auto Opcode = BO->getOpcode();
14690     switch (Opcode) {
14691     default:
14692       break;
14693     case BO_Comma:
14694       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14695     }
14696     break;
14697   }
14698   }
14699   return llvm::None;
14700 }
14701 
14702 /// This helper function takes a pointer expression and returns the alignment of
14703 /// a VarDecl and a constant offset from the VarDecl.
14704 Optional<std::pair<CharUnits, CharUnits>>
14705 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14706   E = E->IgnoreParens();
14707   switch (E->getStmtClass()) {
14708   default:
14709     break;
14710   case Stmt::CStyleCastExprClass:
14711   case Stmt::CXXStaticCastExprClass:
14712   case Stmt::ImplicitCastExprClass: {
14713     auto *CE = cast<CastExpr>(E);
14714     const Expr *From = CE->getSubExpr();
14715     switch (CE->getCastKind()) {
14716     default:
14717       break;
14718     case CK_NoOp:
14719       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14720     case CK_ArrayToPointerDecay:
14721       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14722     case CK_UncheckedDerivedToBase:
14723     case CK_DerivedToBase: {
14724       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14725       if (!P)
14726         break;
14727       return getDerivedToBaseAlignmentAndOffset(
14728           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14729     }
14730     }
14731     break;
14732   }
14733   case Stmt::CXXThisExprClass: {
14734     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14735     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14736     return std::make_pair(Alignment, CharUnits::Zero());
14737   }
14738   case Stmt::UnaryOperatorClass: {
14739     auto *UO = cast<UnaryOperator>(E);
14740     if (UO->getOpcode() == UO_AddrOf)
14741       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14742     break;
14743   }
14744   case Stmt::BinaryOperatorClass: {
14745     auto *BO = cast<BinaryOperator>(E);
14746     auto Opcode = BO->getOpcode();
14747     switch (Opcode) {
14748     default:
14749       break;
14750     case BO_Add:
14751     case BO_Sub: {
14752       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14753       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14754         std::swap(LHS, RHS);
14755       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14756                                                   Ctx);
14757     }
14758     case BO_Comma:
14759       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14760     }
14761     break;
14762   }
14763   }
14764   return llvm::None;
14765 }
14766 
14767 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14768   // See if we can compute the alignment of a VarDecl and an offset from it.
14769   Optional<std::pair<CharUnits, CharUnits>> P =
14770       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14771 
14772   if (P)
14773     return P->first.alignmentAtOffset(P->second);
14774 
14775   // If that failed, return the type's alignment.
14776   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14777 }
14778 
14779 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14780 /// pointer cast increases the alignment requirements.
14781 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14782   // This is actually a lot of work to potentially be doing on every
14783   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14784   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14785     return;
14786 
14787   // Ignore dependent types.
14788   if (T->isDependentType() || Op->getType()->isDependentType())
14789     return;
14790 
14791   // Require that the destination be a pointer type.
14792   const PointerType *DestPtr = T->getAs<PointerType>();
14793   if (!DestPtr) return;
14794 
14795   // If the destination has alignment 1, we're done.
14796   QualType DestPointee = DestPtr->getPointeeType();
14797   if (DestPointee->isIncompleteType()) return;
14798   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14799   if (DestAlign.isOne()) return;
14800 
14801   // Require that the source be a pointer type.
14802   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14803   if (!SrcPtr) return;
14804   QualType SrcPointee = SrcPtr->getPointeeType();
14805 
14806   // Explicitly allow casts from cv void*.  We already implicitly
14807   // allowed casts to cv void*, since they have alignment 1.
14808   // Also allow casts involving incomplete types, which implicitly
14809   // includes 'void'.
14810   if (SrcPointee->isIncompleteType()) return;
14811 
14812   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14813 
14814   if (SrcAlign >= DestAlign) return;
14815 
14816   Diag(TRange.getBegin(), diag::warn_cast_align)
14817     << Op->getType() << T
14818     << static_cast<unsigned>(SrcAlign.getQuantity())
14819     << static_cast<unsigned>(DestAlign.getQuantity())
14820     << TRange << Op->getSourceRange();
14821 }
14822 
14823 /// Check whether this array fits the idiom of a size-one tail padded
14824 /// array member of a struct.
14825 ///
14826 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14827 /// commonly used to emulate flexible arrays in C89 code.
14828 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14829                                     const NamedDecl *ND) {
14830   if (Size != 1 || !ND) return false;
14831 
14832   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14833   if (!FD) return false;
14834 
14835   // Don't consider sizes resulting from macro expansions or template argument
14836   // substitution to form C89 tail-padded arrays.
14837 
14838   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14839   while (TInfo) {
14840     TypeLoc TL = TInfo->getTypeLoc();
14841     // Look through typedefs.
14842     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14843       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14844       TInfo = TDL->getTypeSourceInfo();
14845       continue;
14846     }
14847     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14848       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14849       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14850         return false;
14851     }
14852     break;
14853   }
14854 
14855   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14856   if (!RD) return false;
14857   if (RD->isUnion()) return false;
14858   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14859     if (!CRD->isStandardLayout()) return false;
14860   }
14861 
14862   // See if this is the last field decl in the record.
14863   const Decl *D = FD;
14864   while ((D = D->getNextDeclInContext()))
14865     if (isa<FieldDecl>(D))
14866       return false;
14867   return true;
14868 }
14869 
14870 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14871                             const ArraySubscriptExpr *ASE,
14872                             bool AllowOnePastEnd, bool IndexNegated) {
14873   // Already diagnosed by the constant evaluator.
14874   if (isConstantEvaluated())
14875     return;
14876 
14877   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14878   if (IndexExpr->isValueDependent())
14879     return;
14880 
14881   const Type *EffectiveType =
14882       BaseExpr->getType()->getPointeeOrArrayElementType();
14883   BaseExpr = BaseExpr->IgnoreParenCasts();
14884   const ConstantArrayType *ArrayTy =
14885       Context.getAsConstantArrayType(BaseExpr->getType());
14886 
14887   const Type *BaseType =
14888       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14889   bool IsUnboundedArray = (BaseType == nullptr);
14890   if (EffectiveType->isDependentType() ||
14891       (!IsUnboundedArray && BaseType->isDependentType()))
14892     return;
14893 
14894   Expr::EvalResult Result;
14895   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14896     return;
14897 
14898   llvm::APSInt index = Result.Val.getInt();
14899   if (IndexNegated) {
14900     index.setIsUnsigned(false);
14901     index = -index;
14902   }
14903 
14904   const NamedDecl *ND = nullptr;
14905   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14906     ND = DRE->getDecl();
14907   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14908     ND = ME->getMemberDecl();
14909 
14910   if (IsUnboundedArray) {
14911     if (index.isUnsigned() || !index.isNegative()) {
14912       const auto &ASTC = getASTContext();
14913       unsigned AddrBits =
14914           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14915               EffectiveType->getCanonicalTypeInternal()));
14916       if (index.getBitWidth() < AddrBits)
14917         index = index.zext(AddrBits);
14918       Optional<CharUnits> ElemCharUnits =
14919           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14920       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14921       // pointer) bounds-checking isn't meaningful.
14922       if (!ElemCharUnits)
14923         return;
14924       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14925       // If index has more active bits than address space, we already know
14926       // we have a bounds violation to warn about.  Otherwise, compute
14927       // address of (index + 1)th element, and warn about bounds violation
14928       // only if that address exceeds address space.
14929       if (index.getActiveBits() <= AddrBits) {
14930         bool Overflow;
14931         llvm::APInt Product(index);
14932         Product += 1;
14933         Product = Product.umul_ov(ElemBytes, Overflow);
14934         if (!Overflow && Product.getActiveBits() <= AddrBits)
14935           return;
14936       }
14937 
14938       // Need to compute max possible elements in address space, since that
14939       // is included in diag message.
14940       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14941       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14942       MaxElems += 1;
14943       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14944       MaxElems = MaxElems.udiv(ElemBytes);
14945 
14946       unsigned DiagID =
14947           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14948               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14949 
14950       // Diag message shows element size in bits and in "bytes" (platform-
14951       // dependent CharUnits)
14952       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14953                           PDiag(DiagID)
14954                               << toString(index, 10, true) << AddrBits
14955                               << (unsigned)ASTC.toBits(*ElemCharUnits)
14956                               << toString(ElemBytes, 10, false)
14957                               << toString(MaxElems, 10, false)
14958                               << (unsigned)MaxElems.getLimitedValue(~0U)
14959                               << IndexExpr->getSourceRange());
14960 
14961       if (!ND) {
14962         // Try harder to find a NamedDecl to point at in the note.
14963         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14964           BaseExpr = ASE->getBase()->IgnoreParenCasts();
14965         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14966           ND = DRE->getDecl();
14967         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14968           ND = ME->getMemberDecl();
14969       }
14970 
14971       if (ND)
14972         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14973                             PDiag(diag::note_array_declared_here) << ND);
14974     }
14975     return;
14976   }
14977 
14978   if (index.isUnsigned() || !index.isNegative()) {
14979     // It is possible that the type of the base expression after
14980     // IgnoreParenCasts is incomplete, even though the type of the base
14981     // expression before IgnoreParenCasts is complete (see PR39746 for an
14982     // example). In this case we have no information about whether the array
14983     // access exceeds the array bounds. However we can still diagnose an array
14984     // access which precedes the array bounds.
14985     if (BaseType->isIncompleteType())
14986       return;
14987 
14988     llvm::APInt size = ArrayTy->getSize();
14989     if (!size.isStrictlyPositive())
14990       return;
14991 
14992     if (BaseType != EffectiveType) {
14993       // Make sure we're comparing apples to apples when comparing index to size
14994       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14995       uint64_t array_typesize = Context.getTypeSize(BaseType);
14996       // Handle ptrarith_typesize being zero, such as when casting to void*
14997       if (!ptrarith_typesize) ptrarith_typesize = 1;
14998       if (ptrarith_typesize != array_typesize) {
14999         // There's a cast to a different size type involved
15000         uint64_t ratio = array_typesize / ptrarith_typesize;
15001         // TODO: Be smarter about handling cases where array_typesize is not a
15002         // multiple of ptrarith_typesize
15003         if (ptrarith_typesize * ratio == array_typesize)
15004           size *= llvm::APInt(size.getBitWidth(), ratio);
15005       }
15006     }
15007 
15008     if (size.getBitWidth() > index.getBitWidth())
15009       index = index.zext(size.getBitWidth());
15010     else if (size.getBitWidth() < index.getBitWidth())
15011       size = size.zext(index.getBitWidth());
15012 
15013     // For array subscripting the index must be less than size, but for pointer
15014     // arithmetic also allow the index (offset) to be equal to size since
15015     // computing the next address after the end of the array is legal and
15016     // commonly done e.g. in C++ iterators and range-based for loops.
15017     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15018       return;
15019 
15020     // Also don't warn for arrays of size 1 which are members of some
15021     // structure. These are often used to approximate flexible arrays in C89
15022     // code.
15023     if (IsTailPaddedMemberArray(*this, size, ND))
15024       return;
15025 
15026     // Suppress the warning if the subscript expression (as identified by the
15027     // ']' location) and the index expression are both from macro expansions
15028     // within a system header.
15029     if (ASE) {
15030       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15031           ASE->getRBracketLoc());
15032       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15033         SourceLocation IndexLoc =
15034             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15035         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15036           return;
15037       }
15038     }
15039 
15040     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15041                           : diag::warn_ptr_arith_exceeds_bounds;
15042 
15043     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15044                         PDiag(DiagID) << toString(index, 10, true)
15045                                       << toString(size, 10, true)
15046                                       << (unsigned)size.getLimitedValue(~0U)
15047                                       << IndexExpr->getSourceRange());
15048   } else {
15049     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15050     if (!ASE) {
15051       DiagID = diag::warn_ptr_arith_precedes_bounds;
15052       if (index.isNegative()) index = -index;
15053     }
15054 
15055     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15056                         PDiag(DiagID) << toString(index, 10, true)
15057                                       << IndexExpr->getSourceRange());
15058   }
15059 
15060   if (!ND) {
15061     // Try harder to find a NamedDecl to point at in the note.
15062     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15063       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15064     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15065       ND = DRE->getDecl();
15066     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15067       ND = ME->getMemberDecl();
15068   }
15069 
15070   if (ND)
15071     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15072                         PDiag(diag::note_array_declared_here) << ND);
15073 }
15074 
15075 void Sema::CheckArrayAccess(const Expr *expr) {
15076   int AllowOnePastEnd = 0;
15077   while (expr) {
15078     expr = expr->IgnoreParenImpCasts();
15079     switch (expr->getStmtClass()) {
15080       case Stmt::ArraySubscriptExprClass: {
15081         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15082         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15083                          AllowOnePastEnd > 0);
15084         expr = ASE->getBase();
15085         break;
15086       }
15087       case Stmt::MemberExprClass: {
15088         expr = cast<MemberExpr>(expr)->getBase();
15089         break;
15090       }
15091       case Stmt::OMPArraySectionExprClass: {
15092         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15093         if (ASE->getLowerBound())
15094           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15095                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15096         return;
15097       }
15098       case Stmt::UnaryOperatorClass: {
15099         // Only unwrap the * and & unary operators
15100         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15101         expr = UO->getSubExpr();
15102         switch (UO->getOpcode()) {
15103           case UO_AddrOf:
15104             AllowOnePastEnd++;
15105             break;
15106           case UO_Deref:
15107             AllowOnePastEnd--;
15108             break;
15109           default:
15110             return;
15111         }
15112         break;
15113       }
15114       case Stmt::ConditionalOperatorClass: {
15115         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15116         if (const Expr *lhs = cond->getLHS())
15117           CheckArrayAccess(lhs);
15118         if (const Expr *rhs = cond->getRHS())
15119           CheckArrayAccess(rhs);
15120         return;
15121       }
15122       case Stmt::CXXOperatorCallExprClass: {
15123         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15124         for (const auto *Arg : OCE->arguments())
15125           CheckArrayAccess(Arg);
15126         return;
15127       }
15128       default:
15129         return;
15130     }
15131   }
15132 }
15133 
15134 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15135 
15136 namespace {
15137 
15138 struct RetainCycleOwner {
15139   VarDecl *Variable = nullptr;
15140   SourceRange Range;
15141   SourceLocation Loc;
15142   bool Indirect = false;
15143 
15144   RetainCycleOwner() = default;
15145 
15146   void setLocsFrom(Expr *e) {
15147     Loc = e->getExprLoc();
15148     Range = e->getSourceRange();
15149   }
15150 };
15151 
15152 } // namespace
15153 
15154 /// Consider whether capturing the given variable can possibly lead to
15155 /// a retain cycle.
15156 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15157   // In ARC, it's captured strongly iff the variable has __strong
15158   // lifetime.  In MRR, it's captured strongly if the variable is
15159   // __block and has an appropriate type.
15160   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15161     return false;
15162 
15163   owner.Variable = var;
15164   if (ref)
15165     owner.setLocsFrom(ref);
15166   return true;
15167 }
15168 
15169 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15170   while (true) {
15171     e = e->IgnoreParens();
15172     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15173       switch (cast->getCastKind()) {
15174       case CK_BitCast:
15175       case CK_LValueBitCast:
15176       case CK_LValueToRValue:
15177       case CK_ARCReclaimReturnedObject:
15178         e = cast->getSubExpr();
15179         continue;
15180 
15181       default:
15182         return false;
15183       }
15184     }
15185 
15186     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15187       ObjCIvarDecl *ivar = ref->getDecl();
15188       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15189         return false;
15190 
15191       // Try to find a retain cycle in the base.
15192       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15193         return false;
15194 
15195       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15196       owner.Indirect = true;
15197       return true;
15198     }
15199 
15200     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15201       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15202       if (!var) return false;
15203       return considerVariable(var, ref, owner);
15204     }
15205 
15206     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15207       if (member->isArrow()) return false;
15208 
15209       // Don't count this as an indirect ownership.
15210       e = member->getBase();
15211       continue;
15212     }
15213 
15214     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15215       // Only pay attention to pseudo-objects on property references.
15216       ObjCPropertyRefExpr *pre
15217         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15218                                               ->IgnoreParens());
15219       if (!pre) return false;
15220       if (pre->isImplicitProperty()) return false;
15221       ObjCPropertyDecl *property = pre->getExplicitProperty();
15222       if (!property->isRetaining() &&
15223           !(property->getPropertyIvarDecl() &&
15224             property->getPropertyIvarDecl()->getType()
15225               .getObjCLifetime() == Qualifiers::OCL_Strong))
15226           return false;
15227 
15228       owner.Indirect = true;
15229       if (pre->isSuperReceiver()) {
15230         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15231         if (!owner.Variable)
15232           return false;
15233         owner.Loc = pre->getLocation();
15234         owner.Range = pre->getSourceRange();
15235         return true;
15236       }
15237       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15238                               ->getSourceExpr());
15239       continue;
15240     }
15241 
15242     // Array ivars?
15243 
15244     return false;
15245   }
15246 }
15247 
15248 namespace {
15249 
15250   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15251     ASTContext &Context;
15252     VarDecl *Variable;
15253     Expr *Capturer = nullptr;
15254     bool VarWillBeReased = false;
15255 
15256     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15257         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15258           Context(Context), Variable(variable) {}
15259 
15260     void VisitDeclRefExpr(DeclRefExpr *ref) {
15261       if (ref->getDecl() == Variable && !Capturer)
15262         Capturer = ref;
15263     }
15264 
15265     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15266       if (Capturer) return;
15267       Visit(ref->getBase());
15268       if (Capturer && ref->isFreeIvar())
15269         Capturer = ref;
15270     }
15271 
15272     void VisitBlockExpr(BlockExpr *block) {
15273       // Look inside nested blocks
15274       if (block->getBlockDecl()->capturesVariable(Variable))
15275         Visit(block->getBlockDecl()->getBody());
15276     }
15277 
15278     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15279       if (Capturer) return;
15280       if (OVE->getSourceExpr())
15281         Visit(OVE->getSourceExpr());
15282     }
15283 
15284     void VisitBinaryOperator(BinaryOperator *BinOp) {
15285       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15286         return;
15287       Expr *LHS = BinOp->getLHS();
15288       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15289         if (DRE->getDecl() != Variable)
15290           return;
15291         if (Expr *RHS = BinOp->getRHS()) {
15292           RHS = RHS->IgnoreParenCasts();
15293           Optional<llvm::APSInt> Value;
15294           VarWillBeReased =
15295               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15296                *Value == 0);
15297         }
15298       }
15299     }
15300   };
15301 
15302 } // namespace
15303 
15304 /// Check whether the given argument is a block which captures a
15305 /// variable.
15306 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15307   assert(owner.Variable && owner.Loc.isValid());
15308 
15309   e = e->IgnoreParenCasts();
15310 
15311   // Look through [^{...} copy] and Block_copy(^{...}).
15312   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15313     Selector Cmd = ME->getSelector();
15314     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15315       e = ME->getInstanceReceiver();
15316       if (!e)
15317         return nullptr;
15318       e = e->IgnoreParenCasts();
15319     }
15320   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15321     if (CE->getNumArgs() == 1) {
15322       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15323       if (Fn) {
15324         const IdentifierInfo *FnI = Fn->getIdentifier();
15325         if (FnI && FnI->isStr("_Block_copy")) {
15326           e = CE->getArg(0)->IgnoreParenCasts();
15327         }
15328       }
15329     }
15330   }
15331 
15332   BlockExpr *block = dyn_cast<BlockExpr>(e);
15333   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15334     return nullptr;
15335 
15336   FindCaptureVisitor visitor(S.Context, owner.Variable);
15337   visitor.Visit(block->getBlockDecl()->getBody());
15338   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15339 }
15340 
15341 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15342                                 RetainCycleOwner &owner) {
15343   assert(capturer);
15344   assert(owner.Variable && owner.Loc.isValid());
15345 
15346   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15347     << owner.Variable << capturer->getSourceRange();
15348   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15349     << owner.Indirect << owner.Range;
15350 }
15351 
15352 /// Check for a keyword selector that starts with the word 'add' or
15353 /// 'set'.
15354 static bool isSetterLikeSelector(Selector sel) {
15355   if (sel.isUnarySelector()) return false;
15356 
15357   StringRef str = sel.getNameForSlot(0);
15358   while (!str.empty() && str.front() == '_') str = str.substr(1);
15359   if (str.startswith("set"))
15360     str = str.substr(3);
15361   else if (str.startswith("add")) {
15362     // Specially allow 'addOperationWithBlock:'.
15363     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15364       return false;
15365     str = str.substr(3);
15366   }
15367   else
15368     return false;
15369 
15370   if (str.empty()) return true;
15371   return !isLowercase(str.front());
15372 }
15373 
15374 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15375                                                     ObjCMessageExpr *Message) {
15376   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15377                                                 Message->getReceiverInterface(),
15378                                                 NSAPI::ClassId_NSMutableArray);
15379   if (!IsMutableArray) {
15380     return None;
15381   }
15382 
15383   Selector Sel = Message->getSelector();
15384 
15385   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15386     S.NSAPIObj->getNSArrayMethodKind(Sel);
15387   if (!MKOpt) {
15388     return None;
15389   }
15390 
15391   NSAPI::NSArrayMethodKind MK = *MKOpt;
15392 
15393   switch (MK) {
15394     case NSAPI::NSMutableArr_addObject:
15395     case NSAPI::NSMutableArr_insertObjectAtIndex:
15396     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15397       return 0;
15398     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15399       return 1;
15400 
15401     default:
15402       return None;
15403   }
15404 
15405   return None;
15406 }
15407 
15408 static
15409 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15410                                                   ObjCMessageExpr *Message) {
15411   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15412                                             Message->getReceiverInterface(),
15413                                             NSAPI::ClassId_NSMutableDictionary);
15414   if (!IsMutableDictionary) {
15415     return None;
15416   }
15417 
15418   Selector Sel = Message->getSelector();
15419 
15420   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15421     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15422   if (!MKOpt) {
15423     return None;
15424   }
15425 
15426   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15427 
15428   switch (MK) {
15429     case NSAPI::NSMutableDict_setObjectForKey:
15430     case NSAPI::NSMutableDict_setValueForKey:
15431     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15432       return 0;
15433 
15434     default:
15435       return None;
15436   }
15437 
15438   return None;
15439 }
15440 
15441 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15442   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15443                                                 Message->getReceiverInterface(),
15444                                                 NSAPI::ClassId_NSMutableSet);
15445 
15446   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15447                                             Message->getReceiverInterface(),
15448                                             NSAPI::ClassId_NSMutableOrderedSet);
15449   if (!IsMutableSet && !IsMutableOrderedSet) {
15450     return None;
15451   }
15452 
15453   Selector Sel = Message->getSelector();
15454 
15455   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15456   if (!MKOpt) {
15457     return None;
15458   }
15459 
15460   NSAPI::NSSetMethodKind MK = *MKOpt;
15461 
15462   switch (MK) {
15463     case NSAPI::NSMutableSet_addObject:
15464     case NSAPI::NSOrderedSet_setObjectAtIndex:
15465     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15466     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15467       return 0;
15468     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15469       return 1;
15470   }
15471 
15472   return None;
15473 }
15474 
15475 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15476   if (!Message->isInstanceMessage()) {
15477     return;
15478   }
15479 
15480   Optional<int> ArgOpt;
15481 
15482   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15483       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15484       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15485     return;
15486   }
15487 
15488   int ArgIndex = *ArgOpt;
15489 
15490   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15491   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15492     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15493   }
15494 
15495   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15496     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15497       if (ArgRE->isObjCSelfExpr()) {
15498         Diag(Message->getSourceRange().getBegin(),
15499              diag::warn_objc_circular_container)
15500           << ArgRE->getDecl() << StringRef("'super'");
15501       }
15502     }
15503   } else {
15504     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15505 
15506     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15507       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15508     }
15509 
15510     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15511       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15512         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15513           ValueDecl *Decl = ReceiverRE->getDecl();
15514           Diag(Message->getSourceRange().getBegin(),
15515                diag::warn_objc_circular_container)
15516             << Decl << Decl;
15517           if (!ArgRE->isObjCSelfExpr()) {
15518             Diag(Decl->getLocation(),
15519                  diag::note_objc_circular_container_declared_here)
15520               << Decl;
15521           }
15522         }
15523       }
15524     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15525       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15526         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15527           ObjCIvarDecl *Decl = IvarRE->getDecl();
15528           Diag(Message->getSourceRange().getBegin(),
15529                diag::warn_objc_circular_container)
15530             << Decl << Decl;
15531           Diag(Decl->getLocation(),
15532                diag::note_objc_circular_container_declared_here)
15533             << Decl;
15534         }
15535       }
15536     }
15537   }
15538 }
15539 
15540 /// Check a message send to see if it's likely to cause a retain cycle.
15541 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15542   // Only check instance methods whose selector looks like a setter.
15543   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15544     return;
15545 
15546   // Try to find a variable that the receiver is strongly owned by.
15547   RetainCycleOwner owner;
15548   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15549     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15550       return;
15551   } else {
15552     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15553     owner.Variable = getCurMethodDecl()->getSelfDecl();
15554     owner.Loc = msg->getSuperLoc();
15555     owner.Range = msg->getSuperLoc();
15556   }
15557 
15558   // Check whether the receiver is captured by any of the arguments.
15559   const ObjCMethodDecl *MD = msg->getMethodDecl();
15560   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15561     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15562       // noescape blocks should not be retained by the method.
15563       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15564         continue;
15565       return diagnoseRetainCycle(*this, capturer, owner);
15566     }
15567   }
15568 }
15569 
15570 /// Check a property assign to see if it's likely to cause a retain cycle.
15571 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15572   RetainCycleOwner owner;
15573   if (!findRetainCycleOwner(*this, receiver, owner))
15574     return;
15575 
15576   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15577     diagnoseRetainCycle(*this, capturer, owner);
15578 }
15579 
15580 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15581   RetainCycleOwner Owner;
15582   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15583     return;
15584 
15585   // Because we don't have an expression for the variable, we have to set the
15586   // location explicitly here.
15587   Owner.Loc = Var->getLocation();
15588   Owner.Range = Var->getSourceRange();
15589 
15590   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15591     diagnoseRetainCycle(*this, Capturer, Owner);
15592 }
15593 
15594 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15595                                      Expr *RHS, bool isProperty) {
15596   // Check if RHS is an Objective-C object literal, which also can get
15597   // immediately zapped in a weak reference.  Note that we explicitly
15598   // allow ObjCStringLiterals, since those are designed to never really die.
15599   RHS = RHS->IgnoreParenImpCasts();
15600 
15601   // This enum needs to match with the 'select' in
15602   // warn_objc_arc_literal_assign (off-by-1).
15603   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15604   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15605     return false;
15606 
15607   S.Diag(Loc, diag::warn_arc_literal_assign)
15608     << (unsigned) Kind
15609     << (isProperty ? 0 : 1)
15610     << RHS->getSourceRange();
15611 
15612   return true;
15613 }
15614 
15615 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15616                                     Qualifiers::ObjCLifetime LT,
15617                                     Expr *RHS, bool isProperty) {
15618   // Strip off any implicit cast added to get to the one ARC-specific.
15619   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15620     if (cast->getCastKind() == CK_ARCConsumeObject) {
15621       S.Diag(Loc, diag::warn_arc_retained_assign)
15622         << (LT == Qualifiers::OCL_ExplicitNone)
15623         << (isProperty ? 0 : 1)
15624         << RHS->getSourceRange();
15625       return true;
15626     }
15627     RHS = cast->getSubExpr();
15628   }
15629 
15630   if (LT == Qualifiers::OCL_Weak &&
15631       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15632     return true;
15633 
15634   return false;
15635 }
15636 
15637 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15638                               QualType LHS, Expr *RHS) {
15639   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15640 
15641   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15642     return false;
15643 
15644   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15645     return true;
15646 
15647   return false;
15648 }
15649 
15650 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15651                               Expr *LHS, Expr *RHS) {
15652   QualType LHSType;
15653   // PropertyRef on LHS type need be directly obtained from
15654   // its declaration as it has a PseudoType.
15655   ObjCPropertyRefExpr *PRE
15656     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15657   if (PRE && !PRE->isImplicitProperty()) {
15658     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15659     if (PD)
15660       LHSType = PD->getType();
15661   }
15662 
15663   if (LHSType.isNull())
15664     LHSType = LHS->getType();
15665 
15666   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15667 
15668   if (LT == Qualifiers::OCL_Weak) {
15669     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15670       getCurFunction()->markSafeWeakUse(LHS);
15671   }
15672 
15673   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15674     return;
15675 
15676   // FIXME. Check for other life times.
15677   if (LT != Qualifiers::OCL_None)
15678     return;
15679 
15680   if (PRE) {
15681     if (PRE->isImplicitProperty())
15682       return;
15683     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15684     if (!PD)
15685       return;
15686 
15687     unsigned Attributes = PD->getPropertyAttributes();
15688     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15689       // when 'assign' attribute was not explicitly specified
15690       // by user, ignore it and rely on property type itself
15691       // for lifetime info.
15692       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15693       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15694           LHSType->isObjCRetainableType())
15695         return;
15696 
15697       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15698         if (cast->getCastKind() == CK_ARCConsumeObject) {
15699           Diag(Loc, diag::warn_arc_retained_property_assign)
15700           << RHS->getSourceRange();
15701           return;
15702         }
15703         RHS = cast->getSubExpr();
15704       }
15705     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15706       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15707         return;
15708     }
15709   }
15710 }
15711 
15712 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15713 
15714 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15715                                         SourceLocation StmtLoc,
15716                                         const NullStmt *Body) {
15717   // Do not warn if the body is a macro that expands to nothing, e.g:
15718   //
15719   // #define CALL(x)
15720   // if (condition)
15721   //   CALL(0);
15722   if (Body->hasLeadingEmptyMacro())
15723     return false;
15724 
15725   // Get line numbers of statement and body.
15726   bool StmtLineInvalid;
15727   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15728                                                       &StmtLineInvalid);
15729   if (StmtLineInvalid)
15730     return false;
15731 
15732   bool BodyLineInvalid;
15733   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15734                                                       &BodyLineInvalid);
15735   if (BodyLineInvalid)
15736     return false;
15737 
15738   // Warn if null statement and body are on the same line.
15739   if (StmtLine != BodyLine)
15740     return false;
15741 
15742   return true;
15743 }
15744 
15745 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15746                                  const Stmt *Body,
15747                                  unsigned DiagID) {
15748   // Since this is a syntactic check, don't emit diagnostic for template
15749   // instantiations, this just adds noise.
15750   if (CurrentInstantiationScope)
15751     return;
15752 
15753   // The body should be a null statement.
15754   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15755   if (!NBody)
15756     return;
15757 
15758   // Do the usual checks.
15759   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15760     return;
15761 
15762   Diag(NBody->getSemiLoc(), DiagID);
15763   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15764 }
15765 
15766 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15767                                  const Stmt *PossibleBody) {
15768   assert(!CurrentInstantiationScope); // Ensured by caller
15769 
15770   SourceLocation StmtLoc;
15771   const Stmt *Body;
15772   unsigned DiagID;
15773   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15774     StmtLoc = FS->getRParenLoc();
15775     Body = FS->getBody();
15776     DiagID = diag::warn_empty_for_body;
15777   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15778     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15779     Body = WS->getBody();
15780     DiagID = diag::warn_empty_while_body;
15781   } else
15782     return; // Neither `for' nor `while'.
15783 
15784   // The body should be a null statement.
15785   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15786   if (!NBody)
15787     return;
15788 
15789   // Skip expensive checks if diagnostic is disabled.
15790   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15791     return;
15792 
15793   // Do the usual checks.
15794   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15795     return;
15796 
15797   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15798   // noise level low, emit diagnostics only if for/while is followed by a
15799   // CompoundStmt, e.g.:
15800   //    for (int i = 0; i < n; i++);
15801   //    {
15802   //      a(i);
15803   //    }
15804   // or if for/while is followed by a statement with more indentation
15805   // than for/while itself:
15806   //    for (int i = 0; i < n; i++);
15807   //      a(i);
15808   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15809   if (!ProbableTypo) {
15810     bool BodyColInvalid;
15811     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15812         PossibleBody->getBeginLoc(), &BodyColInvalid);
15813     if (BodyColInvalid)
15814       return;
15815 
15816     bool StmtColInvalid;
15817     unsigned StmtCol =
15818         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15819     if (StmtColInvalid)
15820       return;
15821 
15822     if (BodyCol > StmtCol)
15823       ProbableTypo = true;
15824   }
15825 
15826   if (ProbableTypo) {
15827     Diag(NBody->getSemiLoc(), DiagID);
15828     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15829   }
15830 }
15831 
15832 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15833 
15834 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15835 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15836                              SourceLocation OpLoc) {
15837   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15838     return;
15839 
15840   if (inTemplateInstantiation())
15841     return;
15842 
15843   // Strip parens and casts away.
15844   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15845   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15846 
15847   // Check for a call expression
15848   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15849   if (!CE || CE->getNumArgs() != 1)
15850     return;
15851 
15852   // Check for a call to std::move
15853   if (!CE->isCallToStdMove())
15854     return;
15855 
15856   // Get argument from std::move
15857   RHSExpr = CE->getArg(0);
15858 
15859   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15860   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15861 
15862   // Two DeclRefExpr's, check that the decls are the same.
15863   if (LHSDeclRef && RHSDeclRef) {
15864     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15865       return;
15866     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15867         RHSDeclRef->getDecl()->getCanonicalDecl())
15868       return;
15869 
15870     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15871                                         << LHSExpr->getSourceRange()
15872                                         << RHSExpr->getSourceRange();
15873     return;
15874   }
15875 
15876   // Member variables require a different approach to check for self moves.
15877   // MemberExpr's are the same if every nested MemberExpr refers to the same
15878   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15879   // the base Expr's are CXXThisExpr's.
15880   const Expr *LHSBase = LHSExpr;
15881   const Expr *RHSBase = RHSExpr;
15882   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15883   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15884   if (!LHSME || !RHSME)
15885     return;
15886 
15887   while (LHSME && RHSME) {
15888     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15889         RHSME->getMemberDecl()->getCanonicalDecl())
15890       return;
15891 
15892     LHSBase = LHSME->getBase();
15893     RHSBase = RHSME->getBase();
15894     LHSME = dyn_cast<MemberExpr>(LHSBase);
15895     RHSME = dyn_cast<MemberExpr>(RHSBase);
15896   }
15897 
15898   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15899   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15900   if (LHSDeclRef && RHSDeclRef) {
15901     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15902       return;
15903     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15904         RHSDeclRef->getDecl()->getCanonicalDecl())
15905       return;
15906 
15907     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15908                                         << LHSExpr->getSourceRange()
15909                                         << RHSExpr->getSourceRange();
15910     return;
15911   }
15912 
15913   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15914     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15915                                         << LHSExpr->getSourceRange()
15916                                         << RHSExpr->getSourceRange();
15917 }
15918 
15919 //===--- Layout compatibility ----------------------------------------------//
15920 
15921 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15922 
15923 /// Check if two enumeration types are layout-compatible.
15924 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15925   // C++11 [dcl.enum] p8:
15926   // Two enumeration types are layout-compatible if they have the same
15927   // underlying type.
15928   return ED1->isComplete() && ED2->isComplete() &&
15929          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15930 }
15931 
15932 /// Check if two fields are layout-compatible.
15933 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15934                                FieldDecl *Field2) {
15935   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15936     return false;
15937 
15938   if (Field1->isBitField() != Field2->isBitField())
15939     return false;
15940 
15941   if (Field1->isBitField()) {
15942     // Make sure that the bit-fields are the same length.
15943     unsigned Bits1 = Field1->getBitWidthValue(C);
15944     unsigned Bits2 = Field2->getBitWidthValue(C);
15945 
15946     if (Bits1 != Bits2)
15947       return false;
15948   }
15949 
15950   return true;
15951 }
15952 
15953 /// Check if two standard-layout structs are layout-compatible.
15954 /// (C++11 [class.mem] p17)
15955 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15956                                      RecordDecl *RD2) {
15957   // If both records are C++ classes, check that base classes match.
15958   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15959     // If one of records is a CXXRecordDecl we are in C++ mode,
15960     // thus the other one is a CXXRecordDecl, too.
15961     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15962     // Check number of base classes.
15963     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15964       return false;
15965 
15966     // Check the base classes.
15967     for (CXXRecordDecl::base_class_const_iterator
15968                Base1 = D1CXX->bases_begin(),
15969            BaseEnd1 = D1CXX->bases_end(),
15970               Base2 = D2CXX->bases_begin();
15971          Base1 != BaseEnd1;
15972          ++Base1, ++Base2) {
15973       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15974         return false;
15975     }
15976   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15977     // If only RD2 is a C++ class, it should have zero base classes.
15978     if (D2CXX->getNumBases() > 0)
15979       return false;
15980   }
15981 
15982   // Check the fields.
15983   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15984                              Field2End = RD2->field_end(),
15985                              Field1 = RD1->field_begin(),
15986                              Field1End = RD1->field_end();
15987   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15988     if (!isLayoutCompatible(C, *Field1, *Field2))
15989       return false;
15990   }
15991   if (Field1 != Field1End || Field2 != Field2End)
15992     return false;
15993 
15994   return true;
15995 }
15996 
15997 /// Check if two standard-layout unions are layout-compatible.
15998 /// (C++11 [class.mem] p18)
15999 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16000                                     RecordDecl *RD2) {
16001   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16002   for (auto *Field2 : RD2->fields())
16003     UnmatchedFields.insert(Field2);
16004 
16005   for (auto *Field1 : RD1->fields()) {
16006     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16007         I = UnmatchedFields.begin(),
16008         E = UnmatchedFields.end();
16009 
16010     for ( ; I != E; ++I) {
16011       if (isLayoutCompatible(C, Field1, *I)) {
16012         bool Result = UnmatchedFields.erase(*I);
16013         (void) Result;
16014         assert(Result);
16015         break;
16016       }
16017     }
16018     if (I == E)
16019       return false;
16020   }
16021 
16022   return UnmatchedFields.empty();
16023 }
16024 
16025 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16026                                RecordDecl *RD2) {
16027   if (RD1->isUnion() != RD2->isUnion())
16028     return false;
16029 
16030   if (RD1->isUnion())
16031     return isLayoutCompatibleUnion(C, RD1, RD2);
16032   else
16033     return isLayoutCompatibleStruct(C, RD1, RD2);
16034 }
16035 
16036 /// Check if two types are layout-compatible in C++11 sense.
16037 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16038   if (T1.isNull() || T2.isNull())
16039     return false;
16040 
16041   // C++11 [basic.types] p11:
16042   // If two types T1 and T2 are the same type, then T1 and T2 are
16043   // layout-compatible types.
16044   if (C.hasSameType(T1, T2))
16045     return true;
16046 
16047   T1 = T1.getCanonicalType().getUnqualifiedType();
16048   T2 = T2.getCanonicalType().getUnqualifiedType();
16049 
16050   const Type::TypeClass TC1 = T1->getTypeClass();
16051   const Type::TypeClass TC2 = T2->getTypeClass();
16052 
16053   if (TC1 != TC2)
16054     return false;
16055 
16056   if (TC1 == Type::Enum) {
16057     return isLayoutCompatible(C,
16058                               cast<EnumType>(T1)->getDecl(),
16059                               cast<EnumType>(T2)->getDecl());
16060   } else if (TC1 == Type::Record) {
16061     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16062       return false;
16063 
16064     return isLayoutCompatible(C,
16065                               cast<RecordType>(T1)->getDecl(),
16066                               cast<RecordType>(T2)->getDecl());
16067   }
16068 
16069   return false;
16070 }
16071 
16072 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16073 
16074 /// Given a type tag expression find the type tag itself.
16075 ///
16076 /// \param TypeExpr Type tag expression, as it appears in user's code.
16077 ///
16078 /// \param VD Declaration of an identifier that appears in a type tag.
16079 ///
16080 /// \param MagicValue Type tag magic value.
16081 ///
16082 /// \param isConstantEvaluated whether the evalaution should be performed in
16083 
16084 /// constant context.
16085 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16086                             const ValueDecl **VD, uint64_t *MagicValue,
16087                             bool isConstantEvaluated) {
16088   while(true) {
16089     if (!TypeExpr)
16090       return false;
16091 
16092     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16093 
16094     switch (TypeExpr->getStmtClass()) {
16095     case Stmt::UnaryOperatorClass: {
16096       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16097       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16098         TypeExpr = UO->getSubExpr();
16099         continue;
16100       }
16101       return false;
16102     }
16103 
16104     case Stmt::DeclRefExprClass: {
16105       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16106       *VD = DRE->getDecl();
16107       return true;
16108     }
16109 
16110     case Stmt::IntegerLiteralClass: {
16111       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16112       llvm::APInt MagicValueAPInt = IL->getValue();
16113       if (MagicValueAPInt.getActiveBits() <= 64) {
16114         *MagicValue = MagicValueAPInt.getZExtValue();
16115         return true;
16116       } else
16117         return false;
16118     }
16119 
16120     case Stmt::BinaryConditionalOperatorClass:
16121     case Stmt::ConditionalOperatorClass: {
16122       const AbstractConditionalOperator *ACO =
16123           cast<AbstractConditionalOperator>(TypeExpr);
16124       bool Result;
16125       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16126                                                      isConstantEvaluated)) {
16127         if (Result)
16128           TypeExpr = ACO->getTrueExpr();
16129         else
16130           TypeExpr = ACO->getFalseExpr();
16131         continue;
16132       }
16133       return false;
16134     }
16135 
16136     case Stmt::BinaryOperatorClass: {
16137       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16138       if (BO->getOpcode() == BO_Comma) {
16139         TypeExpr = BO->getRHS();
16140         continue;
16141       }
16142       return false;
16143     }
16144 
16145     default:
16146       return false;
16147     }
16148   }
16149 }
16150 
16151 /// Retrieve the C type corresponding to type tag TypeExpr.
16152 ///
16153 /// \param TypeExpr Expression that specifies a type tag.
16154 ///
16155 /// \param MagicValues Registered magic values.
16156 ///
16157 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16158 ///        kind.
16159 ///
16160 /// \param TypeInfo Information about the corresponding C type.
16161 ///
16162 /// \param isConstantEvaluated whether the evalaution should be performed in
16163 /// constant context.
16164 ///
16165 /// \returns true if the corresponding C type was found.
16166 static bool GetMatchingCType(
16167     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16168     const ASTContext &Ctx,
16169     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16170         *MagicValues,
16171     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16172     bool isConstantEvaluated) {
16173   FoundWrongKind = false;
16174 
16175   // Variable declaration that has type_tag_for_datatype attribute.
16176   const ValueDecl *VD = nullptr;
16177 
16178   uint64_t MagicValue;
16179 
16180   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16181     return false;
16182 
16183   if (VD) {
16184     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16185       if (I->getArgumentKind() != ArgumentKind) {
16186         FoundWrongKind = true;
16187         return false;
16188       }
16189       TypeInfo.Type = I->getMatchingCType();
16190       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16191       TypeInfo.MustBeNull = I->getMustBeNull();
16192       return true;
16193     }
16194     return false;
16195   }
16196 
16197   if (!MagicValues)
16198     return false;
16199 
16200   llvm::DenseMap<Sema::TypeTagMagicValue,
16201                  Sema::TypeTagData>::const_iterator I =
16202       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16203   if (I == MagicValues->end())
16204     return false;
16205 
16206   TypeInfo = I->second;
16207   return true;
16208 }
16209 
16210 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16211                                       uint64_t MagicValue, QualType Type,
16212                                       bool LayoutCompatible,
16213                                       bool MustBeNull) {
16214   if (!TypeTagForDatatypeMagicValues)
16215     TypeTagForDatatypeMagicValues.reset(
16216         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16217 
16218   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16219   (*TypeTagForDatatypeMagicValues)[Magic] =
16220       TypeTagData(Type, LayoutCompatible, MustBeNull);
16221 }
16222 
16223 static bool IsSameCharType(QualType T1, QualType T2) {
16224   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16225   if (!BT1)
16226     return false;
16227 
16228   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16229   if (!BT2)
16230     return false;
16231 
16232   BuiltinType::Kind T1Kind = BT1->getKind();
16233   BuiltinType::Kind T2Kind = BT2->getKind();
16234 
16235   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16236          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16237          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16238          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16239 }
16240 
16241 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16242                                     const ArrayRef<const Expr *> ExprArgs,
16243                                     SourceLocation CallSiteLoc) {
16244   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16245   bool IsPointerAttr = Attr->getIsPointer();
16246 
16247   // Retrieve the argument representing the 'type_tag'.
16248   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16249   if (TypeTagIdxAST >= ExprArgs.size()) {
16250     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16251         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16252     return;
16253   }
16254   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16255   bool FoundWrongKind;
16256   TypeTagData TypeInfo;
16257   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16258                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16259                         TypeInfo, isConstantEvaluated())) {
16260     if (FoundWrongKind)
16261       Diag(TypeTagExpr->getExprLoc(),
16262            diag::warn_type_tag_for_datatype_wrong_kind)
16263         << TypeTagExpr->getSourceRange();
16264     return;
16265   }
16266 
16267   // Retrieve the argument representing the 'arg_idx'.
16268   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16269   if (ArgumentIdxAST >= ExprArgs.size()) {
16270     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16271         << 1 << Attr->getArgumentIdx().getSourceIndex();
16272     return;
16273   }
16274   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16275   if (IsPointerAttr) {
16276     // Skip implicit cast of pointer to `void *' (as a function argument).
16277     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16278       if (ICE->getType()->isVoidPointerType() &&
16279           ICE->getCastKind() == CK_BitCast)
16280         ArgumentExpr = ICE->getSubExpr();
16281   }
16282   QualType ArgumentType = ArgumentExpr->getType();
16283 
16284   // Passing a `void*' pointer shouldn't trigger a warning.
16285   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16286     return;
16287 
16288   if (TypeInfo.MustBeNull) {
16289     // Type tag with matching void type requires a null pointer.
16290     if (!ArgumentExpr->isNullPointerConstant(Context,
16291                                              Expr::NPC_ValueDependentIsNotNull)) {
16292       Diag(ArgumentExpr->getExprLoc(),
16293            diag::warn_type_safety_null_pointer_required)
16294           << ArgumentKind->getName()
16295           << ArgumentExpr->getSourceRange()
16296           << TypeTagExpr->getSourceRange();
16297     }
16298     return;
16299   }
16300 
16301   QualType RequiredType = TypeInfo.Type;
16302   if (IsPointerAttr)
16303     RequiredType = Context.getPointerType(RequiredType);
16304 
16305   bool mismatch = false;
16306   if (!TypeInfo.LayoutCompatible) {
16307     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16308 
16309     // C++11 [basic.fundamental] p1:
16310     // Plain char, signed char, and unsigned char are three distinct types.
16311     //
16312     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16313     // char' depending on the current char signedness mode.
16314     if (mismatch)
16315       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16316                                            RequiredType->getPointeeType())) ||
16317           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16318         mismatch = false;
16319   } else
16320     if (IsPointerAttr)
16321       mismatch = !isLayoutCompatible(Context,
16322                                      ArgumentType->getPointeeType(),
16323                                      RequiredType->getPointeeType());
16324     else
16325       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16326 
16327   if (mismatch)
16328     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16329         << ArgumentType << ArgumentKind
16330         << TypeInfo.LayoutCompatible << RequiredType
16331         << ArgumentExpr->getSourceRange()
16332         << TypeTagExpr->getSourceRange();
16333 }
16334 
16335 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16336                                          CharUnits Alignment) {
16337   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16338 }
16339 
16340 void Sema::DiagnoseMisalignedMembers() {
16341   for (MisalignedMember &m : MisalignedMembers) {
16342     const NamedDecl *ND = m.RD;
16343     if (ND->getName().empty()) {
16344       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16345         ND = TD;
16346     }
16347     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16348         << m.MD << ND << m.E->getSourceRange();
16349   }
16350   MisalignedMembers.clear();
16351 }
16352 
16353 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16354   E = E->IgnoreParens();
16355   if (!T->isPointerType() && !T->isIntegerType())
16356     return;
16357   if (isa<UnaryOperator>(E) &&
16358       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16359     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16360     if (isa<MemberExpr>(Op)) {
16361       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16362       if (MA != MisalignedMembers.end() &&
16363           (T->isIntegerType() ||
16364            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16365                                    Context.getTypeAlignInChars(
16366                                        T->getPointeeType()) <= MA->Alignment))))
16367         MisalignedMembers.erase(MA);
16368     }
16369   }
16370 }
16371 
16372 void Sema::RefersToMemberWithReducedAlignment(
16373     Expr *E,
16374     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16375         Action) {
16376   const auto *ME = dyn_cast<MemberExpr>(E);
16377   if (!ME)
16378     return;
16379 
16380   // No need to check expressions with an __unaligned-qualified type.
16381   if (E->getType().getQualifiers().hasUnaligned())
16382     return;
16383 
16384   // For a chain of MemberExpr like "a.b.c.d" this list
16385   // will keep FieldDecl's like [d, c, b].
16386   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16387   const MemberExpr *TopME = nullptr;
16388   bool AnyIsPacked = false;
16389   do {
16390     QualType BaseType = ME->getBase()->getType();
16391     if (BaseType->isDependentType())
16392       return;
16393     if (ME->isArrow())
16394       BaseType = BaseType->getPointeeType();
16395     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16396     if (RD->isInvalidDecl())
16397       return;
16398 
16399     ValueDecl *MD = ME->getMemberDecl();
16400     auto *FD = dyn_cast<FieldDecl>(MD);
16401     // We do not care about non-data members.
16402     if (!FD || FD->isInvalidDecl())
16403       return;
16404 
16405     AnyIsPacked =
16406         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16407     ReverseMemberChain.push_back(FD);
16408 
16409     TopME = ME;
16410     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16411   } while (ME);
16412   assert(TopME && "We did not compute a topmost MemberExpr!");
16413 
16414   // Not the scope of this diagnostic.
16415   if (!AnyIsPacked)
16416     return;
16417 
16418   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16419   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16420   // TODO: The innermost base of the member expression may be too complicated.
16421   // For now, just disregard these cases. This is left for future
16422   // improvement.
16423   if (!DRE && !isa<CXXThisExpr>(TopBase))
16424       return;
16425 
16426   // Alignment expected by the whole expression.
16427   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16428 
16429   // No need to do anything else with this case.
16430   if (ExpectedAlignment.isOne())
16431     return;
16432 
16433   // Synthesize offset of the whole access.
16434   CharUnits Offset;
16435   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16436        I++) {
16437     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16438   }
16439 
16440   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16441   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16442       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16443 
16444   // The base expression of the innermost MemberExpr may give
16445   // stronger guarantees than the class containing the member.
16446   if (DRE && !TopME->isArrow()) {
16447     const ValueDecl *VD = DRE->getDecl();
16448     if (!VD->getType()->isReferenceType())
16449       CompleteObjectAlignment =
16450           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16451   }
16452 
16453   // Check if the synthesized offset fulfills the alignment.
16454   if (Offset % ExpectedAlignment != 0 ||
16455       // It may fulfill the offset it but the effective alignment may still be
16456       // lower than the expected expression alignment.
16457       CompleteObjectAlignment < ExpectedAlignment) {
16458     // If this happens, we want to determine a sensible culprit of this.
16459     // Intuitively, watching the chain of member expressions from right to
16460     // left, we start with the required alignment (as required by the field
16461     // type) but some packed attribute in that chain has reduced the alignment.
16462     // It may happen that another packed structure increases it again. But if
16463     // we are here such increase has not been enough. So pointing the first
16464     // FieldDecl that either is packed or else its RecordDecl is,
16465     // seems reasonable.
16466     FieldDecl *FD = nullptr;
16467     CharUnits Alignment;
16468     for (FieldDecl *FDI : ReverseMemberChain) {
16469       if (FDI->hasAttr<PackedAttr>() ||
16470           FDI->getParent()->hasAttr<PackedAttr>()) {
16471         FD = FDI;
16472         Alignment = std::min(
16473             Context.getTypeAlignInChars(FD->getType()),
16474             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16475         break;
16476       }
16477     }
16478     assert(FD && "We did not find a packed FieldDecl!");
16479     Action(E, FD->getParent(), FD, Alignment);
16480   }
16481 }
16482 
16483 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16484   using namespace std::placeholders;
16485 
16486   RefersToMemberWithReducedAlignment(
16487       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16488                      _2, _3, _4));
16489 }
16490 
16491 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16492                                             ExprResult CallResult) {
16493   if (checkArgCount(*this, TheCall, 1))
16494     return ExprError();
16495 
16496   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16497   if (MatrixArg.isInvalid())
16498     return MatrixArg;
16499   Expr *Matrix = MatrixArg.get();
16500 
16501   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16502   if (!MType) {
16503     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16504     return ExprError();
16505   }
16506 
16507   // Create returned matrix type by swapping rows and columns of the argument
16508   // matrix type.
16509   QualType ResultType = Context.getConstantMatrixType(
16510       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16511 
16512   // Change the return type to the type of the returned matrix.
16513   TheCall->setType(ResultType);
16514 
16515   // Update call argument to use the possibly converted matrix argument.
16516   TheCall->setArg(0, Matrix);
16517   return CallResult;
16518 }
16519 
16520 // Get and verify the matrix dimensions.
16521 static llvm::Optional<unsigned>
16522 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16523   SourceLocation ErrorPos;
16524   Optional<llvm::APSInt> Value =
16525       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16526   if (!Value) {
16527     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16528         << Name;
16529     return {};
16530   }
16531   uint64_t Dim = Value->getZExtValue();
16532   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16533     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16534         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16535     return {};
16536   }
16537   return Dim;
16538 }
16539 
16540 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16541                                                   ExprResult CallResult) {
16542   if (!getLangOpts().MatrixTypes) {
16543     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16544     return ExprError();
16545   }
16546 
16547   if (checkArgCount(*this, TheCall, 4))
16548     return ExprError();
16549 
16550   unsigned PtrArgIdx = 0;
16551   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16552   Expr *RowsExpr = TheCall->getArg(1);
16553   Expr *ColumnsExpr = TheCall->getArg(2);
16554   Expr *StrideExpr = TheCall->getArg(3);
16555 
16556   bool ArgError = false;
16557 
16558   // Check pointer argument.
16559   {
16560     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16561     if (PtrConv.isInvalid())
16562       return PtrConv;
16563     PtrExpr = PtrConv.get();
16564     TheCall->setArg(0, PtrExpr);
16565     if (PtrExpr->isTypeDependent()) {
16566       TheCall->setType(Context.DependentTy);
16567       return TheCall;
16568     }
16569   }
16570 
16571   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16572   QualType ElementTy;
16573   if (!PtrTy) {
16574     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16575         << PtrArgIdx + 1;
16576     ArgError = true;
16577   } else {
16578     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16579 
16580     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16581       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16582           << PtrArgIdx + 1;
16583       ArgError = true;
16584     }
16585   }
16586 
16587   // Apply default Lvalue conversions and convert the expression to size_t.
16588   auto ApplyArgumentConversions = [this](Expr *E) {
16589     ExprResult Conv = DefaultLvalueConversion(E);
16590     if (Conv.isInvalid())
16591       return Conv;
16592 
16593     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16594   };
16595 
16596   // Apply conversion to row and column expressions.
16597   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16598   if (!RowsConv.isInvalid()) {
16599     RowsExpr = RowsConv.get();
16600     TheCall->setArg(1, RowsExpr);
16601   } else
16602     RowsExpr = nullptr;
16603 
16604   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16605   if (!ColumnsConv.isInvalid()) {
16606     ColumnsExpr = ColumnsConv.get();
16607     TheCall->setArg(2, ColumnsExpr);
16608   } else
16609     ColumnsExpr = nullptr;
16610 
16611   // If any any part of the result matrix type is still pending, just use
16612   // Context.DependentTy, until all parts are resolved.
16613   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16614       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16615     TheCall->setType(Context.DependentTy);
16616     return CallResult;
16617   }
16618 
16619   // Check row and column dimenions.
16620   llvm::Optional<unsigned> MaybeRows;
16621   if (RowsExpr)
16622     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16623 
16624   llvm::Optional<unsigned> MaybeColumns;
16625   if (ColumnsExpr)
16626     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16627 
16628   // Check stride argument.
16629   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16630   if (StrideConv.isInvalid())
16631     return ExprError();
16632   StrideExpr = StrideConv.get();
16633   TheCall->setArg(3, StrideExpr);
16634 
16635   if (MaybeRows) {
16636     if (Optional<llvm::APSInt> Value =
16637             StrideExpr->getIntegerConstantExpr(Context)) {
16638       uint64_t Stride = Value->getZExtValue();
16639       if (Stride < *MaybeRows) {
16640         Diag(StrideExpr->getBeginLoc(),
16641              diag::err_builtin_matrix_stride_too_small);
16642         ArgError = true;
16643       }
16644     }
16645   }
16646 
16647   if (ArgError || !MaybeRows || !MaybeColumns)
16648     return ExprError();
16649 
16650   TheCall->setType(
16651       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16652   return CallResult;
16653 }
16654 
16655 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16656                                                    ExprResult CallResult) {
16657   if (checkArgCount(*this, TheCall, 3))
16658     return ExprError();
16659 
16660   unsigned PtrArgIdx = 1;
16661   Expr *MatrixExpr = TheCall->getArg(0);
16662   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16663   Expr *StrideExpr = TheCall->getArg(2);
16664 
16665   bool ArgError = false;
16666 
16667   {
16668     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16669     if (MatrixConv.isInvalid())
16670       return MatrixConv;
16671     MatrixExpr = MatrixConv.get();
16672     TheCall->setArg(0, MatrixExpr);
16673   }
16674   if (MatrixExpr->isTypeDependent()) {
16675     TheCall->setType(Context.DependentTy);
16676     return TheCall;
16677   }
16678 
16679   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16680   if (!MatrixTy) {
16681     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16682     ArgError = true;
16683   }
16684 
16685   {
16686     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16687     if (PtrConv.isInvalid())
16688       return PtrConv;
16689     PtrExpr = PtrConv.get();
16690     TheCall->setArg(1, PtrExpr);
16691     if (PtrExpr->isTypeDependent()) {
16692       TheCall->setType(Context.DependentTy);
16693       return TheCall;
16694     }
16695   }
16696 
16697   // Check pointer argument.
16698   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16699   if (!PtrTy) {
16700     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16701         << PtrArgIdx + 1;
16702     ArgError = true;
16703   } else {
16704     QualType ElementTy = PtrTy->getPointeeType();
16705     if (ElementTy.isConstQualified()) {
16706       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16707       ArgError = true;
16708     }
16709     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16710     if (MatrixTy &&
16711         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16712       Diag(PtrExpr->getBeginLoc(),
16713            diag::err_builtin_matrix_pointer_arg_mismatch)
16714           << ElementTy << MatrixTy->getElementType();
16715       ArgError = true;
16716     }
16717   }
16718 
16719   // Apply default Lvalue conversions and convert the stride expression to
16720   // size_t.
16721   {
16722     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16723     if (StrideConv.isInvalid())
16724       return StrideConv;
16725 
16726     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16727     if (StrideConv.isInvalid())
16728       return StrideConv;
16729     StrideExpr = StrideConv.get();
16730     TheCall->setArg(2, StrideExpr);
16731   }
16732 
16733   // Check stride argument.
16734   if (MatrixTy) {
16735     if (Optional<llvm::APSInt> Value =
16736             StrideExpr->getIntegerConstantExpr(Context)) {
16737       uint64_t Stride = Value->getZExtValue();
16738       if (Stride < MatrixTy->getNumRows()) {
16739         Diag(StrideExpr->getBeginLoc(),
16740              diag::err_builtin_matrix_stride_too_small);
16741         ArgError = true;
16742       }
16743     }
16744   }
16745 
16746   if (ArgError)
16747     return ExprError();
16748 
16749   return CallResult;
16750 }
16751 
16752 /// \brief Enforce the bounds of a TCB
16753 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16754 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16755 /// and enforce_tcb_leaf attributes.
16756 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16757                                const FunctionDecl *Callee) {
16758   const FunctionDecl *Caller = getCurFunctionDecl();
16759 
16760   // Calls to builtins are not enforced.
16761   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16762       Callee->getBuiltinID() != 0)
16763     return;
16764 
16765   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16766   // all TCBs the callee is a part of.
16767   llvm::StringSet<> CalleeTCBs;
16768   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16769            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16770   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16771            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16772 
16773   // Go through the TCBs the caller is a part of and emit warnings if Caller
16774   // is in a TCB that the Callee is not.
16775   for_each(
16776       Caller->specific_attrs<EnforceTCBAttr>(),
16777       [&](const auto *A) {
16778         StringRef CallerTCB = A->getTCBName();
16779         if (CalleeTCBs.count(CallerTCB) == 0) {
16780           this->Diag(TheCall->getExprLoc(),
16781                      diag::warn_tcb_enforcement_violation) << Callee
16782                                                            << CallerTCB;
16783         }
16784       });
16785 }
16786